有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    通过不调用paintComponentsuper方法,您已经打破了绘制链

    @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 SwingPerforming Custom Painting了解有关Swing中绘画如何工作的更多细节