在按钮上画图像分为两种:一种是使用现有的图像用ImageIcon 命令生成并添加到JButton(ImageIcon)中即可完成,这是一种简单的绘制方式。代码如下:
import javax.swing.*;
import java.awt.*;
public class TestImageIcon extends JFrame{
private ImageIcon usIcon = new ImageIcon("E://p/us1.jpg");
private ImageIcon myIcon = new ImageIcon("E://p/a.jpg");
private ImageIcon frIcon = new ImageIcon("E://p/zero.jpg");
private ImageIcon ukIcon = new ImageIcon("E://p/pi.png");
public TestImageIcon() {
setLayout(new GridLayout(1,4,5,5));
add(new JLabel(usIcon));
add(new JLabel(myIcon));
add(new JButton(frIcon));
add(new JButton(ukIcon));
}
public static void main(String[] args)
{
TestImageIcon frame = new TestImageIcon();
frame.setTitle("TestImageIcon");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}
结果如图:
第二种对于初学者相对比较复杂:是在按钮上画一些基本图形并显示按钮上的文本信息;
对于这种情况需要对JButton类进行扩展,然后使用Graphics类中的画图功能:(draw对应的画图函数)进行绘制,然后在绘制字符串(这两个没有必要的前后关系,谁前谁后都可以)。然后添加到JFrame框架中,如果不添加将什么也不会显示。
对应的代码如下:
import javax.swing.*;
import java.awt.*;
public class Exercise13_2 extends JFrame{
public Exercise13_2() {
setLayout(new GridLayout(1,2,10,10 ));
add(new OverButton(OverButton.OK));
add(new OverButton(OverButton.CANCEL));
}
public static void main(String[] args)
{
Exercise13_2 frame = new Exercise13_2();
frame.setTitle("Exercise13_2");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class OverButton extends JButton{
public static final String OK = "ok";
public static final String CANCEL = "Cancel";
private String type = null;
public OverButton() {
}
public OverButton(String str) {
this.type = str;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = getWidth();
int y = getHeight();
int h = (int)(0.7*getHeight());
int w = (int)(0.7*getWidth());
FontMetrics fm = g.getFontMetrics();
int stringOk = fm.stringWidth("OK");
int stringAscent = fm.getAscent();
int stringCancel = fm.stringWidth("CANCEL");
switch(type) {
case OK:
//JButton jbok = new JButton("OK");
//add(jbok);
g.drawArc(0,0,x,y, 0, 360);
g.drawString("OK", (int)(x/2-stringOk/2), (int)(y/2+stringAscent/2));
break;
case CANCEL:
g.drawArc((int)(0.1*x), (int)(0.1*y), w, h, 0, 360);
g.drawString("Cancel", (int)(x/2-stringCancel/2), (int)(y/2+stringAscent/2));
break;
}
结果如图所示: