Reputation: 375
I want to make with swing this interface:
And when I resise it I want all the subpanels and buttons to be resized like this:
Not only main window to be resized. I am using GridBagLayout. And I dont know how to stick the borders of the panel with GridBagLayout to the borders of the Frame in that way, when I am resizing the frame the panel also to be resized.
Upvotes: 3
Views: 165
Reputation: 24626
The property to achieve this, i.e. when JFrame is resized the JPanel should also resize itself, will be GridBagConstraints.BOTH
. It appears to me that your Left JButton is a bit smaller than the Right JButton. If you really wanted to achieve this with GridBagLayout, here I have crafted a small sample code for your help, have a look and ask any question that may arise :
import java.awt.*;
import javax.swing.*;
public class GridBagExample
{
private JPanel contentPane;
private void displayGUI()
{
JFrame frame = new JFrame("GridBag Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.CYAN);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH; // appears to me this is what you wanted
contentPane.add(centerPanel, gbc);
JButton leftButton = new JButton("Left");
JButton rightButton = new JButton("Right");
gbc.gridwidth = 1;
gbc.gridy = 1;
gbc.weightx = 0.3;
gbc.weighty = 0.1;
contentPane.add(leftButton, gbc);
gbc.gridx = 1;
gbc.weightx = 0.7;
gbc.weighty = 0.1;
contentPane.add(rightButton, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new GridBagExample().displayGUI();
}
});
}
}
Upvotes: 3
Reputation: 2549
I normally use nested layouts for this.
JPanel
with a BorderLayout
as the base. JPanel
, and add this to the CENTER
of the BorderLayout
. JPanel
s. JPanel
with a GridLayout of 1 row and 2 columns. JPanel
s to it in the correct order. JPanel
to the SOUTH
of the BorderLayout
.Upvotes: 9