代码之家  ›  专栏  ›  技术社区  ›  Tanzeel

如何使用ActionListener更改JPanel的颜色

  •  0
  • Tanzeel  · 技术社区  · 5 年前

    我正在学习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 方法未被调用。你能纠正我的错误吗。我的整个实施是错误的吗?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Landstalker    5 年前

    paintComponent 必须是 protected (参见 here ).

    将代码更改为:

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

    结果:

    enter image description here