0

I'm trying to build a simple layout, with :

** first row is consisted of : 3 JComboboxes. ** second row of one JTextArea ** third row of 3 buttons. 

However, I'm getting this weird layout :

enter image description here

How can I make everything seem without all these insanse gaps, and set a sensible height to the components (it seems it takes up the whole frame currently for some reason)?

My code :

 mainFrame.setSize(500,600); mainFrame.setLayout(new GridLayout(0,1,0,0)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); JPanel datePanel = new JPanel(new GridLayout(1,3,0,0)); String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; JComboBox petList = new JComboBox( petStrings ); JComboBox petList2 = new JComboBox( petStrings ); JComboBox petList3 = new JComboBox( petStrings ); datePanel.add( petList ); datePanel.add( petList2 ); datePanel.add( petList3 ); mainFrame.add( datePanel ); JPanel controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); final JTextArea commentTextArea = new JTextArea("",7,25); JScrollPane scrollPane = new JScrollPane(commentTextArea); controlPanel.add(scrollPane); mainFrame.add(controlPanel); JPanel buttonsPanel = new JPanel( new GridLayout(0,1,10,10) ); buttonsPanel.add( new JButton("x") ); buttonsPanel.add( new JButton("y") ); buttonsPanel.add( new JButton("z") ); mainFrame.add( buttonsPanel ); 
2
  • You do this by using LayoutManagers correctly. Which layout manager? There's a lot of ways you can do this, so your question is too broad Commented Nov 20, 2017 at 18:44
  • Use different layout managers, maybe a combination of GridLayout and GridBagLayout Commented Nov 20, 2017 at 21:18

1 Answer 1

1

However, I'm getting this weird layout :

You are using a GridLayout so that is what the GridLayout does. It makes each cell in the grid the same size.

You need to use a different layout manager or combination of layout managers.

Maybe the default BorderLayout of the frame would work for you:

  1. You create a JPanel which uses the FlowLayout and then add the combo boxes to the panel. Then add the panel to frame using the BorderLayout.PAGE_START as the constraint
  2. Then you add the text area to the BorderLayout.CENTER
  3. Then you create a panel for the buttons and add them to the BorderLayout.PAGE_END.

Or if you don't want to nest layouts then you could use a GridBagLayout.

We can't give you an exactly solution so you need to play with different layout managers. Read the Swing tutorial on Layout Manager for more information and working examples to get you started.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.