动作侦听器未响应Java中的单击

时间:2019-04-05 17:08:01

标签: java

当我单击按钮时什么也没有发生。这是代码。

我如何理解这个问题?我很快就做出来,以解决jpanel背景颜色的变化,但是当我用一条消息对其进行测试时,动作监听器无法正常工作。

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


public class Changcolorbtns extends JFrame implements ActionListener{
    JLabel lbl;
    JPanel p1,p2,p3,p4;
    JButton btn1,btn2,btn3,btn4;
public Changcolorbtns() {
    //JFrame 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLocationRelativeTo(null);
     setSize(500,400);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(null);

    // declaring 
    JButton btn1 = new JButton("Red");
    JButton btn2 = new JButton("Blue");
    JButton btn3 = new JButton("Black");
    JButton btn4 = new JButton("Green");
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();
    JPanel p4 = new JPanel();
   JLabel lbl = new JLabel("hit me");
    //settingn location and size
    lbl.setBounds(60,60,60,60);
    p1.setBounds(0,0,250,250);
    p2.setBounds(0,250,250,250);
    p3.setBounds(250,0,250,250);
    p4.setBounds(250,250,250,250);
    btn1.setBounds(50,50,100,100);
    btn1.setVisible(true);
    btn2.setBounds(250,50,100,100);
    btn3.setBounds(50,250,100,100);
    btn4.setBounds(250,250,100,100);
     //adding 2 jpane
    p1.add(btn1);
    p2.add(btn2);
    p3.add(btn3);
    p4.add(btn4);

    //setting jpanel color
    p1.setBackground(Color.RED);
    p2.setBackground(Color.RED);
    p3.setBackground(Color.RED);
    p4.setBackground(Color.RED);
    //adding to jframe
    add(p1);
    add(p2);
    add(p3);
    add(p4);


    //adding action listeners
   btn1.addActionListener(this);

    //setting visible

    setVisible(true);
}

 @Override
    public void actionPerformed(ActionEvent e){

       if(e.getSource()==btn1){
           JOptionPane.showMessageDialog(null, "hi");
       }
    }
    public static void main(String[] args) {
         new Changcolorbtns();
    }
}

0 个答案:

没有答案