我不確定你為啥一定要這樣做,至少在業界customized jbutton很常見,
都是用繼承的方式..因為
1.不overwrite paint(g)的話下一次awt thread 重畫gui的時候你的oval就會不見
除非你overwrite upper level component的paint method
2.replace jbutton裡面的g的話就表示你要自己全部重新實作button的graphics,而
且必須算offset
你的需求可以用繼承加上factory pattern來作。下面附上sample code for you
有問題的話請寫站內信,我在美東上班沒辦法接水球
※ 引述《lovesneakers (sneakers)》之銘言:
: 推 willieliao:err..有一點搞不懂你的意思,可不可以說一下你要這樣的 04/25 04:44
: 推 willieliao:目的是? 04/25 04:46
: 我想這麼做的目的是
: JButton 上面的 Graphics 想由別隻程式來提供
: 假如我想產生一個 button 上面畫了魚
: 或是想產生一個 button 上面畫了圓形之類的
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
public class test {
public static void main(String[] args) {
JFrame f = new JFrame();
Box b = Box.createHorizontalBox();
b.add(MyButtonFactory.createMyButton("Oval", EnumButtonType.OVAL));
b.add(MyButtonFactory.createMyButton("Line", EnumButtonType.LINE));
f.getContentPane().add(b);
f.pack();
f.show();
}
public static class MyButtonFactory {
public static MyButton createMyButton(String title, int enumButtonType) {
return new MyButton(title, enumButtonType);
}
private static class MyButton extends JButton {
private int enumButtonType;
public void paint(Graphics g) {
super.paint(g);
paintExtra(g, enumButtonType);
}
public MyButton(String label, int enumButtonType) {
super(label);
this.enumButtonType = enumButtonType;
}
private void paintExtra(Graphics g, int enumButtonType) {
switch (enumButtonType) {
case EnumButtonType.OVAL:
g.setColor(Color.BLUE);
g.fillOval(0, 0, 100, 100);
break;
case EnumButtonType.LINE:
g.setColor(Color.RED);
g.drawLine(0, 0, 100, 100);
}
} // you can make this a separate class to provide drawing function
}
}
public interface EnumButtonType {
public static final int OVAL = 1;
public static final int LINE = 2;
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 98.204.128.203