java面板不会显示在窗口中
我试图在选中jcheckbox hat且矩形可见的情况下启动程序,然后当取消选中复选框时,矩形消失,并在再次选中复选框时重新绘制。当我运行程序并选中该复选框时,另一个复选框会出现在框架的左侧
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class Head extends JPanel {
JCheckBox hat;
public Head() {
hat = new JCheckBox("Hat");
hat.setSelected(true);
hat.addItemListener(new CheckSelection());
add(hat);
}
class CheckSelection implements ItemListener {
public void itemStateChanged(ItemEvent ie) {
repaint();
}
}
public void paintComponent(Graphics g) {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
}
}
public static void main(String[] args) {
Head head = new Head();
JFrame f = new JFrame();
f.add(head);
f.setSize(400, 400);
//f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
# 1 楼答案
通过不调用
paintComponent
的super
方法,您已经打破了绘制链Graphics
上下文是组件之间的共享资源,paintComponent
的工作之一是为Graphics
绘制做好准备,通常是用组件的背景色填充它。因此,未能调用super.paintComponent
意味着之前在Graphics
上下文中绘制的内容仍然存在参见Painting in AWT and Swing和Performing Custom Painting了解有关Swing中绘画如何工作的更多细节