如何使用 ActionListener 更改 JPanel 的颜色

How to change color of JPanel with ActionListener

我正在学习 Java Applet 和 Swings 的基础知识。我正在尝试一个简单的代码。我想在单击按钮时更改面板的颜色。这是代码:

SimpleGui.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGui implements ActionListener {
    JFrame frame;
    JButton button;

    public static void main(String[] args) {
        SimpleGui gui = new SimpleGui();
        gui.go();
    }

    public void go() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        button = new JButton("changes colour");
        button.addActionListener(this);

        MyPanel drawPanel = new MyPanel();

        frame.getContentPane().add(BorderLayout.SOUTH,button);
        frame.getContentPane().add(BorderLayout.CENTER,drawPanel);

        frame.setSize(300, 300);
        frame.setVisible(true);
    }

    //event handling method
    public void actionPerformed(ActionEvent event) {
        frame.repaint();
        button.setText("color changed");
    }
}

class MyPanel extends JPanel {

    public void paintCompenent(Graphics g) {
        g.setColor(Color.green);
        g.fillRect(20, 50, 100, 100);
    }
}

我添加了一些println语句来调试,我发现paintComponent方法没有被调用。你能纠正我吗?我在哪里犯了错误。我的整个实现是错误的吗?

paintComponent 必须是 protected(参见 here)。

将您的代码更改为:

class MyPanel extends JPanel {
     protected void paintComponent(Graphics g) {
        g.setColor(Color.green);
        g.fillRect(20, 50, 100, 100);
    }
}  

结果: