import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JButtonTest {
public static void main(String[] args) {
JFrame f = new JFrame("JButton基本用法");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ButtonDemo());
f.setSize(600,200);
f.setVisible(true);
}
}
class ButtonDemo extends JPanel implements ActionListener{
JTextField jtf;
public ButtonDemo(){
try{
SwingUtilities.invokeAndWait(new Runnable(){//Swing 实用方法的集合。
//invokeAndWait() 导致 doRun.run() 在 AWT 事件指派线程上同步执行。
public void run(){
makeGUI();
}
});
}catch(Exception e){
e.printStackTrace();
}
}
private void makeGUI(){
setLayout(new FlowLayout());
ImageIcon dz = new ImageIcon("E:\\java\\Test\\icon\\dz.jpg");
JButton jb = new JButton(dz);
jb.setActionCommand("地址");
jb.addActionListener(this);
add(jb);
ImageIcon ht = new ImageIcon("E:\\java\\Test\\icon\\ht.jpg");
jb = new JButton(ht);
jb.setActionCommand("后退");
jb.addActionListener(this);
add(jb);
ImageIcon qj = new ImageIcon("E:\\java\\Test\\icon\\qj.jpg");
jb = new JButton(qj);
jb.setActionCommand("前进");
jb.addActionListener(this);
add(jb);
ImageIcon sx = new ImageIcon("E:\\java\\Test\\icon\\sx.jpg");
jb = new JButton(sx);
jb.setActionCommand("刷新");
jb.addActionListener(this);
add(jb);
jtf = new JTextField(15);
add(jtf);
}
public void actionPerformed(ActionEvent e) {
jtf.setText(e.getActionCommand());
}
}