I haven't really worked with Swing at all in Java. I'm experimenting with it. I want to make a set layout that the size can't be changed. I've seen alot of things suggesting to use Layout managers to add multiple JPanels into a JFrame.
However, all the tutorials I've seen involving layout managers say it allows for the user to resize the screen. The layout I want has a rectangle going along the left hand side, a thin rectangle going along the bottom, and a third rectangle taking up the rest of the space. I attempting it using an Absolute layout but it just doesn't want to work for me.
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test extends JFrame {
public Test() {
JPanel rect1 = new JPanel();
rect1.setBounds(101, 650, 900, 50);
rect1.setBackground(Color.RED);
getContentPane().add(rect1);
JPanel rect2 = new JPanel();
rect2.setBounds(0, 650, 100, 1000);
rect2.setBackground(Color.BLUE);
getContentPane().add(rect2);
JPanel rect3 = new JPanel();
rect3.setBounds(101, 700, 900, 950);
rect3.setBackground(Color.GREEN);
getContentPane().add(rect3);
setTitle("TEST");
setSize(1000, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test ex = new Test();
ex.setVisible(true);
}
});
}
}
Can someone help me properly make three Jpanels in a Jframe in this layout (all with different colors)?
You might be able to achieve the same thing using a BorderLayout as the bases or even a GridBagLayout.
The main piece you are missing is the fact that layout managers use (or can use depending on the layout manager) the component's preferred/minimum/maximum size
Basically, what you would do is define a custom component (extending from something like JPanel) and override it's getPreferredSize method and return the required value you need. Depending on the layout manager, you may also need to override the getMaximumSize and getMinimumSize methods as well.
For example...
Basically, this shows the "default" size and what happens when the screen is resized...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FixedSizeLayout {
public static void main(String[] args) {
new FixedSizeLayout();
}
public FixedSizeLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new ContentPane(), gbc);
gbc.gridx++;
add(new LeftPane(), gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 1;
add(new BottomPane(), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ContentPane extends JPanel {
public ContentPane() {
setBackground(Color.GREEN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
}
public class BottomPane extends JPanel {
public BottomPane() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 50);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
}
public class LeftPane extends JPanel {
public LeftPane() {
setBackground(Color.BLUE);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 150);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
}
}
Now, if you prefer, you can make the screen non-resizable, but I for one won't like you. I prefer to use the power of the layout managers and allow users to make decisions about how they want to view the content ... where I can ... but that's just me (I don't like non-resizable windows except in the case of some dialogs)
You can use setResizable(). Please refer to below code fragment.
setResizable(false); // this will not allow resizing
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
AbsoluteLayout is no go. Don't do that. You are probably looking for BorderLayout. Check the tutorial: How to Use BorderLayout for details. If you don't want your JFrame to be able to re-size use frame.setResizable(false); on it.
Just use simple BorderLayout and it will resize automatically:
JPanel panel = new JPanel(new BorderLayout());
panel.add(greenPanel, BorderLayout.CENTER);
panel.add(redPanel, BorderLayout.SOUTH);
panel.add(bluePanel, BorderLayout.EAST);
You can use MigLayout and replace BorderLayout.CENTER by "dock center":
JPanel panel = new JPanel(new MigLayout(" insets 0"));
panel.add(greenPanel, "dock center");
panel.add(redPanel, "dock south");
panel.add(bluePanel, "dock east");
Read more about MigLayout here: http://www.miglayout.com/QuickStart.pdf
Related
JTextField, JSlider, JComboBox, etc added to a JComponent are not displayed in the JFrame containing the JComponent. It seems only drawing by the Graphics parameter allows painting. The included test program compares using JPanel to JComponent in my efforts to discover how to display components added to a JComponent. Is there any way to get such components displayed?
public class TestPaints {
public static void main(String[] args) {
new TestPaints();
}
JTextField _text1;
JLabel _label1 = new JLabel("Text1");
JTextField _text2;
JLabel _label2 = new JLabel("Text2");
TestPaints() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Paint a Widget");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2));
GridBagConstraints grid = new GridBagConstraints();
frame.add(new JLabel("TextField in JComponent "));
grid.gridx = 2;
frame.add(new JLabel("TextField in JPanel"), grid);
grid.gridy = 2;
grid.gridx = 1;
frame.add(new TestJComponent(), grid);
grid.gridx = 2;
frame.add(new TestJPanel(), grid);
grid.gridy = 3;
grid.gridx = 1;
/* tabbing between the two TextFields shows that keystrokes are seen */
frame.add(_label1, grid);
grid.gridx = 2;
frame.add(_label2, grid);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestJComponent extends JComponent {
public TestJComponent() {
setPreferredSize(new Dimension(100, 30));
_text1 = new JTextField(6);
_text1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
_label1.setText(_text1.getText());
_label1.repaint();
}
});
_text1.setOpaque(true);
_text1.setVisible(true);
add(_text1);
/* This doesn't work
JPanel panel = new JPanel();
panel.add(_text1);
add(panel); */
setOpaque(true);
setVisible(true);
setBackground(Color.green);
}
public void paint(Graphics g) {
super.paint(g); // did not do background. Rectangle r = g.getClipBounds(); // needs this
g.setColor(getBackground());
g.fillRect(r.x, r.y, r.width, r.height);
/* Variations such as these don't work */
_text1.setOpaque(true);
_text1.setVisible(true);
_text1.paintComponents(g);
}
}
class TestJPanel extends JPanel {
TestJPanel() {
_text2 = new JTextField(6);
_text2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
_label2.setText(_text2.getText());
_label2.repaint();
}
});
add(_text2);
setBackground(Color.blue);
}
}
}
Edit: you need to give your JComponent a layout such as FlowLayout for components to show properly since it does not have a default layout like JPanel has. So add setLayout(new FlowLayout()) into your JComponent's constructor
You have:
frame.setLayout(new GridLayout(3, 2));
and then try to add components to the JFrame's contentPane using GridBagConstraints, and this doesn't make sense. If you want to use these constraints, then the container needs to use GridBagLayout, not GridLayout.
Also this is dangerous code:
public void paint(Graphics g) {
super.paint(g); // did not do background. Rectangle r = g.getClipBounds(); // needs this
g.setColor(getBackground());
g.fillRect(r.x, r.y, r.width, r.height);
/* Variations such as these don't work */
_text1.setOpaque(true);
_text1.setVisible(true);
_text1.paintComponents(g);
}
You should be overriding JComponent's paintComponent method, not its paint method (call super.paintComponent) and should not be setting component visibility or calling a component's paintComponents method directly within any painting method.
Another issue: don't use KeyListeners within Swing text components but rather add a DocumentListener to the component's Document. Otherwise you risk breaking some of the functionality of the text component, and also your listener won't work for copy/paste, while the DocumentListener will.
And another issue, your main issue: you need to give the JComponent a layout. It does not default to FlowLayout like a JPanel does. This is why the added components are not showing within it.
For example:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class TestPaints2 {
private JTextField textField1 = new JTextField(8);
private JTextField textField2 = new JTextField(8);
private JLabel label1 = new JLabel("Text1");
private JLabel label2 = new JLabel("Text2");
public TestPaints2() {
textField1.getDocument().addDocumentListener(new MyDocListener(label1));
textField2.getDocument().addDocumentListener(new MyDocListener(label2));
TestJComponent2 jComponent = new TestJComponent2();
jComponent.add(textField1);
TestJPanel2 jPanel = new TestJPanel2();
jPanel.add(textField2);
JPanel mainPanel = new JPanel(new GridLayout(0, 2));
mainPanel.add(new JLabel("JComponent"));
mainPanel.add(new JLabel("JPanel"));
mainPanel.add(jComponent);
mainPanel.add(jPanel);
mainPanel.add(label1);
mainPanel.add(label2);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class MyDocListener implements DocumentListener {
private JLabel label;
public MyDocListener(JLabel label) {
this.label = label;
}
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
Document doc = e.getDocument();
int offset = doc.getLength();
try {
String text = doc.getText(0, offset);
label.setText(text);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TestPaints2());
}
}
class TestJComponent2 extends JComponent {
private static final Color BG = Color.GREEN;
private static final int GAP = 5;
public TestJComponent2() {
setOpaque(true);
setBackground(BG);
setLayout(new FlowLayout());
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
}
class TestJPanel2 extends JPanel {
private static final Color BG = Color.BLUE;
private static final int GAP = 5;
public TestJPanel2() {
setBackground(BG);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
}
}
I am currently working on a little game but I just encountered a problem:
I have three classes, the first one is the JFrame:
public class Game
{
public static void main(String[] args)
{
new Game().gui();
}
public void gui()
{
DrawPanel panel = new DrawPanel();
JFrame frame = new JFrame("Test");
//frame.add(panel);
frame.add(new MainMenu());
frame.setSize(800, 700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
Now I have two other classes, one is the mainMenu, currently consisting of just one JButton.
I decided to make the menu its own class because later, I want to call the menu by pressing escape, but the problem is that (for testing reasons) I want to draw an rectangle when "start" is pressed. I tried different approaches but nothing happens.
public class MainMenu extends JPanel implements ActionListener
{
GamePanel panel = new GamePanel();
public MainMenu()
{
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 200;
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
add(b1, c);
}
}
public class DrawPanel extends JPanel
{
public void paint(Graphics g)
{
g.drawRect (10, 10, 200, 200);
}
}
There are several errors I found in your code:
You're not adding your DrawPanel to anything because this line
frame.add(panel);
is commented, so, that leads us to the next problem:
You're overriding paint() method instead of paintComponent() and also don't forget to call
super.paintComponent();
at the very beginning of the method. Without it, you're preventing your code to keep painting the rest of the components. See Custom painting in Swing
That still doesn't makes anything appear because you haven't declared a location for your DrawPanel and thus it's taking JFrame's default Layout Manager which is BorderLayout and it's default location when not specified is CENTER, and as you're adding new MainMenu() to it on the same position it replaces the DrawPanel panel, since only one component can exist on the same position.
Instead try and place the DrawPanel to the CENTER and the MainMenu to the SOUTH. It now should look like this:
Don't forget to place your program on the Event Dispatch Thread (EDT) by writing your main method as follows:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Your constructor here
}
});
}
You're implementing ActionListener on MainMenu but not implementing it's methods, remove it or implement the actionPerformed method and move the code inside the b1 action listener to it. However I highly recommend you to take at Should your class implement ActionListener or use an object of an anonymous ActionListener class too
You're playing with MainMenu's JPanel visibility, instead you should try using a CardLayout or consider using JDialogs.
For example I would make a JDialog and place the JButton there, so it will open the JFrame with the Rectangle drawn in it.
Now, the code that made the above output and follows all recommendations (but #6) is:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Game {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Game().gui();
}
});
}
public void gui() {
DrawPanel panel = new DrawPanel();
JFrame frame = new JFrame("Test");
frame.add(panel, BorderLayout.CENTER);
frame.add(new MainMenu(), BorderLayout.SOUTH);
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
class MainMenu extends JPanel {
// GamePanel panel = new GamePanel();
public MainMenu() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 200;
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
add(b1, c);
}
}
class DrawPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(10, 10, 200, 200);
}
}
As suggested in the comments by #MadProgrammer, you can also override the getPreferredSize() method of your DrawPanel and then call frame.pack():
Your DrawPanel class should now look like this:
class DrawPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(10, 10, 200, 200);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
}
I need to create a JFrame which has three JPanels laid out as shown:
Could anybody please tell me how I can achieve this layout? I have already tried using BorderLayout, but in BorderLayout, if I add the topmost pane at BorderLayout.NORTH, the one in the center at BorderLayout.CENTER, and the one at the bottom to BorderLayout.SOUTH, the topmost pane becomes too small (in height) and the pane in the center becomes too big (in height).
P.S. I have already made the 3 panes and set their preferred sizes properly.
You could use all sorts of things, compound layouts (using two BorderLayouts for example) or other layouts, it will depend on what you ultimately want to achieve.
For simplicity, I'd use a GridBagLayout, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new ABigPanel(), gbc);
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new ASmallPanel(), gbc);
add(new ASmallerPanel(), gbc);
}
}
public class ABigPanel extends JPanel {
public ABigPanel() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
public class ASmallPanel extends JPanel {
public ASmallPanel() {
setBackground(Color.GREEN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 180);
}
}
public class ASmallerPanel extends JPanel {
public ASmallerPanel() {
setBackground(Color.CYAN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 40);
}
}
}
See How to Use GridBagLayout for more details
I'm making a GUI for a a custom source server browser with improved filtering.
This is what I have so far.
However, when I resize...
When I resize the window I want the L4D2 'filter panel' to resize to the current maximum width of the container. I also want to be able to add more of these panels in a column (such as box layout provides).
Boxlayout get's the panels to appear in a column, but it doesn't do anything for their widths.
I'm thinking I may need to override the filter panels preferred size methods so that they can retrieve the size of the parent container, but I'm not sure how to do this.
How should I approach this problem?
EDIT: Here's an example program depicting the problem.
import javax.swing.*;
import java.awt.*;
public class guiExampleProblem {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final MyWindows wnd = new MyWindows("guiExampleProblem");
wnd.setVisible(true);
}
});
}
}
class MyWindows extends JFrame {
public MyWindows(String text) {
super(text);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel containerPanel1 = new JPanel();
JPanel containerPanel2 = new JPanel();
JPanel containerPanel3 = new JPanel();
containerPanel1.setBackground(Color.BLACK);
containerPanel2.setBackground(Color.RED);
containerPanel3.setBackground(Color.GREEN);
mainPanel.add(containerPanel1);
mainPanel.add(containerPanel2);
mainPanel.add(containerPanel3);
this.add(mainPanel);
pack();
}
}
When the window is resized, I want the panels to expand only along the x-axis, and remain at a constant height on the y-axis, however in the example the panels expand on both the x y axis.
I managed to get the desired functionality by overriding the 'filter panels' getPrefferedSize methods so that they retrieve the parent containers width and use that. Here is the code in the form of an example:
import javax.swing.*;
import java.awt.*;
public class guiExampleProblem {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final MyWindows wnd = new MyWindows("guiExampleProblem");
wnd.setVisible(true);
}
});
}
}
class MyWindows extends JFrame {
public MyWindows(String text) {
super(text);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
JPanel containerPanel1 = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(this.getParent().getWidth(),60);
}
};
JPanel containerPanel2 = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(this.getParent().getWidth(),60);
}
};
JPanel containerPanel3 = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(this.getParent().getWidth(),60);
}
};
containerPanel1.setBackground(Color.BLACK);
containerPanel2.setBackground(Color.RED);
containerPanel3.setBackground(Color.GREEN);
mainPanel.add(containerPanel1);
mainPanel.add(containerPanel2);
mainPanel.add(containerPanel3);
this.add(mainPanel);
pack();
}
}
Put the panel (with BoxLayout) that is to stretch in the CENTER of a BorderLayout -- put the panel to the right in the EAST of that BorderLayout. You have given no detail of what else you want this to do, nor any code, but this might be what you want.
--
After your solution: it seems to me that using FlowLayout here is confusing -- it lays out its components one after the other horizontally, and your trick of getting preferred size from the width of the container makes it behave differently. I also avoid getting into layout logic in my application when I can, so I looked for another way to do this and came up with:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class guiExampleProblem2
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
final MyWindows2 wnd = new MyWindows2("guiExampleProblem2");
wnd.setVisible(true);
}
});
}
}
class MyWindows2 extends JFrame
{
public MyWindows2(String text)
{
super(text);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel containerPanel1 = addContainedPanel(Color.BLACK, 60, 60, mainPanel);
JPanel containerPanel2 = addContainedPanel(Color.RED, 60, 60, mainPanel);
JPanel containerPanel3 = addContainedPanel(Color.GREEN, 60, 60, mainPanel);
this.add(mainPanel, BorderLayout.NORTH);
pack();
}
JPanel addContainedPanel(Color color, int width, int height, JPanel container)
{
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(width, height));
panel.setBackground(color);
container.add(panel);
return panel;
}
}
This uses the NORTH portion of a BorderLayout (which is the default layout for a JFrame, by the way) to do the main thing you wanted -- stretch things horizontally. The BoxLayout with a page axis is intended to lay things out top-to-bottom, so I think that's less confusing for the reader. Anyway, it's another way to do it that I think uses the components - including the layout managers - more like they were intended and documented.
I want to have my screen split in two so I used a BorderLayout with East and West sections. I had problems resizing and here I eventually found out that width is not changed in the East and West panels and height is not changed in the North and South panels and both are changed in the Center panel.
However, I want both width and height to be changed upon resize, and have two panels side by side. I have tried various levels of nesting to try getting it to work but I do not think it will work with BorderLayout.
It seems like this should be easy for the default layout manager but maybe I should try a different layout (e.g. BoxLayout) to achieve what I want.
Also here is some code which replicates the problem I am talking about (try resizing the window):
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
public static void main(String[] args) {
JFrame window = new Main();
window.setVisible(true);
}
public Main() {
JButton east = new JButton("East");
JButton west = new JButton("West");
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(east, BorderLayout.EAST);
content.add(west, BorderLayout.WEST);
setContentPane(content);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
}
Edit: I do not want the two sides to be equal, roughly 2:1 is the ratio which I want.
What you can use in your case is GridLayout, here two JButtons will resize themselves as the JFrame resizes.
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame window = new Main();
window.setVisible(true);
}
});
}
public Main() {
JButton east = new JButton("East");
JButton west = new JButton("West");
JPanel content = new JPanel();
content.setLayout(new GridLayout(1, 2));
content.add(east);
content.add(west);
setContentPane(content);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
}
Moreover, it's always best to run your GUI related code from the EDT - Event Dispatch Thread, and not from the Main Thread. Do read Concurrency in Swing, for more info on the topic.
LATEST EDIT : As per requested comment
Use GridBagLayout to specify the size that you want to give
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame window = new Main();
window.setVisible(true);
}
});
}
public Main() {
JPanel east = new JPanel();
east.setOpaque(true);
east.setBackground(Color.WHITE);
JPanel west = new JPanel();
west.setOpaque(true);
west.setBackground(Color.BLUE);
JPanel content = new JPanel();
content.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.3;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
content.add(east, gbc);
gbc.weightx = 0.7;
gbc.gridx = 1;
content.add(west, gbc);
setContentPane(content);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
}
Why don't you try with JSplitPane:
import javax.swing.*;
import java.awt.*;
public class AppDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, eastButton, westButton);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(splitPane, BorderLayout.CENTER);
frame.setContentPane(content);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(500, 400));
frame.pack();
frame.setVisible(true);
});
}
}
You will get this:
If you want to keep your BorderLayout you can use something like the following object:
public class ResizablePanel extends JPanel {
public ResizablePanel(JComponent body) {
setLayout(new BorderLayout());
JButton resize = new JButton();
resize.setPreferredSize(new Dimension(Integer.MAX_VALUE, 4));
resize.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
Dimension preferredSize = ResizablePanel.this.getPreferredSize();
ResizablePanel.this.setPreferredSize(new Dimension(preferredSize.width, preferredSize.height-e.getY()));
ResizablePanel.this.revalidate();
}
});
add(resize, BorderLayout.PAGE_START);
add(body, BorderLayout.CENTER);
}
}
Now wrap the part you want to resize with an instance of ResizablePanel and you'll be able to resize it by dragging the thin button.
Note that this is code is for resizing the height of a panel that you put at the bottom (PAGE_END) part of a border layout, but it should be fairly straightforward to change it for resizing the width.
Sorry about replying to an old post.
My fix is to still use BorderLayout but to throw in the following line after the Component is resized
getLayout().layoutContainer(this);