下面以點擊按鈕后改變窗口背景色為例:

成都創(chuàng)新互聯(lián)-專業(yè)網站定制、快速模板網站建設、高性價比山海關網站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式山海關網站制作公司更省心,省錢,快速模板網站建設找我們,業(yè)務覆蓋山海關地區(qū)。費用合理售后完善,10余年實體公司更值得信賴。
import?java.awt.*;
import?java.awt.event.*;
public?class?MyAWTDemo?extends?Frame{
public?MyAWTDemo()?{
Button?bt?=?new?Button("=點擊按鈕,改變背景色=");
//給按鈕添加響應代碼
bt.addActionListener(new?ActionListener()?{
public?void?actionPerformed(ActionEvent?e)?{
//這里寫,你想點擊按鈕后,執(zhí)行的代碼
setBackground(new?Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));
}
});
add(bt);
setLayout(new?FlowLayout());
setTitle("窗口標題");
setSize(260,?100);
setLocationRelativeTo(null);
setVisible(true);
//給窗口添加一個響應代碼,當我們點擊窗口右上角的關閉按鈕時,系統(tǒng)就退出JVM虛擬機
this.addWindowListener(new?WindowAdapter()?{
public?void?windowClosing(WindowEvent?e)?{
System.exit(0);//系統(tǒng)退出
}
});
}
public?static?void?main(String[]?args)?{
new?MyAWTDemo();
}
}
效果圖
經調試,已經解決:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI1 extends JFrame {
private JButton b1 = new JButton("button1");
private JButton b2 = new JButton("button2");
private JTextField txt = new JTextField(10);
private ActionListener bl = new ActionListener() { // 定義一個內部類
public void actionPerformed(ActionEvent e) {
String name = ((JButton) e.getSource()).getText();
txt.setText(name);
}
};
public GUI1(int a, int b) {
setSize(a, b);
b1.addActionListener(bl);
b2.addActionListener(bl);
setLayout(new FlowLayout());
add(b1);
add(b2);
add(txt);
}
public static void main(String[] args) {
GUI1 s = new GUI1(200, 110);
s.setDefaultCloseOperation(EXIT_ON_CLOSE);
s.setLocationRelativeTo(null);
s.setVisible(true);
}
}
addActionListener的參數是ActionListener你的this是Applet。當然不對啦。
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Jsq extends Applet implements ActionListener{
Button b1;
public void init() {
Button b1=new Button("+");
b1.addActionListener(this);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
System.out.println("you click the button");
}
}
文章名稱:java中按鈕響應代碼,html按鈕響應
分享路徑:http://chinadenli.net/article27/dsgepjj.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、用戶體驗、網站維護、網站導航、網站設計、動態(tài)網站
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)