【问题标题】:Java Swing, can't see the errorJava Swing,看不到错误
【发布时间】:2011-11-08 16:43:38
【问题描述】:

我遇到了一个非常奇怪的问题,我有一个自定义的 JPanel,我想画一个圆圈,但什么也没发生……这是我的来源,希望有人看到错误,我找不到。

import javax.swing.JPanel;

public class CircleView extends JPanel {

public CircleView() {}

@Override
    public void paintComponent(Graphics g) {
    g.setColor(Color.red);
    g.drawOval(10, 10, 50, 50);
    }
}

【问题讨论】:

  • 如何测试CircleView
  • 我将它添加到 layeredPane。我可以向其中添加图像,但是添加 CircleView 后,什么也没有发生

标签: java swing graphics jpanel paintcomponent


【解决方案1】:

这根本不是真的

Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
        at KondorExport.Util.Helping.CustomComponent12.<init>(CustomComponent12.java:19)
        at KondorExport.Util.Helping.CustomComponent12$1.run(CustomComponent12.java:37)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.RuntimeException: Uncompilable source code - class CircleView is public, should be declared in a file named CircleView.java
        at KondorExport.Util.Helping.CircleView.<clinit>(CustomComponent12.java:44)
        ... 10 more

1) 移除构造函数

2) 添加super.paintComponent(g);

这个可以跑

class CircleView extends JPanel {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }

    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.red);
        g.drawOval(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}

【讨论】:

  • 我读了一些howtos,我认为我写的已经足够了,会试试^^
  • 似乎,该类工作正常。将其添加到 layeredPane 是问题所在...
【解决方案2】:

这是因为您的组件没有尺寸,因此@mKorbel 提供的 sscce 在定义组件的首选尺寸时使用了一些“神奇”的尺寸。

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 2016-07-11
    • 2020-12-13
    • 1970-01-01
    • 2011-06-09
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多