Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Add the same JComponent in more than one JPanel

843806Sep 1 2008 — edited Sep 1 2008
Hello!

I'm making a simple drawing application where the user can draw common shapes, move and delete them. However, I'm trying to make two windows view/observe the same "picture". So all shapes added, moved or removed in the picture will happen in both places. My problem seems to be a restriction in Swing; when I add the same shape (same reference) to two different JPanels, only one of the JPanels draw the shape. However if I copy the shape (different references) and add the copy to the other JPanel it gets drawn. This code/application will demonstrate the problem:
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;

public class Square extends JComponent
{
	protected void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		
		int x = 0;
		int y = 0;
		int width = this.getWidth();
		int height = this.getHeight();
		
		g.setColor(Color.RED);		
		g.fillRect(x, y, width, height);
	}
}
import javax.swing.*;

public class SwingHelp 
{
	public static void main(String[] args) 
	{
		JFrame frame1 = new JFrame("1");
		JFrame frame2 = new JFrame("2");
		JPanel panel1 = new JPanel();
		JPanel panel2 = new JPanel();
		
		Square mySquare = new Square();
		mySquare.setBounds(50, 50, 75, 75);
		
		panel1.setLayout(null);
		panel2.setLayout(null);
		
		panel1.add(mySquare);		
		panel2.add(mySquare);
		
		frame1.add(panel1);
		frame2.add(panel2);
		
		frame1.setSize(500, 500);
		frame2.setSize(500, 500);
		
		frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame1.setVisible(true);
		frame2.setVisible(true);
	}
}
Is there any setting or workaround to get the desired effect I want? Any help is appreciated :-)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 29 2008
Added on Sep 1 2008
4 comments
98 views