Sticking components in JPanel to GridLayout

Could please anyone help in the following.
I have an application where some JPanel with several Swing components
positioned with help of GridLayout. What I need is to
remove and place components during runtime,
but the problem is that when I remove component placed somewhere
inbetween with use of the method remove() of the class JPanel,
all components are shifted so that the empty space is filled and
even one can see that the initial GridLayout is destroyed.
How can I stick all components to the initial grid cells of GridLayout?
I mean I do not want components to shift anywhere from their original
cells.
Thank you in advance.

Well, that solution is what I came to also.
I mean I replacing removed compenent with some other invisible component.
But is this indeed the only way?
I tryied the method removeLayoutComponent() in the class GridLayout, but
I have not understood how it works and what it is for.
When I tryied it instead of remove() (of JPanel) it did not remove anything,
but it looks like something relevant to my situation.
PS The second line of my orginal poster should be read
"I have an application where some JPanel is created with several Swing components
positioned with help of GridLayout in it".
Sorry...

Similar Messages

  • Can't show J components on JPanel

    Because I'm a begineer, I'm not sure I can explain my problem correctly.
    The problem is quite simple.
    I'd like to show some J components on JPanel but I can't.
    I made a JFrame which has 5 JPanels.
    Each JPanel has some components and calls paint method to draw some lines.
    public void paint(Graphics g){
         g.setColor(Color.black );
         drawDisplay(g);
    When I put AWT componts such as Label, Button etc, there's no problem.
    But when I put J components like JLabel, JButton,
    I cannot see the components. Sometimes I can click JCombo box....
    Interestingly, when I remove the paint method, J components show up on interface.
    Anybody understand this situation?
    Do I have to know something for this?
    Thank-you.

    I second camickr's recommendation for you to study the tutorials. A few specifics:
    public void paint(Graphics g){
       g.setColor(Color.black );
       drawDisplay(g);
    }* Don't override the paint method of a JPanel, override the paintComponent method.
    * You will need to call super.paintComponent(g) within your paintComponent override. This may need to be the first line in fact.
    * As noted by camickr, do not place AWT components on a Swing component (JPanel).

  • How can we add components to JPanel so that they can be resizeable

    Is it possible to add components to JPanel so that we can resize them or drag them.

    You could try searching the forums, but I'll save you the trouble. tjacobs has oft posted code which does what you want, both dragging and resizing.
    You can find an example here or here.

  • Updating components in jpanel

    Hi, all
    I have a report application which will update me system utilization in several jpanel. Those panels stored in a hashtable and I programmed it refresh each 5 minutes. Here is how I do it.
    Step 1: remove all
    mypanel=(JPanel)panels.get("1");
    mypanel.removeAll();
    mypanel.validate();
    Step 2: show progress
    mypanel.add(<updating message in jlabel>);
    mypanel.add(<a progressbar>);
    mypanel.validate();
    Step 3: add new content
    mypanel.removeAll();
    mypanel.add(<a graph in jlabel>);
    mypanel.add(<a jtable with data>);
    The problem is the old content still remains when progress bar appeared. Didn't I just remove all components in step 1? How can I have a empty panel with only progress bar?
    Thanks,
    Vincent Chen

    Damn, I found what the problem is, but if I gave the solution to the OP, that would mean confessing I have followed the link, and admitting to belong to the "not worth mentioning" category!Well, since my cover's blown anyway, let's caugh it up:
    Your have an attrubute searchType of type SearchType, you initialize it to reference a new SeearchType() , and you use its status for the search, however you never add the instance in the panel's widget hierarchy. Instead you add a new SearchType() .
    Same for attribute style :
    searchType = new SearchType();
    style = new Style();
    this.add(new SearchType(), c);
    this.add(new Style(), c);
    // in event handler
    search(txfQuery.getText(),searchType.getSelected(),style.caseSensitive(),limitation.getLimNum());
                                    ^
                                    *At this point, the instance referenced by searchType has never been displayed, so the checkbox, combobox, and whatnot that the user has interacted with are not the ones whose state you read.

  • Zooming causes components on JPanel to displace

    Hi friends,
    my english is somewhat weak, but i am trying to clear my point.
    I have a prob regarding zoom. In my application I have A JPanel which is drawing some rectangles on it and having some JLabels. My prob is when i zoomin my JPanel through my zooming code and try to select any of JLabel ,I am not actually selecting labels by just clicking on the label but i have to make some random guess on JPanel to select that label.
    I am not getting what mistake i m making there. may be i would have to move my labels by some distance on zooming(but its only my view). if any of you have some ideas then please do tell me.
    thankyou

    I second camickr's recommendation for you to study the tutorials. A few specifics:
    public void paint(Graphics g){
       g.setColor(Color.black );
       drawDisplay(g);
    }* Don't override the paint method of a JPanel, override the paintComponent method.
    * You will need to call super.paintComponent(g) within your paintComponent override. This may need to be the first line in fact.
    * As noted by camickr, do not place AWT components on a Swing component (JPanel).

  • Handling focus on components within JPanel

    I have a custom component called a DmsField which extends JPanel. "Dms" means degrees/minutes/seconds. It's a JPanel with a two-button JRadioButton group for the sign, and three JFormattedTextFields for degrees (int), minutes (int), and seconds (float, 2 dec places). It's later subclassed into LatField and LonField so I can enter latitudes and longitudes into an application. When I put a LatField or a LonField into my dialog's JPanel, tabbing through the various components in the larger panel shifts the focus to the whole LatField (or LonField) object first, then through the subobjects in the *Field.  How can I get the focus traversal to NOT focus on the DmsField itself, but to go straight to the first component inside the DmsField?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I have tried putting a FocusListener on the JPanel which would set the focus to its first component. Works fine tabbing forward, but gets stuck on first component when back-tabbing.
    Disabling FOCUS_EVENT_MASK on the JPanel didn't change anything.
    The odd thing is, I don't see any other JPanels exhibiting this behavior.

  • Re-order components in JPanel using Drag and Drop

    Hi,
    I have a JPanel that contains some more JPanels (the Layout is GridBagLayout - one column, each row - 1 JPanel). I would like to drag one JPanel (1) and after dropping it on some other JPanel (2), the (1) should be inserted at (2)'s position.
    I really can't get the idea from sun's tutorials :(

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class DragTest extends JPanel
        public DragTest()
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weighty = 1.0;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            for(int j = 0; j < 4; j++)
                JPanel panel = new JPanel(new BorderLayout());
                panel.setBorder(BorderFactory.createEtchedBorder());
                panel.add(new JLabel("panel " + (j+1), JLabel.CENTER));
                add(panel, gbc);
        public static void main(String[] args)
            DragTest test = new DragTest();
            DragListener listener = new DragListener(test);
            test.addMouseListener(listener);
            test.addMouseMotionListener(listener);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class DragListener extends MouseInputAdapter
        DragTest dragTest;
        Component selectedComponent;
        GridBagConstraints constraints;
        Point start;
        boolean dragging;
        final int MIN_DRAG_DISTANCE = 5;
        public DragListener(DragTest dt)
            dragTest = dt;
            dragging = false;
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            Component[] c = dragTest.getComponents();
            for(int j = 0; j < c.length; j++)
                Rectangle r = c[j].getBounds();
                if(r.contains(p))
                    selectedComponent = c[j];
                    start = p;
                    dragging = true;
                    break;
        public void mouseReleased(MouseEvent e)
            if(dragging)  // no component has been removed
                dragging = false;
                return;
            Point p = e.getPoint();
            if(!dragTest.getBounds().contains(p))  // out of bounds
                // failed drop - add back at index = 0
                dragTest.add(selectedComponent, constraints, 0);
                dragTest.revalidate();
                return;
            Component comp = dragTest.getComponentAt(p);
            int index;
            if(comp == dragTest)
                index = getDropIndex(dragTest, p);
            else  // over a child component
                Rectangle r = comp.getBounds();
                index = getComponentIndex(dragTest, comp);
                if(p.y - r.y > (r.y + r.height) - p.y)
                    index += 1;
            dragTest.add(selectedComponent, constraints, index);
            dragTest.revalidate();
        private int getDropIndex(Container parent, Point p)
            Component[] c = parent.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j].getY() > p.y)
                    return j;
            return -1;
        private int getComponentIndex(Container parent, Component target)
            Component[] c = parent.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j] == target)
                    return j;
            return -1;
        public void mouseDragged(MouseEvent e)
            if(dragging)
                if(e.getPoint().distance(start) > MIN_DRAG_DISTANCE)
                    // save constraints for the drop
                    GridBagLayout layout = (GridBagLayout)dragTest.getLayout();
                    constraints = layout.getConstraints(selectedComponent);
                    dragTest.remove(selectedComponent);
                    dragging = false;
                    dragTest.revalidate();
    }

  • How to change properties or add components in JPanel after initialization ?

    Hi,
    I am working on an applet where an image will be loaded in a JPanel from an URL. The JPanel is inside a JscrollPane.
    1.The image will be added on the JPanel later , not during initialization.
    2. JPanel size will be the size of the image.
    3 .the image size may change when the image is changed. Then the JPanel size also has to be updated.
    FYI I am using MediaTracker to load the image.
    I was trying updateUI() for scrollPane. But it is not working.
    How can I do it? Any suggestion?
    Thanks in advance.

    I have to use JPanel because I need flexible control on the imageYou said previously that the panel was the size of the image, so I don't understand what kind of flexible control you are talking about. Presumably you have code in the paintComponent(...) method of the JPanel something like:
    g.drawImage(0, 0, width, height)
    Well that is exactly what a JLabel would do.
    So if you need further custom painting then you would just override the paintComponent(...) method of JLabel to do your custom painting.

  • Make components like JPanel / Containers ..  from a String..

    public class PuzzlePieces {
         private String area;
         private String *container* = area +"Container";
         private String panel = area +"Panel";
         private Container *container* = new Container();
         private int number;
         public PuzzlePieces(String area, int numbersOfPices) {
              this.area = area;
              this.number = numbersOfPices;
         }as you can see I want to make a Container out of a Sting. How can I do this? Please make an example if you have a solution. TY

    Plexus81 wrote:
    OK, I'll try to explain ..
    I get a string in, as you can see. I want to make/add JButton, JPanel, Containers .. based on name of the String I get in.
    String
    StringPanel
    StringContainer
    But I cant write like this
    Container String +"Container" = new Container();What's the best way to solve this..You want the variable names for those Containers to be based off the Strings? Is that what you mean? Why do you want/need to do that?
    The go-to solution for stuff like this is to use a Map of String, Container pairs. But why over complicate your program with stuff you probably don't really need?

  • Adding Components to a JPanel not working correctly

    I'm trying to build a JFrame that contains a parent JPanel that will hold a JPanel used to display a message view, a vertical strut and a JPanel that holds VCR-like buttons to cycle through the messages.
    My parent JPanel uses a BorderLayout and the Border is a TitledBorder which tells which product you are viewing (i.e., Message 1 of 5). I build the message JPanel, vertical strut and button JPanel and add them all in order to the parent JPanel which then gets added to the rootContentPane of the JFrame. All that appears is the parent JPanel's TitledBorder, the strut and the button JPanel. Using JSwat, I've been able to determine that the message JPanel has 0 for both its height and width after adding the message components to the JPanel.
    I create the message JPanel with a BorderLayout and an OvalBorder as copied from Manning Press's Swing book (which works fine in other JFrames that I have built), then add other components as necessary to the individual messages (mostly items around the edges with a central display for the actual message). What I can't figure out is why the height and width of the message JPanel isn't growing as I add components.
    I had previously used the same code to display a single message (minus the parent JPanel, strut and button JPanel) where I added the border panels (northPanel, eastPanel, southPanel and westPanel) created in createMsgPanel() directly to the contentPane and it worked perfectly, so I know that the code that adds the message works fine. Then, the requirements changed (go figure) and I had to display multiple messages from the same screen.
    Here's what I've got:
    public class Layout
                 extends JFrame
                 implements ActionListener
       private MissionData missionData;
       private JPanel messagePanel = null;
       private int index = 0;
       private int numMsgs = 0;
       private JPanel mainPanel = null;
       private JPanel buttonPanel = null;
       private TitledBorder titledBorder = null;
       Layout ()
       public Layout (MissionData msn)
          super ();
          missionData = msn;
          setSize (640, 640);
          setIconImage (new ImageIcon ("Icon.jpg").getImage());
          setTitle (((Message) (missionData.messages.elementAt(0))).name);
          numMsgs = missionData.messages.size();
          titledBorder = new TitledBorder (
                            new LineBorder (Color.BLACK),
                            "Message " + String.valueOf (index + 1) +
                            " of " + String.valueOf (numMsgs),
                            TitledBorder.LEFT,
                            TitledBorder.TOP);
          mainPanel = new JPanel ();
          mainPanel.setLayout (new BorderLayout());
          mainPanel.setBorder (new CompoundBorder (titledBorder,
                                                   new EmptyBorder (
                                                      new Insets (3, 3, 3, 3))));
          messagePanel = new JPanel();
          messagePanel.setLayout (new BorderLayout ());
          messagePanel.setBorder (new CompoundBorder (
                                     new EmptyBorder (50, 50, 50, 50),
                                     new OvalBorder (20, 20, Color.white)));
          messagePanel.setBackground (Color.black);
          createButtonPanel ();
          createMsgPanel ((Message) missionData.messages.elementAt (0));
          mainPanel.add (messagePanel);
          mainPanel.add (Box.createVerticalStrut (20));
          mainPanel.add (buttonPanel);
          Container mainContentPane = getContentPane();
          mainContentPane.add (mainPanel);
       private void createMsgPanel (Message msg)
          MessageType msgType = null;
          if (msg.getFunctionalAreaDesignator(0) == Message.GENERAL_INFO)
             if (msg.getMessageNumber(0) == 1)
                msgType = FREE_TEXT;
          else if (msg.getFunctionalAreaDesignator(0) == Message.SUPPORT)
             if (msg.getMessageNumber(0) == 33)
                msgType = CAS;
             else if (msg.getMessageNumber(0) == 34)
                msgType = OSR;
          // Setup NORTH Panel of Display
          JPanel northPanel = new JPanel (new GridLayout (2, 6));
          northPanel.setBackground (Color.black);
          northPanel.add (new JTIMLabel ("", false));
          northPanel.add (new JTIMLabel ("<html>RECV</html>", false));
          if (msgType == CAS)
             northPanel.add (new JTIMLabel ("<html>PCLR</html>", false));
             northPanel.add (new JTIMLabel ("<html>MSN</html>", false));
             northPanel.add (new JTIMLabel ("<html>SAVE</html>", false));
          else if (msgType == OSR)
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          else if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("<html>ERASE</html>", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("<html>BRDCST</html>", false));
          northPanel.add (new JTIMLabel ("<html>SEND</html>", false));
          northPanel.add (new JTIMLabel ("", false));
          northPanel.add (new JTIMLabel ("", false));
          if (msgType == CAS)
             northPanel.add (new JTIMLabel ("<html>CAS</html>", false));
          else if (msgType == OSR)
             northPanel.add (new JTIMLabel ("<html>OSR</html>", false));
          else if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("<html>FTXT</html>", false));
          if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          else
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("<html>CAS</html>", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          messagePanel.add (northPanel, BorderLayout.NORTH);
          // Setup EAST Box of Display
          Box eastBox = new Box (BoxLayout.Y_AXIS);
          if (msgType == CAS)
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>F<br>T<br>X<br>T</html>", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>O<br>S<br>R</html>", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>D<br>P<br>I<br>P</html>", false));
             eastBox.add (Box.createGlue());
          else if (msgType == FREE_TEXT)
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
          eastBox.add (new JTIMLabel ("<html>W<br>L<br>C<br>O</html>", false));
          eastBox.add (Box.createGlue());
          eastBox.add (new JTIMLabel ("<html>C<br>N<br>T<br>C<br>O</html>",
                                        false));
          eastBox.add (Box.createGlue());
          messagePanel.add (eastBox, BorderLayout.EAST);
          // Setup SOUTH Panel of Display
          JPanel southPanel = new JPanel (new GridLayout (2, 5));
          southPanel.setBackground (Color.black);
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("<html>ON</html>", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          if (msgType == CAS)
             southPanel.add (new JTIMLabel ("<html>USE</html>", false));
             southPanel.add (new JTIMLabel ("<html>RCALL</html>", false));
          else if ((msgType == OSR) || (msgType == FREE_TEXT))
             southPanel.add (new JTIMLabel ("", false));
             southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("<html>MENU</html>", false));
          southPanel.add (new JTIMLabel ("<html>VMF</html>", false));
          if (msgType == CAS)
             southPanel.add (new JTIMLabel ("<html>NETS</html>", false));
          else if ((msgType == OSR) || (msgType == FREE_TEXT))
             southPanel.add (new JTIMLabel ("<html>CAS</html>", false));
          southPanel.add (new JTIMLabel ("", false));
          messagePanel.add (southPanel, BorderLayout.SOUTH);
          // Setup WEST Box of Display
          JTIMLabel incrLabel = null;
          JTIMLabel decrLabel = null;
          Box westBox = new Box (BoxLayout.Y_AXIS);
          if (msgType == FREE_TEXT)
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>N<br>E<br>X<br>T</html>", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>P<br>R<br>E<br>V</html>", false));
          else
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>U<br>F<br>C</html>", false));
             westBox.add (Box.createGlue());
             if (msgType == CAS)
                westBox.add (new JTIMLabel ("<html>/\\</html>", false));
                westBox.add (Box.createGlue());
                westBox.add (new JTIMLabel ("<html>\\/</html>", false));
                westBox.add (Box.createGlue());
                incrLabel = new JTIMLabel ("<html>I<br>N<br>C<br>R</html>", false);
                westBox.add (incrLabel);
                westBox.add (Box.createGlue());
                decrLabel = new JTIMLabel ("<html>D<br>E<br>C<br>R</html>", false);
                westBox.add (decrLabel);
                westBox.add (Box.createGlue());
          messagePanel.add (westBox, BorderLayout.WEST);
          // Create CENTER Box to display message bodies
          GriddedPanel centerBox = new GriddedPanel ();
          centerBox.setBackground (Color.black);
          messagePanel.add (centerBox, BorderLayout.CENTER);
          if (msgType == CAS)
             new CASDisplay (msg, centerBox, incrLabel, decrLabel);
          else if (msgType == OSR)
             new OSRDisplay (msg, centerBox);
          else if (msgType == FREE_TEXT)
             new FreeTextDisplay (msg, centerBox);
       private void createButtonPanel ()
          // build the button panel
          buttonPanel = new JPanel ();
          buttonPanel.setLayout (new BoxLayout (buttonPanel, BoxLayout.X_AXIS));
          buttonPanel.setBorder (new LineBorder (Color.BLACK));
          // Create and add the buttons
          buttonPanel.add (createButton ("FIRST_BUTTON"));
          buttonPanel.add (createButton ("PREV_BUTTON"));
          buttonPanel.add (createButton ("NEXT_BUTTON"));
          buttonPanel.add (createButton ("LAST_BUTTON"));
       private JButton createButton (String buttonName)
          JButton button = new JButton ();
          button.addActionListener (this);
          button.setActionCommand (buttonName);
          Image image = null;
          String tooltip = "Press to go to the ";
          if (buttonName.equals ("FIRST_BUTTON"))
             image = new ImageIcon ("firstArrowIcon.gif").getImage();
             tooltip += "First";
          else if (buttonName.equals ("PREV_BUTTON"))
             image = new ImageIcon ("previousArrowIcon.gif").getImage();
             tooltip += "Previous";
          else if (buttonName.equals ("NEXT_BUTTON"))
             image = new ImageIcon ("nextArrowIcon.gif").getImage();
             tooltip += "Next";
          else if (buttonName.equals ("LAST_BUTTON"))
             image = new ImageIcon ("lastArrowIcon.gif").getImage();
             tooltip += "Last";
          tooltip += " message in the lst";
          button.setToolTipText (tooltip);
          button.setIcon (new ImageIcon (image.getScaledInstance (36, 36, Image.SCALE_FAST)));
          return button;
       public void actionPerformed (ActionEvent e)
          if (e.getActionCommand ().equals ("FIRST_BUTTON"))
             index = 0;
          else if (e.getActionCommand ().equals ("PREV_BUTTON"))
             if (index > 0)
                index--;
          else if (e.getActionCommand ().equals ("NEXT_BUTTON"))
             if (index < numMsgs - 1)
                index++;
          else if (e.getActionCommand ().equals ("LAST_BUTTON"))
             index = numMsgs - 1;
          titledBorder.setTitle ("Message " + String.valueOf (index + 1) +
                                 " of " + String.valueOf (numMsgs));
          createMsgPanel ((Message) missionData.messages.elementAt (index));
       private static class MessageType
                            extends EnumeratedType
                            implements Serializable
          final static long serialVersionUID = 1;
          protected MessageType (int value, String desc)
             super (value, desc);
       private static MessageType FREE_TEXT =
          new MessageType (0, "Free Text");
       private static MessageType CAS =
          new MessageType (1, "Call Accounting System");
       private static MessageType OSR =
          new MessageType (2, "Occupational Survey Report");
    }

    That's all well and good, but I've had more times that not where
    people want the entire program, not bits and pieces.Then you missed the whole point of that link.
    We don't want to see bits and pieces of code. We want to see an executable program, but we want an executable program the demonstrates the incorrect behaviour without all the unnecessary code. 90% of the code you posted was not related to your problem. That is we what you do to some basic debugging and remove the parts of code that are not related to the problem so we can concentrate on the code that is related to the problem.

  • JPanels & Components not behaving properly.

    Hi, I'm having great difficulties trying to get my panels and their components to work with each other. I want a few simple things on a JFrame in the following manner.
    |JLabel | JList |
    |JLabel | JTextField |
    |JLabel | JTextArea |
    |--------------------------|
    |JButton | JButton| JButton|
    The problem is all the JLabel, JList, JTextField and JTextArea occupy the same amount of space, I only want 5 lines for JList, 1 line for JTextField and 20 lines for JTextArea. Does anyone have any clues as to what I'm doing wrong? I've attached my code below. Please take a look and see if you can help me out. I'm stumped! :( Thanks in advance for all your help!
    Juivette
    emailScreen( Vector emailVector ) {
    this.emailVector = emailVector;
    emailList = new JList( emailVector );
    emailList.setVisibleRowCount(5);
    initScreen();
    addListeners();
    pack();
    private void initScreen() {
    getContentPane().setLayout( new BorderLayout() );
    JPanel mainPanel = new JPanel( new BorderLayout() );
    JPanel leftPanel = new JPanel( new GridLayout(0,1) );
    JPanel rightPanel = new JPanel( new GridLayout(0,1) );
    JPanel buttonPanel = new JPanel( new GridLayout(0, 3) );
    emailScrollPane = new JScrollPane( emailList );
    emailToLabel = new JLabel( "Receipent(s): ", JLabel.RIGHT );
    ChangeColour.changeColour( emailToLabel );
    subjectLabel = new JLabel( "Subject: ", JLabel.RIGHT );
    ChangeColour.changeColour( subjectLabel );
    subjectText = new JTextField( 50 );
    messageLabel = new JLabel( "Message: ", JLabel.RIGHT );
    ChangeColour.changeColour( messageLabel );
    messageArea = new JTextArea( 20, 50 );
    leftPanel.add( emailToLabel );
    leftPanel.add( subjectLabel );
    leftPanel.add( messageLabel );
    rightPanel.add( emailScrollPane );
    rightPanel.add( subjectText );
    rightPanel.add( messageArea );
    SendButton = new JButton( "Send" );
    ClearButton = new JButton( "Clear" );
    CancelButton = new JButton( "Cancel" );
    buttonPanel.add( SendButton );
    buttonPanel.add( ClearButton );
    buttonPanel.add( CancelButton );
    mainPanel.add( leftPanel, "West" );
    mainPanel.add( rightPanel, "East" );
    mainPanel.add( buttonPanel, "South" );
    getContentPane().add( mainPanel, "Center" );

    Review the Java Swing Tutorial on Layout Managers: (the BoxLayout may be what you need)
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
    The entire tutorial can be downloaded free from:
    http://java.sun.com/docs/books/tutorial/

  • Problem with jpanel and revalidate()

    i have made a calendar. on click on jlabel you can switch month/year and there is the problem. for example when i switch from february to march and back again, then the panel don�t update. but why?
    i hope you understand what i mean.(I am german and can�t englisch)
    here is the code(i have mixed german in english in the code, i hope you understand even so.)
    package organizer.gui;
    import organizer.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Kalender extends JPanel {
    private Calendar calendar;
    private JPanel days;
    private JLabel monthLabel;
    private SimpleDateFormat monthFormat = new SimpleDateFormat("dd MMM yyyy");
    private TerminManager manger;
    public Kalender(TerminManager manager) {
       super();
       this.manger=manager;
       this.calendar=Calendar.getInstance();
       this.initializeJPanel();
       this.updatePanel();
    protected void updatePanel() {
       monthLabel.setText(monthFormat.format(calendar.getTime()));
       if(days!=null) {
         days.removeAll();
       }else {
         days = new JPanel(new GridLayout(0, 7));
       days.setOpaque(true);
       for (int i = 1; i <=7; i++) {
         int dayInt = ( (i + 1) == 8) ? 1 : i + 1;
         JLabel label = new JLabel();
         label.setHorizontalAlignment(JLabel.CENTER);
         if (dayInt == Calendar.SUNDAY) {
           label.setText("Son");
         else if (dayInt == Calendar.MONDAY) {
           label.setText("Mon");
         else if (dayInt == Calendar.TUESDAY) {
           label.setText("Die");
         else if (dayInt == Calendar.WEDNESDAY) {
           label.setText("Mit");
         else if (dayInt == Calendar.THURSDAY) {
           label.setText("Don");
         else if (dayInt == Calendar.FRIDAY) {
           label.setText("Fre");
         else if (dayInt == Calendar.SATURDAY) {
           label.setText("Sam");
         days.add(label);
       Calendar setupCalendar = (Calendar) calendar.clone();
       setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
       int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
       for (int i = 1; i < (firstday - 1); i++) {
         days.add(new JLabel(""));
       for (int i = 1; i <=setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
         int day = setupCalendar.get(Calendar.DAY_OF_MONTH);
         final Date d = setupCalendar.getTime();
         final JLabel label = new JLabel(String.valueOf(day));
         label.setOpaque(true);
         if(this.manger.isTerminAtDay(d)) {
           String s="<html><center>" + day + "<br>";
           if(this.manger.isBirthdayAtDay(d)) {
             s+="Geburtstag<br>";
           if(this.manger.isOtherTerminAtDay(d)) {
             s+="Termin";
           label.setText(s);
           label.addMouseListener(new MouseListener() {
              * mouseClicked
              * @param e MouseEvent
             public void mouseClicked(MouseEvent e) {
               Termin[] t = Kalender.this.manger.getTermineAtDay(d);
               if (t.length == 1) {
                 new TerminDialog(null, t[0]);
               else {
                 new TerminAuswahlDialog(null, t, d);
              * mouseEntered
              * @param e MouseEvent
             public void mouseEntered(MouseEvent e) {
              * mouseExited
              * @param e MouseEvent
             public void mouseExited(MouseEvent e) {
              * mousePressed
              * @param e MouseEvent
             public void mousePressed(MouseEvent e) {
              * mouseReleased
              * @param e MouseEvent
             public void mouseReleased(MouseEvent e) {
         final Color background=label.getBackground();
         final Color foreground=label.getForeground();
         label.setHorizontalAlignment(JLabel.CENTER);
         label.addMouseListener(new MouseAdapter() {
           public void mouseEntered(MouseEvent e) {
             label.setBackground(Color.BLUE);
             label.setForeground(Color.RED);
           public void mouseExited(MouseEvent e) {
             label.setBackground(background);
             label.setForeground(foreground);
         days.add(label);
         setupCalendar.roll(Calendar.DAY_OF_MONTH,true);
       this.add(days, BorderLayout.CENTER);
       this.revalidate();
    private JLabel createUpdateButton(final int field,final int amount) {
       final JLabel label = new JLabel();
       final Border selectedBorder = new EtchedBorder();
       final Border unselectedBorder = new EmptyBorder(selectedBorder
           .getBorderInsets(new JLabel()));
       label.setBorder(unselectedBorder);
       label.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e) {
           calendar.add(field, amount);
           Kalender.this.updatePanel();
         public void mouseEntered(MouseEvent e) {
           label.setBorder(selectedBorder);
         public void mouseExited(MouseEvent e) {
           label.setBorder(unselectedBorder);
       return label;
    private void initializeJPanel() {
       JPanel header = new JPanel();
       JLabel label;
       label = this.createUpdateButton(Calendar.YEAR, -1);
       label.setText("<<");
       header.add(label);
       label = this.createUpdateButton(Calendar.MONTH, -1);
       label.setText("<");
       header.add(label);
       monthLabel=new JLabel("");
       header.add(monthLabel);
       label = this.createUpdateButton(Calendar.MONTH, 1);
       label.setText(">");
       header.add(label);
       label = this.createUpdateButton(Calendar.YEAR, 1);
       label.setText(">>");
       header.add(label);
       this.setLayout(new BorderLayout());
       this.add(header, BorderLayout.NORTH);
    }

    I got you code to compile and run and made a single change to get it to work; adding a call to repaint at the end of the updatePanel method.
            this.add(days, BorderLayout.CENTER);
            this.revalidate();
            repaint();
        }Whenever you change the size of a containers components or add/remove components you must ask the container to run through its component hierarchy and check the size requirements of all its children and lay them out again, ie, do a new layout. The JComponent method for this isrevalidate. If you are working in the AWT you must use the Component/(overridden in)Container method validate, sometimes preceded by a call to the invalidate method. Some people prefer the validate method over revalidate. These are methods used to update guis by asking for a renewed layout. For economy you can call one (sometimes with invalidate, but rarely) of these methods on the smallest component/container that includes all the containers needing the renewed layout, ie, keep the action as localized as possible.
    When the rendering of components has changed, things like colors, borders and text, we need to ask the components to repaint themselves. The easy way to do this is to call repaint on the gui. For economy you can call repaint on the smallest component that contains all the components needing repainting. Some classes like those in the JTextComponent group have their own internal repainting calls so they will repaint themselves when changes are made.
    In making guis, especially elaborate ones, it seems to take some playful experimentation to find out what is needed to get what you want. Sometimes it is a call to revalidate, sometimes a call to repaint, sometimes both. You just have to experiment.

  • Swing components in applet not working in web browser

    Hi Guys,
    I've created an applet which makes use of some swing components, but unfortunately, not all of them function properly in my web browser (internet explorer or Mozilla Firefox). Its mainly the buttons; the last buttons works and displays the correct file within the broswer, but the first 5 buttons do not work...
    any help please on how I can sort this problem out?
    Heres the code for my applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    public class MainAppWindow extends JApplet
    int gapBetweenButtons = 5;
    final JPanel displayPanel = new JPanel(new BorderLayout());
    public void init()
       //Panel for overall display in applet window.
       JPanel mainPanel = new JPanel(new BorderLayout());
       mainPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/smalllogo2.gif"))),BorderLayout.NORTH);
       //sub mainPanel which holds all mainPanels together.
       JPanel holdingPanel = new JPanel(new BorderLayout());
       //Panel for displaying all slide show and applications in.
       displayPanel.setBackground(Color.white);
       displayPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/IntroPage.jpg"))),BorderLayout.CENTER);
       displayPanel.setPreferredSize(new Dimension(590,400));
       JPanel buttonPanel = new JPanel(new GridLayout(6,1,0,gapBetweenButtons));
       buttonPanel.setBackground(Color.white);
       JButton button1 = new JButton("User guide");
       button1.addActionListener(
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll(); // If there are any components in the mainPanel, remove them and then add label
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/UserGuide.jpg")));
                   displayPanel.revalidate(); // Validates displayPanel to allow changes to occur onto it, allowing to add different number images/applicaions to it.
       JButton button2 = new JButton("What is a Stack?");
       button2.addActionListener(
       new ActionListener() {
               public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/WhatIsAStack.jpg")));
                   displayPanel.revalidate();
       JButton button3 = new JButton("STACK(ADT)");
       button3.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StackADT.jpg")));
                   displayPanel.revalidate();
       JButton button4 = new JButton("Stacks in the Real World");
       button4.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StacksInTheRealWorld.jpg")));
                   displayPanel.revalidate();
       JButton button5 = new JButton("DEMONSTRATION");
       button5.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                 if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                 Demonstration app = new Demonstration();
                 JPanel appPanel = app.createComponents();//gets the created components from Demonstration application.
                 appPanel.setBackground(Color.pink);
               displayPanel.add(appPanel);
               displayPanel.revalidate();
       JButton button6 = new JButton("Towers Of Hanoi");
       button6.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                     if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                     TowerOfHanoi app = new TowerOfHanoi();
                     JPanel appPanel = app.createComponents();//gets the created components from Towers of Hanoi
                     JPanel mainPanel = new JPanel();//panel used to centralise the application in center
                     mainPanel.add(appPanel);
                     mainPanel.setBackground(Color.pink); //sets mainPanel's background color for 'Towers Of Hanoi'
                     displayPanel.add(mainPanel);
                     displayPanel.revalidate();
       //adding buttons to the buttonPanel.
       buttonPanel.add(button1);
       buttonPanel.add(button2);
       buttonPanel.add(button3);
       buttonPanel.add(button4);
       buttonPanel.add(button5);
       buttonPanel.add(button6);
       JPanel p = new JPanel(); // Used so that the buttons maintain their default shape
       p.setBackground(Color.white);
       p.add(buttonPanel);
       holdingPanel.add(p,BorderLayout.WEST);
       holdingPanel.add(displayPanel,BorderLayout.CENTER);
       //Positioning of holdingPanel in mainPanel.
       mainPanel.add(holdingPanel,BorderLayout.CENTER);
       //indent mainPanel so that its not touching the applet window frame.
       mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
       mainPanel.setBackground(Color.white);
       mainPanel.setPreferredSize(new Dimension(850,600)); //size of applet window
       mainPanel.setOpaque(false); // Needed for Applet
       this.setContentPane(mainPanel);
    }

    Thanks for the response. I don't quite understand what you're talking about though. I have, in my humble knowledge, done nothing with packages. I have put the applet class (WiaRekenToolActiz.class is the applet class) in the jar file wia_actiz_archive.jar. From what I read on the tutorial, java looks for the applet class in all the jar files specified. Since I put my CODEBASE as the main url, I thought it baiscally didn't matter where you out the html file.
    I shall include the complete html page complete with applet tag to perhaps illuminate a bit more what I mean...
    <html>
    <head>
    <title>Wia Rekenmodule hello!</title>
    </head>
    <body bgcolor="#C0C0C0">
    <applet
    CODEBASE= "http://www.creativemathsolutions.nl/test"
    ARCHIVE= "Actiz/wia_actiz_archive.jar, Generic/wia_archive.jar"
    CODE="WiaRekenToolActiz.class" 
    WIDTH=915 HEIGHT=555
    >
    <PARAM NAME = naam VALUE = "Piet Janssen">
    <PARAM NAME = gebdag VALUE = "01">
    <PARAM NAME = gebmaand VALUE = "06">
    <PARAM NAME = gebjaar VALUE = "1970">
    <PARAM NAME = geslacht VALUE = "man">
    <PARAM NAME = dienstjaren VALUE = "10">
    <PARAM NAME = salaris VALUE = "56500">
    <PARAM NAME = deeltijdpercentage VALUE = "100">
    <PARAM NAME = accountnaam VALUE = "Zorginstelling 'De Zonnebloem'">
    </applet>
    </body>
    </html>

  • Displaying custom drawn panels in a panel with FlowLayout vs GridLayout

    I am having trouble to display my custom panels(on which I have drawn) in another panel with FlowLayout. When I use this layout only a small part of their top-left corner appears, when using the GridLayout they are displayed as should, all. Why is this? Is there any way around it?
    The following is the code:
    package diagramillustrator;
    import java.awt.*;
    import java.util.Vector;
    import javax.swing.*;
    public class ClassDiagram extends JPanel
        //fields
        //<editor-fold>
        //general info
        public String title = "class";
        public String name;
        public Vector interfaces;
        public Vector exceptions;
        public String superclass;
        public Vector subClasses;
        public boolean superClass;
        public boolean subClass;
        public String dPackage;
        public String dExtends;
        //variables
        public FieldStructure field;
        //methods
        public MethodStructure constructor;
        public MethodStructure metho;
        //</editor-fold>
        /** Creates a new instance of ClassDiagram */
        public ClassDiagram()
            super();
            super.setSize(132,75);
        protected void paintComponent(Graphics g)
           setBackground(Color.WHITE);
           Graphics2D g2d = (Graphics2D) g;
           super.paintComponent(g2d);
           g2d.setStroke(new BasicStroke(2f));
           g2d.drawRect(1,1,132,25);
           g2d.setFont(new Font("arial", Font.BOLD, 12));
           g2d.drawString(title, 4,18);
           g2d.setColor(Color.LIGHT_GRAY);
           g2d.fillRect(1,25,132,25);
           g2d.setColor(Color.BLACK);
           g2d.drawRect(1,25,132,25);
           g2d.setColor(Color.WHITE);
           g2d.fillRect(1,51,132,25);
           g2d.setColor(Color.BLACK);
           g2d.drawRect(1,50,132,25);
        public static void main(String[] args)
            JFrame f = new JFrame("Testing ClassDiagram");
            f.setSize(500,400);
            //layout shows it correctly
            JPanel panel1 = new JPanel(new GridLayout());
            //layout shows it incorrectly
            //JPanel panel1 = new JPanel(new FlowLayout());
            panel1.setSize(200,200);
            ClassDiagram c1 = new ClassDiagram();
            ClassDiagram c2 = new ClassDiagram();
            ClassDiagram c3 = new ClassDiagram();
            panel1.add(c1);
            panel1.add(c2);
            panel1.add(c3);
            f.add(panel1);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.show();
    }Here is the main method included in the class(the main method is used for testing here) where the adding etc is done.
    public static void main(String[] args)
            JFrame f = new JFrame("Testing ClassDiagram");
            f.setSize(500,400);
            //layout shows it correctly
            JPanel panel1 = new JPanel(new GridLayout());
            //layout shows it incorrectly
            //JPanel panel1 = new JPanel(new FlowLayout());
            panel1.setSize(200,200);
            ClassDiagram c1 = new ClassDiagram();
            ClassDiagram c2 = new ClassDiagram();
            ClassDiagram c3 = new ClassDiagram();
            panel1.add(c1);
            panel1.add(c2);
            panel1.add(c3);
            f.add(panel1);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.show();
        }Please help.
    Thanks,
    AndXer

    Layout managers.
    JPanel panel1 = new JPanel(new GridLayout());GridLayout divides the availabale space into equal cells and expands each child component to fill the cell.
    JPanel panel1 = new JPanel(new FlowLayout());FlowLayout attempts to show each child component at its preferred size. The preferredSize is determined by the layout manager in the process of laying out the children. For a graphic component, ie, a component with no child components, the request for the components preferredSize will return the default size which is 10,10 for JPanel. Therefore you will need to either set the preferredSize for the gtaphic component or override the getPreferredSize method and return the desired Dimension. Another limitation of FlowLayout is that it attempts to lay its children out in&#8211;line.
    GridBagLayout also respects the preferredSize of child components and offers more versatility.
    import java.awt.*;
    import javax.swing.*;
    public class CD extends JPanel
        public String title = "class";
        public CD()
            super();
            setPreferredSize(new Dimension(132,75));
            setBackground(Color.WHITE);
        protected void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D) g;
            super.paintComponent(g2d);
            g2d.setStroke(new BasicStroke(2f));
            g2d.drawRect(1,1,130,25);
            g2d.setFont(new Font("arial", Font.BOLD, 12));
            g2d.drawString(title, 4,18);
            g2d.setColor(Color.LIGHT_GRAY);
            g2d.fillRect(1,25,130,25);
            g2d.setColor(Color.BLACK);
            g2d.drawRect(1,25,130,25);
            g2d.setColor(Color.WHITE);
            g2d.fillRect(1,51,130,25);
            g2d.setColor(Color.BLACK);
            g2d.drawRect(1,50,130,25);
        public static void main(String[] args)
            JPanel panel1 = new JPanel(new GridBagLayout());
            // This has little affect until after realization and
            // is then subject to its parent layout manager. Use
            // the preferredSize for better results.
            //panel1.setSize(200,200);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            // Add some components
            int n = 5;
            // and specify columns
            int cols = 3;
            for(int j = 0; j < n; j++) {
                gbc.gridwidth = ((j+1) % cols == 0) ? GridBagConstraints.REMAINDER
                                                    : 1;
                panel1.add(new CD(), gbc);
            JFrame f = new JFrame("Testing ClassDiagram");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(panel1);
            f.setSize(500,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Swing bug?: scrolling BLIT_SCROLL_MODE painting JTextArea components hangs

    java version "1.5.0_04"
    Hello,
    When drawing JComponent Text Areas and dynamically scrolling, Java gets confused, gets the shivers and freezes when the viewport cannot get its arms around the canvas. ;)
    Possible problem at JViewport.scrollRectToVisible().
    When painting non-text area components eg. graphics circles, it is ok.
    Have provided example code. This code is based on the ScrollDemo2 example provided in the Sun Java
    Tutorial
    thanks,
    Anil Philip
    juwo LLC
    Usage: run program and repeatedly click the left mouse button near right boundary to create a new JComponent node each time and to force scrolling area to increase in size to the right.
    When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers and hangs.
    The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal application) unpainted sometimes.
    * to show possible bug when in the default BLIT_SCROLL_MODE and with JTextArea components.
    * author: Anil Philip. juwo LLC. http://juwo.com
    * Usage: run program and repeatedly click the left mouse button near right boundary to
    * create a new JComponent node each time and to force scrolling area to increase in size to the right.
    * When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers
    and hangs.
    * The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal
    application)
    * unpainted sometimes.
    * This code is based on the ScrollDemo2 example provided in the Sun Java Tutorial (written by John
    Vella, a tutorial reader).
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    /* ScrollDemo2WithBug.java is a 1.5 application that requires no other files. */
    public class ScrollDemo2WithBug extends JPanel {
    private Dimension area; //indicates area taken up by graphics
    private Vector circles; //coordinates used to draw graphics
    private Vector components;
    private JPanel drawingPane;
    public ScrollDemo2WithBug() {
    super(new BorderLayout());
    area = new Dimension(0, 0);
    circles = new Vector();
    components = new Vector();
    //Set up the instructions.
    JLabel instructionsLeft = new JLabel(
    "Click left mouse button to place a circle.");
    JLabel instructionsRight = new JLabel(
    "Click right mouse button to clear drawing area.");
    JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
    instructionPanel.add(instructionsLeft);
    instructionPanel.add(instructionsRight);
    //Set up the drawing area.
    drawingPane = new DrawingPane();
    drawingPane.setBackground(Color.white);
    drawingPane.setPreferredSize(new Dimension(200, 200));
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new JScrollPane(drawingPane);
    // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
    if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
    System.out.println("BACKINGSTORE_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
    System.out.println("BLIT_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
    System.out.println("SIMPLE_SCROLL_MODE");
    //Lay out this demo.
    add(instructionPanel, BorderLayout.PAGE_START);
    add(scroller, BorderLayout.CENTER);
    /** The component inside the scroll pane. */
    public class DrawingPane extends JPanel implements MouseListener {
    private class VisualNode {
    int x = 0;
    int y = 0;
    int id = 0;
    public VisualNode(int id, int x, int y) {
    this.id = id;
    this.x = x;
    this.y = y;
    title.setLineWrap(true);
    title.setAlignmentY(Component.TOP_ALIGNMENT);
    titlePanel.add(new JButton("Hi!"));
    titlePanel.add(title);
    nodePanel.add(titlePanel);
    nodePanel.setBorder(BorderFactory
    .createEtchedBorder(EtchedBorder.RAISED));
    box.add(nodePanel);
    ScrollDemo2WithBug.this.drawingPane.add(box);
    Box box = Box.createVerticalBox();
    Box titlePanel = Box.createHorizontalBox();
    JTextArea title = new JTextArea(1, 10); // 1 rows x 10 cols
    Box nodePanel = Box.createVerticalBox();
    public void paintNode(Graphics g) {
    int ix = (int) x + ScrollDemo2WithBug.this.getInsets().left;
    int iy = (int) y + ScrollDemo2WithBug.this.getInsets().top;
    title.setText(id + " (" + ix + "," + iy + ") ");
    box.setBounds(ix, iy, box.getPreferredSize().width, box
    .getPreferredSize().height);
    int n = 0;
    DrawingPane() {
    this.setLayout(null);
    addMouseListener(this);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fill3DRect(10, 10, 25, 25, true);
    Point point;
    for (int i = 0; i < circles.size(); i++) {
    point = (Point) circles.elementAt(i);
    VisualNode node = (VisualNode) components.get(i);
    node.paintNode(g);
    //Handle mouse events.
    public void mouseReleased(MouseEvent e) {
    final int W = 100;
    final int H = 100;
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    //This will clear the graphic objects.
    circles.removeAllElements();
    area.width = 0;
    area.height = 0;
    changed = true;
    } else {
    int x = e.getX() - W / 2;
    int y = e.getY() - H / 2;
    if (x < 0)
    x = 0;
    if (y < 0)
    y = 0;
    Point point = new Point(x, y);
    VisualNode node = new VisualNode(circles.size(), point.x,
    point.y);
    // add(node);
    components.add(node);
    circles.addElement(point);
    drawingPane.scrollRectToVisible(new Rectangle(x, y, W, H));
    int this_width = (x + W + 2);
    if (this_width > area.width) {
    area.width = this_width;
    changed = true;
    int this_height = (y + H + 2);
    if (this_height > area.height) {
    area.height = this_height;
    changed = true;
    if (changed) {
    //Update client's preferred size because
    //the area taken up by the graphics has
    //gotten larger or smaller (if cleared).
    drawingPane.setPreferredSize(area);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingPane.revalidate();
    drawingPane.repaint();
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ScrollDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ScrollDemo2WithBug();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.setSize(800, 600);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    I changed the name so you can run this as-is without name clashing. It works okay now.
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SD2 extends JPanel {
        public SD2() {
            super(new BorderLayout());
            //Set up the instructions.
            JLabel instructionsLeft = new JLabel(
                    "Click left mouse button to place a circle.");
            JLabel instructionsRight = new JLabel(
                    "Click right mouse button to clear drawing area.");
            JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
            instructionPanel.add(instructionsLeft);
            instructionPanel.add(instructionsRight);
            //Set up the drawing area.
            DrawingPane drawingPane = new DrawingPane(this);
            drawingPane.setBackground(Color.white);
            drawingPane.setPreferredSize(new Dimension(200, 200));
            //Put the drawing area in a scroll pane.
            JScrollPane scroller = new JScrollPane(drawingPane);
            // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
                System.out.println("BACKINGSTORE_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
                System.out.println("BLIT_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
                System.out.println("SIMPLE_SCROLL_MODE");
            //Lay out this demo.
            add(instructionPanel, BorderLayout.PAGE_START);
            add(scroller, BorderLayout.CENTER);
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("ScrollDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new SD2();
            newContentPane.setOpaque(true);      //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.setSize(800, 600);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    /** The component inside the scroll pane. */
    class DrawingPane extends JPanel implements MouseListener {
        SD2 sd2;
        private Dimension area;     //indicates area taken up by graphics
        private Vector circles;     //coordinates used to draw graphics
        private Vector components;
        int n = 0;
        final int
            W = 100,
            H = 100;
        DrawingPane(SD2 sd2) {
            this.sd2 = sd2;
            area = new Dimension(0, 0);
            circles = new Vector();
            components = new Vector();
            this.setLayout(null);
            addMouseListener(this);
         * The 'paint' method is a Container method and it passes its
         * Graphics context, g, to each of its Component children which
         * use it to draw themselves into the parent. JComponent overrides
         * this Container 'paint' method and in it calls this method in
         * addition to others - see api. So the children of DrawingPane will
         * each paint themselves. Here you can do custom painting/rendering.
         * But this is not the place to ask components to paint themselves.
         * That would get swing very confused...
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fill3DRect(10, 10, 25, 25, true);
            g.setColor(Color.red);
            Point point;
            for (int i = 0; i < circles.size(); i++) {
                point = (Point) circles.elementAt(i);
                g.fillOval(point.x-2, point.y-2, 4, 4);
        //Handle mouse events.
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                //This will clear the graphic objects.
                circles.removeAllElements();
                components.removeAllElements();
                removeAll();                    // to clear the components
                area.width = 0;
                area.height = 0;
                setPreferredSize(area);
                revalidate();
                repaint();
            } else {
                int x = e.getX() - W / 2;
                int y = e.getY() - H / 2;
                if (x < 0)
                    x = 0;
                if (y < 0)
                    y = 0;
                Point point = new Point(x, y);
                VisualNode node = new VisualNode(this, circles.size(), point.x, point.y);
                // add(node);
                components.add(node);       // not needed
                circles.addElement(point);
                checkBoundries(x, y, node);
        private void checkBoundries(int x, int y, VisualNode node) {
            boolean changed = false;
            // since we used the setPreferredSize property to set the size
            // of each box we'll have to use it again to let the JScrollPane
            // know what size we need to show all our child components
            int this_width = (x + node.box.getPreferredSize().width + 2);
            if (this_width > area.width) {
                area.width = this_width;
                changed = true;
            int this_height = (y + node.box.getPreferredSize().height + 2);
            if (this_height > area.height) {
                area.height = this_height;
                changed = true;
            if (changed) {
                //Update client's preferred size because
                //the area taken up by the graphics has
                //gotten larger or smaller (if cleared).
                setPreferredSize(area);
                scrollRectToVisible(new Rectangle(x, y, W, H));
                //Let the scroll pane know to update itself
                //and its scrollbars.
                revalidate();
            repaint();
        public void mouseReleased(MouseEvent e) { }
        public void mouseClicked(MouseEvent e)  { }
        public void mouseEntered(MouseEvent e)  { }
        public void mouseExited(MouseEvent e)   { }
    * We are adding components to DrawingPanel so there is no need to get
    * into the paint methods of DrawingPane. Components are designed to draw
    * themseleves when their parent container passes them a Graphics context
    * and asks them to paint themselves into the parent.
    class VisualNode {
        DrawingPane drawPane;
        int x;
        int y;
        int id;
        Box box;
        public VisualNode(DrawingPane dp, int id, int x, int y) {
            drawPane = dp;
            this.id = id;
            this.x = x;
            this.y = y;
            box = Box.createVerticalBox();
            Box titlePanel = Box.createHorizontalBox();
            JTextArea title = new JTextArea(1, 10);     // 1 rows x 10 cols
            Box nodePanel = Box.createVerticalBox();
            title.setLineWrap(true);
            title.setAlignmentY(Component.TOP_ALIGNMENT);
            titlePanel.add(new JButton("Hi!"));
            titlePanel.add(title);
            nodePanel.add(titlePanel);
            nodePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
            box.add(nodePanel);
            // here we are adding a component to drawPane so there is really
            // no need to keep this VisualNode in a collection
            drawPane.add(box);
            int ix = (int) x + drawPane.getInsets().left;
            int iy = (int) y + drawPane.getInsets().top;
            title.setText(id + " (" + ix + "," + iy + ") ");
            // since we are using the preferredSize property to setBounds here
            // we'll need access to it (via box) for the scrollPane in DrawPane
            // so we expose box as a member variable
            box.setBounds(ix, iy, box.getPreferredSize().width,
                                  box.getPreferredSize().height);
    }

Maybe you are looking for