Add the same JComponent in more than one JPanel

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 :-)

Here's a simple example. I have a program called RectangleDrawMaster that draws and displays rectangles on mouse drag and a program called RectangleDrawSlave that uses the master's "model" an ArrayList of ColorRect (objects that have rectangle coordinates and colors). So while both classes use different drawing JPanels, these JPanels share the same model and the images look the same.
ColorRect.java: holds color and rectangle data
import java.awt.Color;
import java.awt.geom.Rectangle2D;
class ColorRect
    private Color c;
    private Rectangle2D rect;
    ColorRect(Color c, Rectangle2D rect)
        this.c = c;
        this.rect = rect;
    public Color getColor()
        return c;
    public Rectangle2D getRect()
        return rect;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
import javax.swing.event.*;
public class RectangleDrawMaster
  private static final int COLOR_MIN = 0;
  private static final int COLOR_MAX = 255;
  private static final Dimension PANEL_SIZE = new Dimension(500, 500);
  //private BufferedImage bImage;
  private Point firstPoint;
  private Point lastPoint;
  private List<ColorRect> rectList = new ArrayList<ColorRect>();
  private Random random = new Random();
  private JPanel mainPanel = new JPanel();
  private List<ChangeListener> changeList = new ArrayList<ChangeListener>();
  private JPanel drawingPanel = new JPanel()
    @Override
    protected void paintComponent(Graphics g)
      super.paintComponent(g);
      panelDraw(g);
  public RectangleDrawMaster()
    drawingPanel.addMouseListener(new MyMouseListener());
    JButton clearBtn = new JButton("Clear");
    clearBtn.addActionListener(new ActionListener()
      @Override
      public void actionPerformed(ActionEvent e)
        clearAction();
    mainPanel.setPreferredSize(PANEL_SIZE);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(drawingPanel, BorderLayout.CENTER);
    mainPanel.add(clearBtn, BorderLayout.SOUTH);
  public void addChangeListener(ChangeListener cl)
    changeList.add(cl);
  public List<ColorRect> getRectList()
    return rectList;
  private void clearAction()
    rectList.clear();
    drawingPanel.repaint();
    invokeChangeListeners();
  private void invokeChangeListeners()
    ChangeEvent e = new ChangeEvent(this);
    for (ChangeListener cl : changeList)
      cl.stateChanged(e);
  private void panelDraw(Graphics g)
    Graphics2D g2 = (Graphics2D) g;
    for (ColorRect rect : rectList)
      g2.setColor(rect.getColor());
      g2.fill(rect.getRect());
  private Color randomColor()
    Color c = new Color(
        random.nextInt(COLOR_MAX - COLOR_MIN) + COLOR_MIN,
        random.nextInt(COLOR_MAX - COLOR_MIN) + COLOR_MIN,
        random.nextInt(COLOR_MAX - COLOR_MIN) + COLOR_MIN);
    return c;
  public JPanel getMainPanel()
    return mainPanel;
  private void drawRectangle()
    int width = Math.abs(firstPoint.x - lastPoint.x);
    int height = Math.abs(firstPoint.y - lastPoint.y);
    int x = Math.min(firstPoint.x, lastPoint.x);
    int y = Math.min(firstPoint.y, lastPoint.y);
    Rectangle2D rect = new Rectangle2D.Double(x, y, width, height);
    Color c = randomColor();
    rectList.add(new ColorRect(c, rect));
    drawingPanel.repaint();
    invokeChangeListeners();
  private class MyMouseListener extends MouseAdapter
    public void mousePressed(MouseEvent e)
      firstPoint = e.getPoint();
    @Override
    public void mouseReleased(MouseEvent e)
      lastPoint = e.getPoint();
      drawRectangle();
  private static void createAndShowUI()
    RectangleDrawMaster rectdraw = new RectangleDrawMaster();
    JFrame frame = new JFrame("Rect Draw Frame");
    frame.getContentPane().add(rectdraw.getMainPanel());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    final RectangleDrawSlave rectdraw2 = new RectangleDrawSlave(rectdraw.getRectList());
    rectdraw.addChangeListener(new ChangeListener()
      public void stateChanged(ChangeEvent e)
        rectdraw2.repaint();
    JDialog dialog = new JDialog(frame, "Rect Draw Dialog", false);
    dialog.getContentPane().add(rectdraw2.getMainPanel());
    dialog.pack();
    dialog.setVisible(true);
  public static void main(String[] args)
    java.awt.EventQueue.invokeLater(new Runnable()
      public void run()
        createAndShowUI();
import java.awt.*;
import java.util.List;
import javax.swing.JPanel;
public class RectangleDrawSlave
    private static final Dimension PANEL_SIZE = new Dimension(500, 500);
    //private BufferedImage bImage;
    private List<ColorRect> rectList;
    private JPanel mainPanel = new JPanel();
    private JPanel drawingPanel = new JPanel()
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            panelDraw(g);
    public RectangleDrawSlave(List<ColorRect> rectList)
        this.rectList = rectList;
        mainPanel.setPreferredSize(PANEL_SIZE);
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(drawingPanel, BorderLayout.CENTER);
    public void repaint()
      drawingPanel.repaint();
    private void panelDraw(Graphics g)
        Graphics2D g2 = (Graphics2D)g;
        for (ColorRect rect : rectList)
            g2.setColor(rect.getColor());
            g2.fill(rect.getRect());
    public JPanel getMainPanel()
        return mainPanel;
}

Similar Messages

  • Can I labled the same song to more than one albums? As you know, some songs are repeated in different albums.

    Can I labled the same song to more than one albums? As you know, some songs are repeated in different albums.

    You can make a copy of an existing song, then change the album, artwork and track number details. You cannot make the same physical file show up in two different albums.
    tt2

  • Can we copy the same quotation to more than one sales order?

    Can we copy the same quotation to more than one sales order?is it posibble.......pls reply

    Hi vepa venkat suhas.,
                                       If the quotation quantity is 100,with reference to quotaion if you raise a sales order for 100 materials then you cannot raise other sales order with reference to the quotation.untill your quatity of 100 in quotation is finished you can raise a sales order
    REWARD if helpfull
    Thanks & Regards
    Narayana

  • Can I put the same app on more than one iPad?

    I'm not sure I can even do this or how if I can.
    Situation is I got a New iPad and my wife 'inherited' my iPad2. We use ONE Apple iTunes account. I've dup'ed the iPad2 over to the New iPad. We use two computers and each has iTunes on it. No problems at this point.
    Now I added an app to my iPad, and my wife wants it. She went to the app store and it shows as 'already installed'. Again, we're both using the same account (I don't want 2). Looked at Previous Purchases, same thing, already installed, grayed out.
    So the question is can I do what I want, that is install the same app on 2 iPads? If so, how?
    Thanks,
    Irv S.

    Sure - as long as you use the same apple ID on both devices you can download it to both devices. Why is is greyed out on her iPad is not clear to me - other than the app is actually on her iPad via Automatic Downloads and she doesn't realize that its on the device. Is that possible?
    Search for the app on her iPad- swipe to the right from the first home screen and type in the name of the App at the top in the search field. Does it show up?

  • Same photo in more than one catalog - what happens?

    What happens if you have the same photo in more than one catalog?
    Background: I'm using a 4yr old 13" MacBook and my Lightroom is getting rather slow, on some pictures unusable.  At the same time my lrcat files are growing rather fast.  Probably due to my current work on some old scanned slides which require quite a lot of spot removal (last 3 photos worked on increased the lrcat file by 250mb) and each time Lightroom became virtually unusable.  I will be upgrading the computer but it wont be for a few months yet.  On one of the last slides I ended up with a "Oops! An untagged string (history step does not belong to instance) got thrown far enough that we display it to the user. This shouldn't happen.".
    So I'm looking at splitting my catalog into two or more seperate catalogs.  But I have some galleries which contain photos from what would cross "sensible" splits of catalog so I thought about having the same photo in both catalogs where necessary.
    My Lightroom is set to include metadata in XMP (probably making the performance worse).  I had intended to split catalogs using "export to catalog".
    Does the photo in each catalog have it's own develop "fork" ? (i.e. does the metadata include catalog tags) ?  Or will changes made to the photo in one catalog automatically upadate the next catalog (or overwrite changes made in the other catalog), etc.?  Only a single computer, no network/sharing issues, nothing on exchangable/removable disk drives.
    I could experiment but after quite some time the other day resolving the "history step does not belong to instance") I am treating my catalog with great care.
    (I have does a search for the question so will be very embarassed/appologetic if somebody says "Read www.adobe.com/.....").
    Many thanks

    For some reason photos were scanned in as jpegs.  They end-up at around 16-19MB each.  Reasons for that are historical.  I am applying spot corrections in Photoshop in a new layer, then merging layers when everyting is done OK to save (saving as PSD gave a massive file size).  I will try saving as tiff.  Personally I hate JPEGs but was never too concerned about the scans in LR as LR is never resaving the image (non-destructive editing).  I may easily upgrade to CS6 (upgrade is <£200 on Amazon), but being non-professional, fuds are not unlimited (particularly with new computer coming soon!!).
    So weird effect is with jpegs around 16MB after Photoshop edits.  It is completely reproducable (i.e. has happened exactly the same of every photo done via this route).  The surprising thing is that exiting and restarting LR stops the weird effect.
    Adding 2 and 2 together to get 22, I wonder if, as I have "Write Metadata to XMP ..." enabled, if LR has a watch on the file for changes after switching to external editor (i.e. to detect when external editor saved changes so LR updates from the file) and that that "watch for change" is not cancelled after exiting the external editor - maybe because LR cannot know if external editing is compketed (even though exitng Photoshop does not stop the effect).  Then, when LR writes to the file (to update the XMP data) it "detects" the change it causd itself and hence the reload.  If I change the Catalog Settings to disable the "Include develop settings in JPEG ..." and disable the "Save XMP Data ...", the effect goes away and if I re-enable those catalog options the effect returns.
    I will try saving as tiff in future now I'm really re-saving the image.
    Many thanks

  • The "Measures" dimension contains more than one hierarchy... Collation issue

    It appears that an Excel query pased through to SSAS has a "measures" with lowercase "m" when analysis services expects an uppercase "M" so it should look like "Measures". Is there a fix in excel to allow
    the correct passing of "Measures" member name to the cube?
    BTW, I have NO Calculations in the cube.
    In excel 2013 when I pivot with a pivot table connected to a case sensitive collation (non default config)
    cube and perform a filter by "Keep only Selected Items" I get the error "The 'Measures' dimension contains more than one hierarchy, therefore the hierarchy must be explicity specified".
    When I revert back to server wide setting to case insensitive, and I preform the exact same pivoting function it works without error. The problem appears to be that excel does not understand the server collation setting.
    When I run SQL Server Profilier I narrowed down the MDX statement run in Excel that gives me an error to this:
    with
    member measures.__XlItemPath as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    [Employee].[Location Code].currentmember.unique_name,
    "|__XLPATHSEP__|"
    member measures.__XlSiblingCount as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    AddCalculatedMembers([Employee].[Location Code].currentmember.siblings).count,
    "|__XLPATHSEP__|"
    member measures.__XlChildCount as
    AddCalculatedMembers([Employee].[Location Code].currentmember.children).count
    select { measures.__XlItemPath, measures.__XlSiblingCount, measures.__XlChildCount } on columns,
    [Employee].[Location Code].&[01W]
    dimension properties MEMBER_TYPE
    on rows
    from [Metrics]
    cell properties value
    Playing around with the query I discovered that if I capitalize the first letter of the "with measures" member, the statement works.
    with
    member Measures.__XlItemPath as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    [Employee].[Location Code].currentmember.unique_name,
    "|__XLPATHSEP__|"
    member Measures.__XlSiblingCount as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    AddCalculatedMembers([Employee].[Location Code].currentmember.siblings).count,
    "|__XLPATHSEP__|"
    member Measures.__XlChildCount as
    AddCalculatedMembers([Employee].[Location Code].currentmember.children).count
    select { measures.__XlItemPath, measures.__XlSiblingCount, measures.__XlChildCount } on columns,
    [Employee].[Location Code].&[01W]
    dimension properties MEMBER_TYPE
    on rows
    from [Metrics]
    cell properties value
    Also, I realise that I could change the collation on just the cube itself to case insenstive to get this to work, but I really don't want to do an impact analysis of running a mixed collation environment.
    So, my question is: Is there an excel fix that will allow me to run a case sensitve cube and allow me to click on filter and filter by "keep only selected items" or "Hide selected Items"? All other filtering works, it's only those two
    filtering options error for me.
    Here are the versions I'm working with:
    Excel 2013 (15.0.4535.1507) MSO(15.0.4551.1007) 32-bit Part of Microsoft Office Professional Plus 2013
    Microsoft Analysis Server Enterprise 2012 11.0.3000.0
    Any help would be appreciated. Thank you in advance!

    Hi, i assume this logic is for Dimension formula?
    If you have multiple hierarchy like ParentH1 and ParentH2 you should use FormulaH1 and FormulaH2 and not FORMULA column.
    in FORMULAH1
    [Account.H1].[Account_A] / [Account.H1].[Account_B]

  • Can the AirPort Extreme support more than one printer at a time?

    can the AirPort Extreme support more than one USB printer at a time if it is connected to a USB Hub?

    can the AirPort Extreme support more than one USB printer at a time if it is connected to a USB Hub?
    Yes.....IF.....you use a powered USB hub.
    I have had 3 printers connected at the same time in the past and assume that more would work as long you have a powered hub to support the number of ports that you need.

  • Is possible to execute the same executable vi more than 1 time (like notepad, for example)?

    I have a Labview executable file that use serial ports to communicate with other devices. I need to execute the same "file.exe" more than 1 time, to control different devices simultaneously. When I double click on an executable been executed (from windows explorer), the file under execution comes to front. Is possible to execute the same file more than 1 time (like notepad, for example)?

    Not the answer you are looking for I know..but still: Copying the application to another location is one possibility...if it has a different path it will execute separately.
    (OR - build control of multiple devices into one and the same application... If you do not want to redesign the code to handle multiple instruments in the same VIs, you could clone the VIs within the same application...)
    MTO

  • I have the same photo in more that one event.  I would like to only have the photo appear in one event.

    I have the same photo in more that one event.  I would like to only have the photo appear in one event.

    Then do not import it more than once in the future  For now you can simply delete one of them and empty the iPhoto trash
    LN

  • HT1539 Can you download the digital copy to more than one iTunes account?

    Can you download the digital copy to more than one iTunes account?

    No. The redemption codes are one-time use only.
    tt2

  • Can't add a goods-issue with more than one item and one is serial managed.

    Hi,
    We are trying to issue more than one item to a production order using the DI API.  If none of the items is serial managed, they all are accepted and the goods-issue Add is successful.  If one the items is batch-managed, the goods-issue Add is also successful.  I am able to add the goods-receipt if I it contains only one item and it is serial-number managed.  However, if I’m issuing more than one item and one or more of the items is serial number managed, then the DI API will not add the goods-issue.  The error message that appears refers to an item that is not among the items being issued.  The message is:
    -10: (IGE1.WhsCode)(line: 3), ‘Item ‘A00006        ‘ with system serial 1 is not in stock.’
    Again item A00006 is not even in the group of items being issued.
    The code I am using for the serial number part is:
    With oGoodsIssue.Lines.SerialNumbers
              .SystemSerialNumber = rs.Fields.Item("SysSerial").Value
              .ManufacturerSerialNumber = rs.Fields.Item("MfrSN").Value
              .InternalSerialNumber = rs.Fields.Item("IntrSerial").Value
              .SetCurrentLine(n)
              .Add()
              rs.MoveNext()
              n += 1
    End With
    The rs is a recordset that the code is looping through as the serial numbers are being added.
    The error message does not occur during this code.  It occurs when it tries to add the full goods-receipt.  Does anyone have any idea how I can fix this?
    Thanks,
    Mike
    Edited by: Mike Angelastro on Mar 31, 2008 8:43 AM

    Hi Mike,
    Try to do the ".Add" only if you need it. Doing a ".add" without assignation may cause the error you have.
    I guess your n variable start at 1 or 0, so you could put code like this :
    With oGoodsIssue.Lines.SerialNumbers
    if n = 0 then (or 1, also I don't the correct syntax of your programming language)
    .Add()
    end if
    .SystemSerialNumber = rs.Fields.Item("SysSerial").Value
    .ManufacturerSerialNumber = rs.Fields.Item("MfrSN").Value
    .InternalSerialNumber = rs.Fields.Item("IntrSerial").Value
    .SetCurrentLine(n)
    rs.MoveNext()
    n += 1
    End With
    HTH
    Jodérick

  • The internet browser with more thane one video running is keep crashing after installing Adobe flash.

    If I run any website contains more than one video like this website for example :
    http://www.neatoxv-21.org ,where it has two videos talking about the cleaning vacuum neato xv-21, and both videos
    are running at the same time, then suddenly the explorer will crash, But in other broswers like google chrome it works fine.
    To double check, I un-installed the software and then I restarted my computer, I installed the software again but the same issue.
    I am using windows 7, so to be sure I missed nothing I updates the windows from Microsoft website and also
    I am sure that I have the latest internet explorer update.
    Now, the funny thing, I did the same process with Google chrome and it works fine!!!
    I am totally confused, wht could be the reason??
    Please advice..

    Update - I've now tested this with different internet connections, different computers and different operating systems. I've also just received a response from my internet service provider who said:
    "I've tested in Firefox, and it looks as if the buttons are crashing the browsers' flash plugin. This being the case, it is not going to be anything related to your computer, the internet connection, or the web server. 
    In all likelihood, it will be an issue with how the flash tour is coded, which I presume is created automatically by the Tourweaver package you mention. You will need to pursue their support for advice on this problem as it is something with the flash file)s( which isn't working correctly."
    So, hopefully Easypano support will be able to fix the problem. Obviously no connection at all with Adobe After Effects

  • Query to retrieve the records which have more than one assignment_id

    Hello,
    I am trying to write a query to retrieve all the records from the table per_all_assignments_f which has more than one different assignment_id for each person_id. Below is the query i have written but this retrieves the records even if a person_id has duplicate assignment_id's but i need records which have more than one assignement_id with no duplicates for each person_id
    select assignment_id ,person_id, assignment_id
    From per_all_assignments_f
    having count(assignment_id) >1
    group by person_id, assignment_id
    Thank You.
    PK

    Maybe something like this?
    select *
    From   per_all_assignments_f f1
    where  exists (select 1
                   from   per_all_assignments_f f2
                   where  f2.person_id = f1.person_id
                   and    f2.assignment_id != f1.assignment_id
                  );Edited by: SomeoneElse on May 7, 2010 2:23 PM
    (you can add a DISTINCT to the outer query if you need to)

  • Use of same iTune for more than one iPod

    I need to find out whether I can use the same itune in one computer for more than one iPod nano and one iPod video?

    I looked at the article, but it doesn't help me know how once I have downloaded onto a nano, for example, the itunes knows that the next thing I connect is something different. My son hooked up his 20GB ipod last night after updating his sister's nano and now the itunes thinks his ipod is a nano. How do I get the itunes to recognize his ipod as the 20GB it is?

  • How to prevent the User from loading more than one seq file?

    Hi,
    I would like to prevent the tester operator from loading more than one test sequence.  Any ideas how to do it?
    Thanks
    Rafi

    Hi Marty,
    Marty_H wrote:
    Hello mhousel,
    Testexec.exe by default loads the sequence files that were last open when it runs.  It is often desired behavior to have multiple sequence files load automatically. 
    [Mark Housel] Maybe for some but certainly not for me. 
    This should be easily handled by TestStand without any problems.  What do you mean by "chaos ensues"? 
    Certainly Teststand doesn't care a bit how many sequences are open.  But, when my sequences open they initialize HW of the ATE associated with
    that sequence file during the sequenceFileLoad callback.  e.g. I allocate TELNET handles to a terminal
    server that connects to multiple console within the system and als for
    the UUT.
    If a second sequence opens it knows nothing about the other sequence and again tries to open a TELENT session to the same port of the
    terminal server and obviously fails, so my sequence reports that it
    can't properly initialize the ATE HW.  Bad juju!
    Are your sequence files set to run automatically when they are loaded?
    I guess so.  Other than the trick of logging in as the special noExecution user and having special code in my sequence and modified Process Model I have no idea how to prevent a sequence fronm "runnin" when opened.
    If you want to prevent Testexec.exe from loading multiple files, you should be able to close out one of the open files when it loads and that sequence file should not load in the future.  I hope that helps.
    The trick I read somewhere else of modifying the Testexec.uir file to never re-load a sequence file automatically seemes to have covered up solved the problem.
    Thanks,
    Mark

Maybe you are looking for

  • [SOLVED] Gnome does not mount ipod after system upgrade

    I did a system upgrade today (2009.12.04) and now gnome does not mount my ipod video (gnome used to mount the ipod without problems before de upgrade). Here is some information about the system messages: Last lines of the output of dmesg before plugg

  • Convert to JPEG

    How do I convert a PDF to JPEG???

  • "Beach Ball" when I conect to a PwrBook in Target Disk Mode

    The iMac G4 is the host to a PwrBook G4 Ti I get the blue screen with the firewire icon on the PwrBook On the iMac, the PwrBook's apears on the desktop as a firewire drive When I either double clic on it, or open finder to search in the PwrBook's dri

  • How to use the mobile phone control computer?

    Using iPhone5 remote control computer, what software?   TKS!!!

  • Yosemite running slow

    On iMac Quad Core i7 32GB with the latest Yosemite OS X 10.10.1. Ive had a couple of crashes lately after my Time Machine (writes to USB3 Lacie 1TB HD) stopped working, so I tried deleting the ext USB drive but that caused a 1 hour wheel of death whi