java 在 jpanel 上画线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14164392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:18:43  来源:igfitidea点击:

Draw lines on jpanel

javaswingjpaneldrawgraphics2d

提问by user1949713

I want to make it like Draw a ruler (line with tick marks at 90 degree angle)just not on jframe but on jpanel.

我想让它像绘制标尺(带有 90 度角的刻度线)一样,而不是在 jframe 上,而是在 jpanel 上。

So I tried:

所以我试过:

JFrame f = new JFrame();
JPanel ff = new JPanel();

ff.add(new JComponent() {
...
});

f.add(ff);
...

but I failed. :( How to?

但我失败了。:( 如何?

回答by Mike

You can simply override paintComponent(Graphics g){}for ff and draw your within that method.

您可以简单地覆盖paintComponent(Graphics g){}ff 并在该方法中绘制您的内容。

i.e.

IE

JPanel ff = new JPanel(){ 
    public void paintComponent(Graphics g){
        // Draw what you want to appear on your JPanel here.
        // g.drawLine(blah blah blah), etc.
    }
};

In which case you have no need for this...

在这种情况下,你不需要这个......

ff.add(new JComponent() {
    ...
});

You don't need this generic component unless you want to implement the custom component as suggest in the link you provided. In the case that you do want to create such a custom component, then you don't need ff, since a JFrame is already a container that can hold your component.

除非您想按照您提供的链接中的建议实现自定义组件,否则您不需要此通用组件。如果您确实想要创建这样的自定义组件,则不需要ff,因为 JFrame 已经是可以容纳您的组件的容器。