簡體   English   中英

ActionListener在JButton上不起作用

[英]ActionListener not working on JButton

我編寫了一個代碼,以在具有網格布局的框架上的三個面板中顯示三個按鈕。 目的是-單擊按鈕時更改按鈕的顏色-最初所有3個按鈕均為黑色

該代碼運行正常,除了按鈕的顏色未更改
點擊。 任何人都可以指出問題或對其進行調試。

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class gui extends JFrame implements ActionListener {

    JPanel p1, p2, p3;
    JButton b1, b2, b3;

    public gui() {
        setLayout(new GridLayout(3, 1));
        JPanel p1 = new JPanel(new GridLayout(1, 1));
        JPanel p2 = new JPanel(new GridLayout(1, 1));
        JPanel p3 = new JPanel(new GridLayout(1, 1));
        JButton b1 = new JButton();
        JButton b2 = new JButton();
        JButton b3 = new JButton();
        b1.setBackground(Color.BLACK);
        b2.setBackground(Color.BLACK);
        b3.setBackground(Color.BLACK);
        b1.addActionListener(this);
        p1.add(b1);
        b2.addActionListener(this);
        p2.add(b2);
        b3.addActionListener(this);
        p3.add(b3);
        add(p1);
        add(p2);
        add(p3);
    }

    public void actionPerformed(ActionEvent e) //function to handle click
    {
        if (e.getSource() == b1) {
            b1.setBackground(Color.RED);
        } else if (e.getSource() == b2) {
            b1.setBackground(Color.YELLOW);
        } else if (e.getSource() == b3) {
            b3.setBackground(Color.BLUE);
        }
    }

    public static void main(String[] args) {
        gui ob1 = new gui();
        ob1.setSize(1000, 500);
        ob1.setLocation(100, 100);
        ob1.setVisible(true);
        ob1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
  1. 您必須使用[也適用於面板]來初始化按鈕

      b1 = new JButton(); b2 = new JButton(); b3 = new JButton(); 

    因為您正在創建隱藏全局變量的局部變量

     JButton b1 = new JButton();//local variables JButton b2 = new JButton(); JButton b3 = new JButton(); 
  2. 在第二個if條件中,您必須更改b2的顏色而不是b1

      else if(e.getSource()==b2){ //b1.setBackground(Color.YELLOW); b2.setBackground(Color.YELLOW); } 
  3. 始終使用.equals()而不是==來比較對象

      e.getSource().equals(b1) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM