【问题标题】:Not sure if I am overriding paintComponent() correctly [duplicate]不确定我是否正确地覆盖了paintComponent() [重复]
【发布时间】:2020-04-26 16:11:14
【问题描述】:

对于想要了解更多关于 awt/swing 并且没有经常使用 awt/swing 的人,我不确定我是否正确地这样做了。我想做的是用一种方法覆盖paintComponent(),该方法创建6个圆圈,这些圆圈应该在某些位置添加到inner面板(x + 50y + 50仅用于测试目的)。我浏览了包括这个网站在内的在线资源,但圆圈似乎仍然没有出现。我确定我做错了什么,但我不确定是什么。提示和/或信息链接将不胜感激

这是我的课程,目标是创建圆圈并将其添加到面板:

public class TimeUnit extends JPanel {

private static final long serialVersionUID = 1L;
private int x = -50;
private int y = -50;

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    ArrayList<Graphics> list = new ArrayList<Graphics>(6);
    for (int i = 0; i < 6; i++) {
        list.add(g.create());
    }

    for (Graphics r : list) {
        r.drawOval(x + 50, y + 50, 50, 50);

    }

}

这就是它被合并到我的主程序中的地方:

           JPanel inner = new JPanel();
           inner.setLayout(null);
           inner.setSize(325, 570);
           inner.setBackground(null);
           inner.setLocation(500, 350);
           inner.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK));
           inner.setVisible(true);
           inner.repaint();



           //----Containers to Panel/Panel to Frame---------
           Panel.add(inner);
           Panel.add(labelOne);
           Panel.add(labelTwo);
           Panel.add(labelFour);
           Panel.add(labelEight);
           Panel.add(timeLabel);
           frame.add(Panel, BorderLayout.CENTER);   

【问题讨论】:

  • paintComponent 应该只绘画,它不应该改变它正在绘画的对象。看到这个answer

标签: java swing awt


【解决方案1】:

您应该使用传入的Graphics g 来绘制椭圆,而不是创建新的Graphics 对象:

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i = 0; i < 6; i++) {
        g.drawOval(x + 50*i, y + 50*i, 50, 50);
    }
}

【讨论】:

    猜你喜欢
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多