Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default [SOLVED] Problem with GridBagLayout

    Hi guys,

    I have a problem with arranging my components in a GridBagLayout.

    The frame is 600x600. Inside it, there are two pairs of (Label,TextField). They are not where I want them to be. What I would like is to have them all at the top of the frame, one after each other. Moreover, I would like all the labels aligned together (easy) but also all the textField aligned together...

    Now, my pairs of (Label,TextField) are spread all over the panel, they aren't all at the top. The second pair is at the middle of the frame, and I would like it to be right after the first pair, just following it. And of course, the frame have to stay 600x600. I would like to be able to do that using the GridBagLayout because it will be useful later if I need to do any modification.

    I probably did all wrong with the anchors.

    Any idea how to get this result ?

    Thanks heaps!

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class GUI_example extends JFrame {
    	
    	private final static long serialVersionUID = 1L;
    	
    	JFrame frame;
    
    	JLabel labelIndex;
    	JLabel labelCategory;
    	JLabel labelUnicode;
    	
    	JTextField textFieldIndex;
    	JTextField textFieldCategory;
    	JTextField textFieldUnicode;
    	
    	public GUI_example() {
    		super();
    		createGUI();
    	}
    
    	public void createGUI() {
    
    		frame = new JFrame();
    		frame.setPreferredSize(new Dimension(600,600));
    	    frame.setTitle("Hello!");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          
            Container pane = frame.getContentPane();
            pane.setLayout(new GridBagLayout());
        	
        	GridBagConstraints c1 = new GridBagConstraints();
        	
        	labelIndex = new JLabel("Index: ");
        	c1.anchor = GridBagConstraints.NORTHWEST;
        	c1.weightx = 0.5;
        	c1.weighty = 0.5;
        	c1.ipady = 10;
        	c1.gridx = 0;
        	c1.gridy = 0;
        	pane.add(labelIndex,c1);
        	
        	textFieldIndex = new JTextField("Some index...");
        	c1.gridx = 1;
        	c1.gridy = 0;
        	pane.add(textFieldIndex,c1);
        	
        	labelCategory = new JLabel("Category: ");
        	c1.anchor = GridBagConstraints.NORTHWEST;
        	c1.weightx = 0.5;
        	c1.weighty = 0.5;
        	c1.gridx = 0;
        	c1.gridy = 1;
        	pane.add(labelCategory,c1);
        
        	textFieldCategory = new JTextField("Some category...");
        	c1.gridx = 1;
        	c1.gridy = 1;
        	pane.add(textFieldCategory,c1);
        	
            frame.pack();
            frame.setVisible(true);
    	}
    
    	public static void main(String[] args) {	
    		new GUI_example();
    	}
    	
    }
    Last edited by ze snow; 02-27-2010 at 04:33 PM.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

  3. #3
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    Yes probably :)
    I already looked that website, actually that's the one I was currently on.
    I have been on that one :

    GridBagLayout (Java Platform SE 6)

    I think it's maybe the BASELINE from anchor but I still don't understand how it works, also they talk a lot about the prevailing row but again, doesn't really understand.

    Is it something to do with Baseline ?

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Anchor works within a "cell", not within a "panel". I.E. you separate your panel into an imaginary grid where the columns and rows have sometimes disparate sizes (weightx and weighty). Then you assign a component to occupy one (gridx and gridy) or more (gridwidth and gridheight combined with x and y) of those cells and, where, within that space, it should "anchor" (anchor) itself, as well as how much of that space it should use (fill), how much space between that "space" and the other "cells" should exist (insets), and how much space should exist between the component and the "edges" of it's cell(s) (ipadx and ipady).

  5. #5
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    Yes but they say anchor is to choose where to put the component in the space it is displayed, so here my JLabel wants to be displayed in my JPanel...

    So, you tried to say that gridbaglayout can't fill my request ?
    Normally i thought gridbaglayout is the most complex one and can do almost any behavior, that's why I chose it straight away...

    What's the best layout to use according to what I want to display ?

  6. #6
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Read my post again, carefully this time.

    The "space" is not the entire panel!

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, there are other layouts that are easier to use than GridBagLayout. If you posted a pic of how you'd like your app to appear, we may be able to help you better. Also, you should post a Short, Self Contained, Correct (Compilable), Example (please see the link for details) and let us run your layout code ourselves.

    Much luck!

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,453
    Rep Power
    20

    Default

    Quote Originally Posted by masijade View Post
    Anchor works within a "cell", not within a "panel". I.E. you separate your panel into an imaginary grid where the columns and rows have sometimes disparate sizes (weightx and weighty). Then you assign a component to occupy one (gridx and gridy) or more (gridwidth and gridheight combined with x and y) of those cells and, where, within that space, it should "anchor" (anchor) itself, as well as how much of that space it should use (fill), how much space between that "space" and the other "cells" should exist (insets), and how much space should exist between the component and the "edges" of it's cell(s) (ipadx and ipady).
    That is about the best and most concise description of GBL behavior I've ever seen. Thanks, masijade.

    db

  9. #9
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Quote Originally Posted by Darryl.Burke View Post
    Thanks, masijade.

    db
    Welcome. ;-)

  10. #10
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Maybe I'll look later. Right now I don't have the time to dig through it and compare what it is doing with what you actually want.

  11. #11
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    ok thank you!

    During this time, if other people also have some ideas, welcome :)

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    An example that mixes layouts. It uses a GridBagLayout to layout the JLabels and JTextFields, but then places this JPanel in the BorderLayout.NORTH position of another JPanel that uses BorderLayout, and then this JPanel is placed BorderLayout.CENTER in the main JPanel that also uses BorderLayout.

    I'm not sure if this is what you're looking for, and if not, please go into greater detail on what you are trying to achieve as well as post an image or two of what the GUI is supposed to look like:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.TitledBorder;
    
    public class GUI2b {
      private static final Dimension APP_SIZE = new Dimension(750, 550);
      public static final String[] LABEL_STRINGS = {"Index:", "Category:", "Unicode"};
      private JPanel mainPanel = new JPanel();
      private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
    
      public GUI2b() {
        mainPanel.setPreferredSize(APP_SIZE);
        mainPanel.setLayout(new BorderLayout());
        
        mainPanel.add(createTopRightPanel(), BorderLayout.CENTER);
        mainPanel.add(createTopLeftPanel(), BorderLayout.WEST);
        mainPanel.add(createSouthPanel(), BorderLayout.SOUTH);
      }
    
      private JPanel createTopRightPanel() {
        JPanel innerTopPanel = new JPanel(new GridBagLayout());
        int index = 0;
        for (String labelString : LABEL_STRINGS) {
          JLabel label = new JLabel(labelString);
          JTextField textField = new JTextField();
          fieldMap.put(labelString, textField);
          
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx = 0; 
          gbc.gridy = index;
          gbc.gridheight = 1;
          gbc.gridwidth = 1;
          gbc.weightx = 1.0;
          gbc.weighty = 0;
          gbc.anchor = GridBagConstraints.LINE_START;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.insets = new Insets(5, 5, 5, 20);
          innerTopPanel.add(label, gbc);
          
          gbc.gridx = 1;
          gbc.gridwidth = 3;
          gbc.weightx = 3.0;
          gbc.anchor = GridBagConstraints.LINE_END;
          gbc.insets = new Insets(5, 5, 5, 5);
          innerTopPanel.add(textField, gbc);
          
          index++;
        }
        
        
        JPanel topRightPanel = new JPanel(new BorderLayout());
        topRightPanel.setBorder(BorderFactory.createCompoundBorder(
            new TitledBorder("Title"), 
            new EmptyBorder(10, 10, 10, 10)));
        topRightPanel.add(innerTopPanel, BorderLayout.NORTH);
        return topRightPanel;
      }
    
      private JPanel createTopLeftPanel() {
        JPanel tlPanel = new JPanel();
        tlPanel.setBorder(new TitledBorder("title"));
        tlPanel.setPreferredSize(new Dimension(250, 100));
        return tlPanel;
      }
    
      private JPanel createSouthPanel() {
        JPanel southPanel = new JPanel();
        southPanel.setBorder(new TitledBorder("title"));
        southPanel.setPreferredSize(new Dimension(200, 150));
        return southPanel;
      }
      
      public String getFieldText(String key) {
        return fieldMap.get(key).getText();
      }
    
      public JComponent getComponent() {
        return mainPanel;
      }
    
      private static void createAndShowUI() {
        JFrame frame = new JFrame("GUI2b");
        frame.getContentPane().add(new GUI2b().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }

  13. #13
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    Ok, I edited my post above, have a look please.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    And I've added a post above yours. Have a look please.

  15. #15
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    Oops sorry, I didn't see.
    Thanks a lot, that's exactly what I meant!

    hmm, quite complex then, I thought we could do it without using 2 layouts :)

    And btw, can you tell me why in the "main", you wrote

    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    createAndShowUI();
    }
    });

    what's the purpose of surrounding the createAndShowUI() with a runnable ?

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by ze snow View Post
    Oops sorry, I didn't see.
    Thanks a lot, that's exactly what I meant!

    hmm, quite complex then, I thought we could do it without using 2 layouts :)
    Personally, I think that it's much easier to nest layouts and to avoid using GridBagLayout unless absolutely necessary.

    And btw, can you tell me why in the "main", you wrote

    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    createAndShowUI();
    }
    });

    what's the purpose of surrounding the createAndShowUI() with a runnable ?
    Swing code should only be called on the EDT, the Event Dispatch Thread, which is the main thread reserved for Swing to do its painting and user interaction. Calling the code as above does just this: the code in the runnable is placed into a queue that is called on the EDT. It can help prevent the occurrence of pernicious intermittent threading errors in your Swing apps.

  17. #17
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

    Default

    Ok I see!

    Thanks heaps Fubarable!

  18. #18
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    To tell you the truth, I see no reason to have to "avoid" using GBL, but hey. I lost all further interest in this thread after seeing two cross-posts on the same topic (opened after he posted his code) on another site without any indiciation that he was already receiving more than enough help right here, and still showing no understanding (or desire to understand) what anchors actually are and how they are used.

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by masijade View Post
    To tell you the truth, I see no reason to have to "avoid" using GBL, but hey. I lost all further interest in this thread after seeing two cross-posts on the same topic (opened after he posted his code) on another site without any indiciation that he was already receiving more than enough help right here, and still showing no understanding (or desire to understand) what anchors actually are and how they are used.
    To the OP, please read this link and address this issue: BeForthrightWhenCrossPostingToOtherSites

    The link will tell you why this is an issue with us.

  20. #20
    ze snow is offline Member
    Join Date
    Feb 2010
    Posts
    29
    Rep Power
    0

Page 1 of 2 12 LastLast

Similar Threads

  1. GridBagLayout
    By Moncleared in forum New To Java
    Replies: 1
    Last Post: 10-18-2009, 11:12 PM
  2. GridBagLayout
    By MuslimCoder in forum New To Java
    Replies: 1
    Last Post: 01-15-2009, 09:54 PM
  3. abt gridbaglayout
    By pinky in forum AWT / Swing
    Replies: 1
    Last Post: 12-15-2008, 09:35 AM
  4. Java Swing GridBagLayout Problem
    By hemanthjava in forum AWT / Swing
    Replies: 1
    Last Post: 06-29-2008, 09:51 PM
  5. Problem with GridBagLayout
    By Daniel in forum SWT / JFace
    Replies: 2
    Last Post: 07-01-2007, 07:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •