Note that there are some explanatory texts on larger screens.

plurals
  1. POJava/Swing: Trying to get BorderLayout to play nice with GridBagLayout
    text
    copied!<p>I'd like to have a window that has 3 menus, one tied to the left, another tied to the center and the last one tied to the right. Like this:</p> <pre><code>-------------------------------------------- -toolbar1---------toolbar2---------toolbar3- -------------------------------------------- - - - rest of the window does something here - </code></pre> <p>The problem I'm having is that this is the result I get:</p> <pre><code>-------------------------------------------- ---------toolbar1toolbar2toolbar3----------- -------------------------------------------- - - - rest of the window does something here - </code></pre> <p>Here's some sample code (compiles and shows the problem):</p> <pre><code>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class TestClass extends JFrame { public TestClass() { super("test"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); final JPanel upper = new JPanel(); upper.setLayout(new GridBagLayout()); final GridBagConstraints gbc = new GridBagConstraints(); final JButton toolbar1 = new JButton("toolbar1"); final JButton toolbar2 = new JButton("toolbar2"); final JButton toolbar3 = new JButton("toolbar3"); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; upper.add(toolbar1, gbc); gbc.gridx = 1; gbc.anchor = GridBagConstraints.CENTER; upper.add(toolbar2, gbc); gbc.gridx = 2; gbc.anchor = GridBagConstraints.EAST; upper.add(toolbar3, gbc); add(upper, BorderLayout.NORTH); final JPanel something = new JPanel(); something.setBackground(Color.WHITE); something.setPreferredSize(new Dimension(600, 600)); something.repaint(); add(something, BorderLayout.CENTER); pack(); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { final TestClass test = new TestClass(); } } </code></pre> <p>How can I fix it? I thought that by setting the <code>anchor</code> in the GridBagConstraints I'd take care of it, but that didn't work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload