jtextarea wont fill panel with GridBagConstraints - java

From my code I expect my JTextArea to fill the top left border seen below:
But as you can see its taking up a tiny section in the middle.
I am using GridBagConstraints on the panel which contains the components.
There is a main class which calles up a class called frame. This class creates the JFrame and sets the size as well as other things. This is then called from the MainFrame.java which has extended the jframe which creates 3 panels and sets their layout. this is seen below
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
private Panel1 storyPanel;
private Panel2 statsPanel;
private Panel3 commandsPanel;
public MainFrame(String title)
{
super(title);
// Setting Layout
GridBagConstraints gbc = new GridBagConstraints();
storyPanel = new Panel1();
storyPanel.setLayout(new GridBagLayout());
statsPanel = new Panel2();
commandsPanel = new Panel3();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(statsPanel, BorderLayout.EAST);
p.add(commandsPanel, BorderLayout.SOUTH);
}
}
The panel in questions is Panel1 or storyPanel. I have set the layout and the code calls the Panel1.java as seen below:
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
add(scroll, gbc);
}
}
I don't understand why my gbc.fill isnt making the JTextArea fill the top left border of the screen shot.
Thanks in advance for any reply's
-Tom T
changing the layout to border layout
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
//GridBagConstraints gbc = new GridBagConstraints();
//gbc.weightx = 0.1;
//gbc.weighty = 0.1;
BorderLayout b = new BorderLayout();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//gbc.gridx = 0;
//gbc.gridy = 0;
//gbc.weightx = 1;
//gbc.weighty = 1;
//gbc.fill = GridBagConstraints.BOTH;
add(scroll, b.CENTER);
}
}

Don't set the layout of storyPanel, as it's contents have already been added and laid out, so changing the layout manager here will discard any properties you applied. Instead, set the layout in Panel1's constructor before you add any components.
Use GridBagConstraints.BOTH for the fill property. The fill property can only have one specified value
Use weightx and weighty to specify how much of the available space the component should use
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new MainFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Panel1 storyPanel;
// private Panel2 statsPanel;
// private Panel3 commandsPanel;
public MainFrame(String title) {
super(title);
storyPanel = new Panel1();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(new JLabel("East"), BorderLayout.EAST);
p.add(new JLabel("South"), BorderLayout.SOUTH);
}
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
add(scroll, gbc);
}
}
}
Having said all that, a BorderLayout would be simpler
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new BorderLayout());
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
}
}
i tried a border layout and set it to center expecting it to resize but that failed as well
Would suggest that you're making a fundamental mistake some where, as it works fine for me. Remember, set the layout BEFORE you add any components to the container

Related

How to left align JPanel in JTabbedPane?

I want to Left align the tab labeled "Unwanted Centered Panel" here is my SSCE:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Issue {
public Issue() {
}
public JPanel buildIssuePanel() {
GridBagLayout layout1 = new GridBagLayout();
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.anchor = GridBagConstraints.LINE_START;
JPanel unWantedCenteredPanel = new JPanel(layout1);
unWantedCenteredPanel.add(new JLabel("SHORT"),gbc1);
return unWantedCenteredPanel;
}
public JPanel buildWiderPanel() {
GridBagLayout layout2 = new GridBagLayout();
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.anchor = GridBagConstraints.LINE_START;
JPanel widerPanel = new JPanel(layout2);
widerPanel.add(new JLabel("LOOOOOOOOOOOONNNNNNNNGGGGGGGGGG"),gbc2);
return widerPanel;
}
public void createAndShow() {
JFrame f = new JFrame();
JTabbedPane tp = new JTabbedPane();
tp.addTab("Unwanted Centered Panel", buildIssuePanel());
tp.addTab("Wider Panel",buildWiderPanel());
f.add(tp);
f.validate();
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
Issue issue = new Issue();
issue.createAndShow();
}
}
Unwanted Centering
Wider Panel
The issue appears to be that JTabbedPane defaults to the larger JPanel child width and centers the smaller one.
I've tried setting:
GridBagConstraints.anchor = GridBagConstraints.LINE_START;
But that seems to get overridden. So, how do I get the JLabel with text "SHORT" to be left aligned?
As #camickr suggested, adding weightx=1 made the achor=LINE_START apply itself.
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class IssueResolved {
public IssueResolved() {
}
public JPanel buildIssueResolvedPanel() {
GridBagLayout layout1 = new GridBagLayout();
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.anchor = GridBagConstraints.LINE_START;
//adding weightx = 1 applies the anchor = LINE_START and gives a left align
gbc1.weightx = 1;
JPanel unWantedCenteredPanelNowLeftAligned = new JPanel(layout1);
unWantedCenteredPanelNowLeftAligned.add(new JLabel("SHORT"),gbc1);
return unWantedCenteredPanelNowLeftAligned;
}
public JPanel buildWiderPanel() {
GridBagLayout layout2 = new GridBagLayout();
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.anchor = GridBagConstraints.LINE_START;
//adding weightx = 1 applies the anchor = LINE_START and gives a left align
gbc2.weightx = 1;
JPanel widerPanel = new JPanel(layout2);
widerPanel.add(new JLabel("LOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNGGGGGGGGGGGGGG"),gbc2);
return widerPanel;
}
public void createAndShow() {
JFrame f = new JFrame();
JTabbedPane tp = new JTabbedPane();
tp.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
tp.addTab("Unwanted Centered Panel Now Left Aligned", buildIssueResolvedPanel());
tp.addTab("Wider Panel",buildWiderPanel());
f.add(tp);
f.validate();
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
IssueResolved issueResolved = new IssueResolved();
issueResolved.createAndShow();
}
}
Left Aligned

Make JLabel text breaks in gridbaglayout

I have following code to add panels dynamically to container with GridBagLayout.
It should grow and display vertical scrollbar, not horizontal.
But when I add too long text in JLabel in parent JPanel, it displays horizontal scrollbar, I want JLabel to break text as container shrinks, and also grows as the container grows.
I've tried setting maximum width but the GridBagLayout not using it.
I've also tried using something like but it makes the label's not growing when I resize the parent.
import java.awt.BorderLayout;
import java.awt.Color;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.border.MatteBorder;
/**
*
* #author MethoD
*/
public class DynamicPanelList extends JPanel {
private JPanel mainList;
public DynamicPanelList() {
setLayout(new BorderLayout());
mainList = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
mainList.add(new JPanel(), gbc);
add(new JScrollPane(mainList));
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel lbl = new JLabel("<html>Hello world items lorem ipsum dolor sit amei blast it");
//lbl.setMaximumSize(new Dimension(100, 100));
panel.add(lbl, BorderLayout.CENTER);
panel.setBorder(new MatteBorder(0, 0, 1, 0, Color.GRAY));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);
validate();
repaint();
}
});
add(add, BorderLayout.SOUTH);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DynamicPanelList tp = new DynamicPanelList();
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

JButton size and JScrollPane not working well together

I am thoroughly confused. I have a pretty decent understanding of how each layout manger works and what each one is used for, but I'm not understanding what combination of layout managers and JPanels are necessary to make what I need work.
What I am trying to accomplish
I have a top bar, and a bottom bar of a container panel NORTH and SOUTH of a BorderLayout.
Within the Center panel, I want an unknown number of buttons 1 or more. Regardless of how many buttons there are they all need to be the same size, if there are dozens then scrolling should start happening once the buttons pass the window size limit.
What I am getting
Depending on the combination of layout mangers and how many nested JPanels I use and all sorts of trouble shooting, I get one massive button filling the entire CENTER element. I get 2 buttons that are the right size, but spread way apart (gap filling the CENTER space), or I get a dozen buttons that are the right size with no scroll.
I can solve any one of these, but then the other breaks. IE if I get a bunch of correctly sized buttons that properly scroll, then when I replace them with a single button its one massive button. Or if I get a single properly sized button then the larger quantity won't scroll etc.
My Code
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.io.*;
public class TestCode extends JFrame {
private final JFrame frame;
public TestCode(){
frame = new JFrame();
JLabel title = new JLabel("Test Title");
JPanel windowContainer = new JPanel();
JPanel topPanel = new JPanel();
final JPanel middlePanel = new JPanel();
JPanel bottomPanel = new JPanel();
JButton searchButton = new JButton("Search");
JButton browseButton = new JButton("Browse...");
JButton testButton = new JButton("Button 1");
JButton exitButton = new JButton("Exit");
final JTextField searchBar = new JTextField("Search database...");
topPanel.setLayout(new GridLayout(2,0));
topPanel.add(title);
title.setHorizontalAlignment(JLabel.CENTER);
topPanel.setPreferredSize(new Dimension(getWidth(), 100));
// This is a subset of the top section. Top part is two panels, bottom panel is two cells (grid)
JPanel topPanelSearch = new JPanel();
topPanelSearch.setLayout(new GridLayout(0,2));
topPanelSearch.add(searchBar);
topPanelSearch.add(searchButton);
topPanel.add(topPanelSearch);
// PROBLEM AREA STARTS
// middlePanel.setLayout(new FlowLayout());
middlePanel.setLayout(new GridLayout(0, 1, 10, 10));
// middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.PAGE_AXIS));
JPanel innerContainer = new JPanel();
innerContainer.setLayout(new BoxLayout(innerContainer, BoxLayout.PAGE_AXIS));
// innerContainer.setLayout(new FlowLayout());
// innerContainer.setLayout(new GridLayout(0, 1, 10, 10));
for(int i = 0; i < 2; i++){
JButton button = new JButton("Button ");
button.setPreferredSize(new Dimension(400, 100));
JPanel test = new JPanel();
test.add(button);
innerContainer.add(test);
}
JScrollPane midScroll = new JScrollPane(innerContainer);
middlePanel.add(midScroll);
// PROBLEM AREA ENDS
bottomPanel.setLayout(new GridLayout(0, 3));
bottomPanel.setPreferredSize(new Dimension(getWidth(), 100));
bottomPanel.add(testButton);
bottomPanel.add(browseButton);
bottomPanel.add(exitButton);
windowContainer.setLayout(new BorderLayout());
windowContainer.add(topPanel, BorderLayout.NORTH);
windowContainer.add(middlePanel, BorderLayout.CENTER);
windowContainer.add(bottomPanel, BorderLayout.SOUTH);
frame.add(windowContainer);
frame.setTitle("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(480, 800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args){
TestCode test = new TestCode();
}
}
Visual of some of the fail results
I want the leftmost picture, but buttons should be stacked neatly (like the middle picture) when there are only a few results, and scrollable when there are lots.
What am I doing wrong?
Try with GridBagLayout and a filler component that takes the remaining vertical space and therefore forces the buttons upwards.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.Box.Filler;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class GridbagButtons extends JFrame {
private final JScrollPane jscrpButtons;
private final JPanel jpButtons;
public GridbagButtons() {
setLayout(new BorderLayout());
jpButtons = new JPanel(new GridBagLayout());
jscrpButtons = new JScrollPane(jpButtons);
add(jscrpButtons, BorderLayout.CENTER);
// add a custom number of buttons
int numButtons = 10;
for (int i = 0; i < numButtons; i++) {
JButton jbButton = new JButton("Button");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = i;
jpButtons.add(jbButton, gbc);
}
// add a vertical filler as last component to "push" the buttons up
GridBagConstraints gbc = new GridBagConstraints();
Filler verticalFiller = new Filler(
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, Integer.MAX_VALUE));
gbc.gridx = 0;
gbc.gridy = numButtons;
gbc.fill = java.awt.GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
jpButtons.add(verticalFiller, gbc);
setSize(300, 200);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridbagButtons().setVisible(true);
}
});
}
}

Why so much room to the left of my labels in java?

Here is what I have:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.LineBorder;
public class Main {
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
static JScrollPane scrollPane;
public static void main(String[] args) {
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
//frame.setPreferredSize(new Dimension(990, 990));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
//GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
//frameConstraints.gridx = 0;
//frameConstraints.gridy = 0;
//frame.add(addButton, frameConstraints);
frame.add(addButton);
// Construct panel
panel.setPreferredSize(new Dimension(1000, 1000));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(600, 600));
// Add panel to frame
//frameConstraints.gridx = 0;
//frameConstraints.gridy = 1;
//frameConstraints.weighty = 1;
//frame.add(panel, frameConstraints);
frame.add(scrollPane);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// Clear panel
panel.removeAll();
// Create label and text field
//JTextField jTextField = new JTextField();
//jTextField.setSize(100, 200);
//listOfTextFields.add(jTextField);
listOfLabels.add(new JLabel("" + indexer));
// Create constraints
//GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer; i++) {
// Text field constraints
//textFieldConstraints.gridx = 1;
//textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
//textFieldConstraints.weightx = 0.5;
//textFieldConstraints.insets = new Insets(10, 10, 10, 10);
//textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(0, 0, 0, 0);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
//panel.add(listOfTextFields.get(i), textFieldConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
c.ipady = 0;
panel.add(new JLabel(), c);
System.out.println("indexer is " + indexer);
// Increment indexer
indexer++;
panel.updateUI();
if(indexer ==2){
listOfLabels.set(0, new JLabel("Test"));
}
}
private int getWidth() {
// TODO Auto-generated method stub
return 0;
}
}
}
Here is the output:
What Am I doing wrong? I want the labels to be justified all the way to the left. I don't have any padding set to the left so I am confused.
FYI, I found this code on stackoverflow and my goal is to have labels that I can dynamically add and update, hence I commented out the textboxes.
Don't call setPreferredSize on the scroll pane, this isn't what you should setting, use GridBagConstraints weightx/y and fill properties.
Don't call updateUI, it doesn't do what you think it does, call revalidate instead, if you have to
The main reasons you're having problems is
You're call setPreferredSize on the panel. When adding components to a GridBagLayout, it will attempt to lay out components around the centre of the container
You've not specified a weightx or anchor property for the GridBagConstraints when adding the labels

How to resize a JPanel to fit a JFrame in "docknorth" with no interference to remaining JPanels

I am doing a little test of a demo Swing GUI. In this demo, the JFrame is composed of 3 "master" JPanels. If you will, the first (jp1) is composed of JLabels, and the other two are composed of several other JPanels. I am using MigLayout.
Here is my sample code:
// All the jPanels
JFrame frame = new JFrame();
frame.setLayout(new MigLayout());
JPanel jp1 = new JPanel();
jp1.setLayout(new MigLayout());
jp1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp2 = new JPanel();
jp2.setLayout(new MigLayout());
jp2.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp3 = new JPanel();
jp3.setLayout(new MigLayout());
jp3.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp4 = new JPanel();
jp4.setLayout(new MigLayout());
jp4.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp5 = new JPanel();
jp5.setLayout(new MigLayout());
jp5.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp6 = new JPanel();
jp6.setLayout(new MigLayout());
jp6.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp7 = new JPanel();
jp7.setLayout(new MigLayout());
jp7.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel bigPanel1 = new JPanel();
bigPanel1.setLayout(new MigLayout());
bigPanel1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel bigPanel2 = new JPanel();
bigPanel2.setLayout(new MigLayout());
bigPanel2.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
//All the labels to be added to JPanel jp1
JLabel label1 = new JLabel();
label1.setText("LABEL1");
JLabel label2 = new JLabel();
label2.setText("LABEL2");
JLabel label3 = new JLabel();
label3.setText("LABEL3");
JLabel label4 = new JLabel();
label4.setText("LABEL4");
jp1.add(label1);
jp1.add(label2);
jp1.add(label3);
jp1.add(label4,"wrap");
bigPanel1.add(jp2);
bigPanel1.add(jp6);
bigPanel1.add(jp3,"grow,wrap");
bigPanel2.add(jp4);
bigPanel2.add(jp7);
bigPanel2.add(jp5,"grow,wrap");
frame.getContentPane().add(jp1,"dock north, wrap");
frame.getContentPane().add(bigPanel1,"span,grow,wrap");
frame.getContentPane().add(bigPanel2,"span,grow,wrap");
frame.pack();
frame.setVisible(true);
Which results in this output:GUI OUTPUT
What I want to achieve is being able to add labels into the 1st JPanel (jp1) without messing with the remainder JPanels width.
Additionally, I want to make the several JPanels inside a bigPanel to occupy its full width, as well as in jp2,jp6 and jp3 to fill bigPanel1.
How should I do this? Thanks in advance.
I have never used MigLayout, and personally dont see the reason if it can be done using default java LayoutManager.
Okay so I used a combination FlowLayout and GridBagLayout to achieve this, along with gc.fill=GridBagConstraints.NONE and gc.anchor=GridBagConstraints.WEST for those panels which we dont want to fill the contentpane width, also updated as per your comment to stop the JPanel/JFrame from growing larger than the given max width when more JLabels are added this was done using a JScrollPane:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class Test {
public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new GridBagLayout());
final JPanel labelPanel = new JPanel();
labelPanel.setBorder(new LineBorder(Color.black));
for (int i = 0; i < 5; i++) {
labelPanel.add(new JLabel("Label" + (i + 1)));
}
final int maxWidth = 200;
final JScrollPane jsp = new JScrollPane(labelPanel) {
#Override
public Dimension getPreferredSize() {
//we set the height by checking if we exceeed the wanted ith thus a scrollbar will appear an we must incoprate that or labels wont be shpwn nicely
return new Dimension(maxWidth, labelPanel.getPreferredSize().width < maxWidth ? (labelPanel.getPreferredSize().height + 5) : ((labelPanel.getPreferredSize().height + getHorizontalScrollBar().getPreferredSize().height) + 5));
}
};
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("label"));
otherPanel.setBorder(new LineBorder(Color.black));
JPanel otherPanel2 = new JPanel();
otherPanel2.add(new JLabel("label 1"));
otherPanel2.add(new JLabel("label 2"));
otherPanel2.setBorder(new LineBorder(Color.black));
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 1.0;
gc.weighty = 1.0;
gc.gridx = 0;
gc.gridy = 0;
frame.add(jsp, gc);
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.WEST;
gc.gridy = 1;
frame.add(otherPanel, gc);
gc.anchor = GridBagConstraints.WEST;
gc.gridy = 2;
frame.add(otherPanel2, gc);
frame.pack();
frame.setVisible(true);
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) {
//Create Swing components on EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
I have use BorderLayout and FlowLayout to manage the layouts. The frame has two JPanel's and one JPanel in it has two more JPanel's. All the internal panels use FlowLayout to align the JLabels. To arrange these panels on the JFrame I have used BorderLayout.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class LayoutTest {
public LayoutTest() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new GridBagLayout());
JPanel motherPanel = new JPanel(new BorderLayout());
JPanel topPanel = new JPanel(new BorderLayout());
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
motherPanel.add(topPanel, BorderLayout.NORTH);
motherPanel.add(bottomPanel, BorderLayout.CENTER);
JPanel topUpperPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel topBottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
topUpperPanel.setBorder(new LineBorder(Color.BLACK));
topBottomPanel.setBorder(new LineBorder(Color.BLACK));
bottomPanel.setBorder(new LineBorder(Color.BLACK));
topPanel.add(topUpperPanel, BorderLayout.PAGE_START);
topPanel.add(topBottomPanel, BorderLayout.CENTER);
for(int i = 0; i < 3; i++) {
JLabel label = new JLabel("Label-" + String.valueOf(i));
label.setBorder(new LineBorder(Color.BLACK));
topUpperPanel.add(label);
}
for(int i = 0; i < 2; i++) {
JLabel label = new JLabel("Label-" + String.valueOf(i));
label.setBorder(new LineBorder(Color.BLACK));
topBottomPanel.add(label);
}
for(int i = 0; i < 5; i++) {
JLabel label = new JLabel("Label-" + String.valueOf(i));
label.setBorder(new LineBorder(Color.BLACK));
bottomPanel.add(label);
}
frame.add(motherPanel);
frame.setTitle("Layout Manager");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LayoutTest();
}
});
}
}
P.S: I would suggest you to separate the panels such that there will be "whithout no interference with remaining JPanels."

Categories