【问题标题】:how to override paintComponent method and use with JPanel [duplicate]如何覆盖paintComponent方法并与JPanel一起使用[重复]
【发布时间】:2018-02-02 15:49:23
【问题描述】:

我已经覆盖paintComponents 方法,但是当我使用它并运行我的程序时,它不会显示任何圆圈和线条。最近frakcool说不是paintComponents方法,是paintComponent方法。我发现了,但我没有得到任何paintComponent 方法。

这张图表明我没有任何paintComponent方法:

代码在这里。

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SecondActivity frame = new SecondActivity();
                frame.setBackground(Color.WHITE);
                frame.paintComponents(null);
              //  frame.paint(null);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

@Override
public void paintComponents(Graphics g) {
    // TODO Auto-generated method stub
    super.paintComponents(g);
    Graphics2D g2d = (Graphics2D) g;

    drawCircle(g2d,centerX,centerY,r);
    drawLineAzim(g2d);
    drawLineEle(g2d);

}

【问题讨论】:

  • 正如我在this comment 中所说并在我对您其他问题的回答中显示的那样,您需要覆盖paintComponent() 而不是paintComponentS()。该方法属于JPanel,这就是我扩展它的原因。
  • (1-) recently frakcool said it is not paintComponents method, it is paintComponent method. - 那你为什么还在执行错误的方法???您甚至使用paintComponent(...) 方法在论坛中搜索其他示例???
  • 如需更好的帮助,请尽快(重新)阅读minimal reproducible example 指南
  • 但是我无法获取paintComponent方法,请帮助。我应该去哪里找呢?

标签: java swing jpanel paintcomponent


【解决方案1】:

您覆盖了错误的方法。去掉方法名称末尾的“s”。你需要覆盖paintComponent(...)

但是,您还需要覆盖JPanelpaintComponent(...) 方法,您不能只是将方法添加到您的类中并期望它起作用。这是 Java 101。

Custom Painting 上的 Swing 教程中的工作示例开始

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2018-03-18
    • 2023-03-20
    • 2017-01-08
    • 2012-02-27
    • 2021-06-21
    • 2015-11-30
    • 2018-08-15
    • 2012-02-16
    相关资源
    最近更新 更多