user
user

Reputation: 25

Java: draw line on JPanel inside JLayeredPane

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(new Dimension(500,500));
JLayeredPane layers = new JLayeredPane();
JPanel p1,p2;

p1=new JPanel();
p2=new JPanel();


p1.setBounds(0,0,200,200);
p2.setBounds(0,0,200,200);

p1.setOpaque(false);
p2.setOpaque(false);

layers.setLayer(p1,new Integer(0));
layers.setLayer(p2,new Integer(1));

layers.add(p1);
layers.add(p2);

f.add(layers);
f.setVisible(true);


Graphics2D gr = (Graphics2D) p2.getGraphics();
gr.setColor(Color.BLACK);

gr.drawLine(10,10,20,20);

I am trying to draw on a JPanel inside a JLayeredPane, but nothing is drawn. If I add a component (a JButton) to either p1 or p2, it will be painted.

What is the correct way to draw inside a JLayeredPane?

Upvotes: 2

Views: 585

Answers (1)

Adam
Adam

Reputation: 36703

You cannot just draw to the graphics context externally, it is not persistent like you'd might expect. Instead you need to override JComponent.paintComponent(Graphics g) in the JPanel. Try this. Ideally you'd subclass JPanel as a separate class.

A good oracle tutorial is "Perform custom painting"

p2=new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D gr = (Graphics2D) g;
        gr.setColor(Color.BLACK);

        gr.drawLine(10,10,20,20)

    }

}

Upvotes: 2

Related Questions