作者willieliao (Willie Liao)
看板java
标题Re: [问题] JButton getGraphics
时间Sat Apr 26 01:55:44 2008
我不确定你为啥一定要这样做,至少在业界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