我试图在选择 jcheckbox 帽子且矩形可见的情况下启动程序,然后当取消选择复选框时矩形消失,并在再次选择复选框时重新绘制。当我运行程序并选中该框时,另一个复选框会出现在框架左侧。
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);
}
}
最佳答案
您没有调用 paintComponent
的 super
方法,从而破坏了绘制链
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(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);
} else {
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);
}
}
Graphics
上下文是组件之间的共享资源,paintComponent
的工作之一是准备用于绘制的 Graphics
,通常通过用组件的背景颜色填充它。因此,未能调用 super.paintComponent
意味着之前绘制到 Graphics
上下文中的内容仍将存在
参见Painting in AWT and Swing和 Performing Custom Painting有关 Swing 中绘画工作原理的更多详细信息
关于java - 面板不会显示在窗口中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882251/