效果如图:
[img]http://dl2.iteye.com/upload/attachment/0093/8189/4fe35173-8ff3-3e91-9e5b-915fe5ce68f5.jpg[/img]
[img]http://dl2.iteye.com/upload/attachment/0093/8189/4fe35173-8ff3-3e91-9e5b-915fe5ce68f5.jpg[/img]
public abstract class JButtonTest<T> extends JTextField{
private JButton choose = new JButton(){
//打印容器
@Override
public void paint(Graphics g) {
super.paint(g);
int width = 3;
int height = 3;
Rectangle rect = g.getClipBounds();//返回当前剪贴区域边界矩形
int x = rect.width/3;
int y = rect.height/2;
for(int i=0;i<3;){
g.fillOval(++i * x, y, width, height);//使用当前颜色填充外接指定矩形框的椭圆
}
}
//容器首选大小
@Override
public Dimension getPreferredSize() {
Dimension dimension = JButtonTest.super.getPreferredSize();
dimension.height -= 6;
dimension.width = dimension.height;
return dimension;
}
};
private JButtonTest<T> self = this;
public JButtonTest(int column){
super(column);
initButtonTest();
}
private void initButtonTest(){
choose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionevent) {
JButtonTest.this.handleClick(self);
}
});
//如果没有这句话,按钮无法显示,原因是默认覆盖
this.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0));
}
//JComponent通知此组件它现在已有了一个父组件
@Override
public void addNotify() {
super.addNotify();
add(choose);//Container中方法将指定组件追加到此容器的尾部
}
public abstract void handleClick(JButtonTest jbuttonTest);
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButtonTest button = new JButtonTest(15){
@Override
public void handleClick(JButtonTest jbuttonTest) {
JOptionPane.showMessageDialog(this, "ddd");
jbuttonTest.setText("ddd");
}
};
panel.add(button);
frame.add(panel);
frame.setSize(500, 300);
frame.setVisible(true);
}
}