java初学者请教在JFrame中显示JPanel对象问题,为什么只能显示BUTTON,不能显示圆
代码如下:ChangeBallColorTest.java代码:
import java.awt.Color;
import javax.swing.*;
public class ChangeBallColorTest {
public static void main(String[] args) {
ChangeBallColorFrame cbcf = new ChangeBallColorFrame();
cbcf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cbcf.setLocation(300,200);
cbcf.setTitle("ChangeBallColor");
cbcf.setVisible(true);
}
}
ChangeBallColorFrame.java代码:
import java.awt.*;
import javax.swing.*;
class ChangeBallColorFrame extends JFrame {
public ChangeBallColorFrame() {
JButton cbcb1 = new JButton("red");
JButton cbcb2 = new JButton("green");
ChangeBallColorPanel cbcp = new ChangeBallColorPanel();
setLayout(null);
setSize(300,400);
setBackground(Color.white);
cbcb1.setBackground(Color.red);
cbcb1.setBounds(160, 20, 75, 30);
add(cbcb1);
cbcb2.setBackground(Color.green);
cbcb2.setBounds(70, 20, 75, 30);
add(cbcb2);
this.getContentPane().add(cbcp);
}
}
ChangeBallColorPanel.java代码:
import java.awt.*;
import javax.swing.*;
class ChangeBallColorPanel extends JPanel{
public void paintComponents(Graphics g) {
super.paintComponents(g);
Graphics g1 = (Graphics) g;
Color c = g1.getColor();
g1.setColor(Color.red);
g1.fillOval(120, 150, 20, 20);
g1.setColor(c);
}
}