Java6学习笔记12——利用Swing制作带有图标的按钮

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class IconButton extends JFrame implements ActionListener {
public static void main(String arg[]) {
new IconButton();
}
public IconButton() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();
setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
JButton button;
Dimension size;

Container pane = getContentPane();
pane.setLayout(null);

Insets insets = pane.getInsets();

ImageIcon imageicon = new ImageIcon("current.png");//建立一个图标对象
button = new JButton(imageicon);//建立按钮时加上图标
size = button.getPreferredSize();
int x = 25 + insets.left;
int y = 15 + insets.top;
button.setBounds(x,y,size.width,size.height);
pane.add(button);

button = new JButton("Exit");
y += size.height + 15;
size = button.getPreferredSize();
button.setBounds(x,y,size.width,size.height);
button.addActionListener(this);
pane.add(button);

int width = 300 + insets.left + insets.right;
int height = y + size.height + 40 + insets.bottom;
setSize(width,height);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
}
}
}

你可能感兴趣的:(java,swing)