Draw lines on jpanel

2019-07-18 12:04发布

问题:

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?

回答1:

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.