import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sl14 extends JFrame{
JPanel jp=new JPanel();
JButton jb=new JButton();
int k=0;
public Sl14(){
JLabel j1=new JLabel();
JLabel j2=new JLabel();
j1.setText("創建面板快樂管理局");
j2.setText("創建2便簽");
j1.setVerticalAlignment(JLabel.CENTER);
j1.setHorizontalAlignment(JLabel.CENTER);
j1.setBounds(0,0,500,200);
j2.setBounds(100,100,500,200);
this.add(j1);
this.add(j2);
jb.setText("按鈕0次");
jb.setMnemonic('G');//設置“Alt+G”組合鍵起到單擊按鈕的作用
jp.add(jb);
jb.addActionListener(this);
this.add(jp);
Image i=this.getToolkit().getImage("a.jpg");
this.setIconImage(i);
this.setTitle("設計窗口標題");
this.setBounds(300,250,500,300);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
this.jb.setText("按鈕"+(++k)+"次");
}
public static void main(String[] args) {
Sl14 s=new Sl14();
}
}
直接在JFrame裡寫的話要在class那加上implements ActionListener,不過還是建議用匿名內部類或私有內部類