我正在学习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
方法。你能纠正我吗?我在哪里犯错。我的整个实现是错误的吗?
Color c = new Color(255,0, 0); // Define your color in RGB
drawPanel.setBackground(c); // Set your background on button clicked