在jpanel上画线 [英] Draw lines on jpanel

查看:144
本文介绍了在jpanel上画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使其像不在jframe上而是在jpanel上绘制标尺(带有90度角刻度线的线).

所以我尝试了:

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

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

f.add(ff);
...

但是我失败了. :( 怎么做?

解决方案

您可以简单地为ff覆盖paintComponent(Graphics g){}并在该方法中进行绘制.

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.
    }
};

在这种情况下,您不需要此...

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

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

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

So I tried:

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

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

f.add(ff);
...

but I failed. :( How to?

解决方案

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

i.e.

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.

这篇关于在jpanel上画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆