I create a parent container onto which I place several JPanel objects, each containing several JButton objects.
I create the parent panel, add the GridBagConstraints then add each child panel to the parent:
final JPanel options = new JPanel(new GridBagLayout());
options.setBorder(new TitledBorder("Select Option"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
options.add(findPanel, gbc);
options.add(addPanel, gbc);
options.add(changePanel, gbc);
options.add(dropPanel, gbc);
gbc.weighty = 1.0;
options.add(new JPanel(), gbc);
With options.add(new JPanel(), gbc); used to take up the extra space under my wanted panels. Works great....until I want to change the contents of the parent after user interaction:
partnoFai.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
options.remove(findPanel);
options.remove(addPanel);
options.remove(changePanel);
options.remove(dropPanel);
options.add(partnoFaiInp, gbc);
gbc.weighty = 1.0;
options.add(new JPanel(), gbc);
frame.pack();
frame.validate();
}
} );
It's adding the new panel, options.add(partnoFaiInp, gbc); to the middle of the parent when I want it at the top. Why wouldn't gbc.anchor = GridBagConstraint.NORTH; keep the new panel in the NORTH of the panel?
Any help is appreciated.
You have to think of the Container in terms of a stack
When you first setup the panel using...
options.add(findPanel, gbc);
options.add(addPanel, gbc);
options.add(changePanel, gbc);
options.add(dropPanel, gbc);
gbc.weighty = 1.0;
options.add(new JPanel(), gbc);
The container has a list of components looking like {findPanel, addPanel, changePanel, dropPanel, JPanel}
When you remove the components using something like...
options.remove(findPanel);
options.remove(addPanel);
options.remove(changePanel);
options.remove(dropPanel);
The container now has a list of components looking like {JPanel}
Then when you add your new component using...
options.add(partnoFaiInp, gbc);
gbc.weighty = 1.0;
options.add(new JPanel(), gbc);
The container now has a list of components looking like {JPanel, partnoFaiInp, JPanel}
So, instead of adding the another "filler" component, you could just specify the insert point of the panel when you add it...
options.add(partnoFaiInp, gbc, 0);
frame.pack();
frame.validate();
The container now has a list of components looking like {partnoFaiInp, JPanel}
Related
I'd like to decorate a JPanel with a JLayer, but am failing to understand why doing so messes up this panel being laid out inside a JScrollPane. The decorated component is supposed to act as a drop in replacement, but it does not appear to work in this case.
The following code creates two equivalent JPanels and puts them into another panel with CardLayout (so you may switch between them using the buttons). The only difference is that in one case the panel is decorated with a JLayer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class JLayerScroll extends JFrame {
public JLayerScroll() {
setTitle("Jumpy border");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
createGui();
setSize(400, 200);
setLocationRelativeTo(null);
}
private void createGui() {
JPanel mainPanel = new JPanel(new CardLayout());
// two panels ("label panels"), first one decorated, second one not
mainPanel.add(createSingleScrolledComponent(new JLayer<JPanel>(createLabelPanel(), new LayerUI<JPanel>())), WITH_JLAYER);
mainPanel.add(createSingleScrolledComponent(createLabelPanel()), WITHOUT_JLAYER);
add(mainPanel);
createButtons(mainPanel);
}
private JPanel createSingleScrolledComponent(Component component) {
GridBagConstraints gbc;
JScrollPane scroll;
JPanel panel = new JPanel(new GridBagLayout());
scroll = new JScrollPane(component);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0d;
gbc.weighty = 1.0d;
panel.add(scroll, gbc);
return panel;
}
private JPanel createLabelPanel() {
GridBagConstraints gbc;
JPanel panel = new JPanel(new GridBagLayout());
JPanel entry = new JPanel(new GridBagLayout());
entry.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
JLabel label = new JLabel("Some input:");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
entry.add(label, gbc);
JTextField field = new JTextField(20);
field.setMinimumSize(new Dimension(field.getPreferredSize().width, field.getMinimumSize().height));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
entry.add(field, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
entry.add(Box.createHorizontalGlue(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
panel.add(entry, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0d;
panel.add(Box.createVerticalGlue(), gbc);
return panel;
}
private static final String WITH_JLAYER = "with-jlayer";
private static final String WITHOUT_JLAYER = "no-jlayer";
private void createButtons(final JPanel mainPanel) {
GridBagConstraints gbc;
JButton button;
JPanel actionsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
actionsPanel.add(Box.createHorizontalGlue(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
button = new JButton("With JLayer");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, WITH_JLAYER);
}
});
actionsPanel.add(button, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
button = new JButton("Without JLayer");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, WITHOUT_JLAYER);
}
});
actionsPanel.add(button, gbc);
add(actionsPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JLayerScroll().setVisible(true);
}
});
}
}
If you pay attention to the red border in the two cases, you will notice that in one case it spans the whole available horizontal space (as expected), while in the other case, it only spans around visible components (label and text field).
Why is this happening and how do I achieve the same behavior as in the undecorated case (spanning through all available horizontal space)?
The only difference is that in one case the panel is decorated with a JLayer.
A difference between a JPanel and a JLayer is that the JLayer implements the Scrollable interface but a JPanel does not.
The getScrollableTracksViewportWidth() method controls whether the component added to the viewport should be displayed at its preferred size or the width of the viewport. The JLayer delegates to the JPanel, but since JPanel doesn't implement the Scrollable interface the JLayer implementation will return "false" which means the component should be displayed at its preferred width.
So a way to get around this is to use a wrapper panel for the JLayer:
//scroll = new JScrollPane(component);
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add( component );
scroll = new JScrollPane(wrapper);
Now the component added to the viewport of the scrollpane is a JPanel in both cases, so they should behave the same way.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So basically I want to create this sort of a GUI, but because of my inexperience with Java GUIs, I cannot figure out which Layout Manager to use. I've tried Flow, Border, Grid, but none of them allow me to create this sort of a GUI without messing up the alignments somewhere.
Any suggestions? How should I decide on a layout manager in the future, or is it something which will come with experience?
I'd prefer to use a simple to use layout, as this is a very basic GUI and I don't think something like MiGLayout should be necessary.
I'd use a combination of compound panels and layouts. Apart from making easier to get the layout to work, you could also isolate areas of responsibility within their own class.
public class TestLayout13 {
public static void main(String[] args) {
new TestLayout13();
}
public TestLayout13() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new FormPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FormPane extends JPanel {
public FormPane() {
setBorder(new EmptyBorder(8, 8, 8, 8));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
NamePane namePane = new NamePane();
namePane.setBorder(new CompoundBorder(new TitledBorder("Name"), new EmptyBorder(4, 4, 4, 4)));
add(namePane, gbc);
gbc.gridy++;
EMailPane emailPane = new EMailPane();
emailPane.setBorder(new CompoundBorder(new TitledBorder("E-Mail"), new EmptyBorder(4, 4, 4, 4)));
add(emailPane, gbc);
}
}
public class NamePane extends JPanel {
public NamePane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("First Name:"), gbc);
gbc.gridx += 2;
add(new JLabel("Last Name:"), gbc);
gbc.gridy++;
gbc.gridx = 0;
add(new JLabel("Title:"), gbc);
gbc.gridx += 2;
add(new JLabel("Nickname:"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 0.5;
add(new JTextField(10), gbc);
gbc.gridx += 2;
add(new JTextField(10), gbc);
gbc.gridy++;
gbc.gridx = 1;
add(new JTextField(10), gbc);
gbc.gridx += 2;
add(new JTextField(10), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 0;
gbc.fill = GridBagConstraints.NONE;
add(new JLabel("Format:"), gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx++;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JComboBox(), gbc);
}
}
protected class EMailPane extends JPanel {
public EMailPane() {
JPanel detailsPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
detailsPane.add(new JLabel("E-Mail Address:"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
detailsPane.add(new JTextField(10), gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.gridwidth = GridBagConstraints.REMAINDER;
detailsPane.add(new JScrollPane(new JList()), gbc);
JPanel buttonsPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
buttonsPane.add(new JButton("Add"), gbc);
gbc.gridy++;
buttonsPane.add(new JButton("Edit"), gbc);
gbc.gridy++;
buttonsPane.add(new JButton("Delete"), gbc);
gbc.gridy++;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH;
buttonsPane.add(new JButton("As Default"), gbc);
JPanel formatPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
formatPane.setBorder(new TitledBorder(new EmptyBorder(1, 1, 1, 1), "Mail Format:"));
formatPane.add(new JRadioButton("HTML"));
formatPane.add(new JRadioButton("Plain"));
formatPane.add(new JRadioButton("Custom"));
setLayout(new BorderLayout());
add(detailsPane);
add(buttonsPane, BorderLayout.LINE_END);
add(formatPane, BorderLayout.PAGE_END);
}
}
}
My preference is MigLayout because it is the most complete and well documented layout manager for Swing. In addition to Swing, it also supports SWT and JavaFX, so the time you spend learning it may pay back more than once. It supports maven, refer to http://www.miglayout.com for details, which is a big plus. Also it has a very useful debug feature. You can add "debug 1" in the constructor, and you will se how the layout was created. Example:
emailButtonPanel.setLayout(new MigLayout("wrap, fill, insets 20 10 0 10, debug 1"));
Another feature that I find very useful from time to time, is the hidemode, which allows you that a component does not take part in the layout if not visible (or several other strategies).
Here is one possible approach for the image you posted, using MigLayout:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import net.miginfocom.layout.CC;
import net.miginfocom.swing.MigLayout;
/**
*/
public class LayoutApproach {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Contact information");
frame.getContentPane().add(new ContactPanel());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(800, 450));
frame.setLocationRelativeTo(null); // Center
frame.pack();
frame.setVisible(true);
}
});
}
static class ContactPanel extends JPanel {
private JPanel namePanel;
private TitledBorder nameTitledBorder;
private JLabel firstNameLabel;
private JTextField firstNameTextField;
private JLabel lastNameLabel;
private JTextField lastNameTextField;
private JLabel titleLabel;
private JTextField titleTextField;
private JLabel nicknameLabel;
private JTextField nickNameTextField;
private JLabel formatLabel;
private JComboBox<String> formatComboBox;
private JPanel emailPanel;
private TitledBorder emailTitledBorder;
private JLabel emailLabel;
private JTextField emailTextField;
private JList<String> emailItemsList;
private JLabel mailFormatLabel;
private JPanel emailButtonPanel;
private JButton addButton;
private JButton editButton;
private JButton removeButton;
private JButton asDefaultButton;
private JRadioButton htmlRadioButton;
private JRadioButton plainTextRadioButton;
private JRadioButton customTextRadioButton;
private JPanel buttonPanel;
private JButton okButton;
private JButton cancelButton;
public ContactPanel() {
createComponents();
makeLayout();
createHandlers();
registerHandlers();
initComponent();
i18n();
}
/**
* Create GUI components, but contains no layout.
*/
public void createComponents() {
namePanel = new JPanel();
nameTitledBorder = new TitledBorder("");
firstNameLabel = new JLabel();
firstNameTextField = new JTextField();
lastNameLabel = new JLabel();
lastNameTextField = new JTextField();
titleLabel = new JLabel();
titleTextField = new JTextField();
nicknameLabel = new JLabel();
nickNameTextField = new JTextField();
formatLabel = new JLabel();
formatComboBox = new JComboBox<>();
emailPanel = new JPanel();
emailTitledBorder = new TitledBorder("");
emailLabel = new JLabel();
emailTextField = new JTextField();
emailItemsList = new JList<>();
mailFormatLabel = new JLabel();
emailButtonPanel = new JPanel();
addButton = new JButton();
editButton = new JButton();
removeButton = new JButton();
asDefaultButton = new JButton();
htmlRadioButton = new JRadioButton();
plainTextRadioButton = new JRadioButton();
customTextRadioButton = new JRadioButton();
buttonPanel = new JPanel();
okButton = new JButton();
cancelButton = new JButton("Cancel");
}
/**
* Create listeners/handlers
*/
public void createHandlers() {
}
/**
* Registers/adds listeners/handlers.
*/
public void registerHandlers() {
}
public void makeLayout() {
layoutNamePanel();
layoutEmailPanel();
layoutButtonPanel();
MigLayout migLayout = new MigLayout("fill, insets 20");
setLayout(migLayout);
add(namePanel, "dock north");
add(emailPanel, "dock north");
add(buttonPanel, "dock south");
}
private void layoutButtonPanel() {
buttonPanel.setLayout(new MigLayout("alignX right"));
buttonPanel.add(okButton, "tag ok");
buttonPanel.add(cancelButton, "tag cancel");
}
private void layoutNamePanel() {
MigLayout nameLayout = new MigLayout("fill, wrap 4", // Layout Constraints
"15[]15[grow]15[]15[grow]", // Column constraints
""); // Row constraints
// -- Layout all components with name
namePanel.setLayout(nameLayout);
// Create this border here since I use it for layout
Border nameBorder = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(10, 6, 10, 6), nameTitledBorder);
namePanel.setBorder(nameBorder);
namePanel.add(firstNameLabel, "alignX right");
namePanel.add(firstNameTextField, "grow");
namePanel.add(lastNameLabel, "alignX right");
namePanel.add(lastNameTextField, "grow");
namePanel.add(titleLabel, "alignX right");
namePanel.add(titleTextField, "grow");
namePanel.add(nicknameLabel, "alignX right");
namePanel.add(nickNameTextField, "grow");
namePanel.add(formatLabel, "alignX right");
namePanel.add(formatComboBox, new CC().grow().span(3)); // Alternative to using plain text'
}
private void layoutEmailPanel() {
MigLayout emailLayout = new MigLayout("fill",// Layout Constraints
"", // Column constraints
""); // Row constraints
// -- Layout all components with name
emailPanel.setLayout(emailLayout);
// Create this border here since I use it for layout
Border emailBorder = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(10, 6, 10, 6), emailTitledBorder);
emailPanel.setBorder(emailBorder);
emailButtonPanel.setLayout(new MigLayout("wrap, fill, insets 20 10 0 10"));
emailButtonPanel.add(addButton, "growx");
emailButtonPanel.add(editButton, "growx");
emailButtonPanel.add(removeButton, "growx");
emailButtonPanel.add(asDefaultButton, "growx");
JPanel emailAndItems = new JPanel(new MigLayout("fill"));
emailAndItems.add(emailLabel, "split 2");
emailAndItems.add(emailTextField, "span, growx, wrap");
emailAndItems.add(emailItemsList, "span, grow");
JPanel radioButtons = new JPanel(new MigLayout());
radioButtons.add(htmlRadioButton);
radioButtons.add(plainTextRadioButton);
radioButtons.add(customTextRadioButton);
emailPanel.add(radioButtons, "dock south");
emailPanel.add(mailFormatLabel, "dock south, gapleft 15");
emailPanel.add(emailAndItems, "dock west, growx, push");
emailPanel.add(emailButtonPanel, "dock east, shrink");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(htmlRadioButton);
buttonGroup.add(plainTextRadioButton);
buttonGroup.add(customTextRadioButton);
}
/**
* Sets initial values for component.
*/
public void initComponent() {
formatComboBox.addItem("Item 1");
formatComboBox.addItem("Item 2");
formatComboBox.addItem("Item 3");
formatComboBox.addItem("Item 4");
DefaultListModel<String> model = new DefaultListModel<>();
emailItemsList.setModel(model);
model.insertElementAt("Item 1", 0);
model.insertElementAt("Item 2", 1);
model.insertElementAt("Item 3", 2);
model.insertElementAt("Item 4", 3);
customTextRadioButton.setSelected(true);
}
public void i18n() {
nameTitledBorder.setTitle("Name:");
firstNameLabel.setText("First Name:");
lastNameLabel.setText("Last Name:");
titleLabel.setText("Title:");
nicknameLabel.setText("Nickname:");
formatLabel.setText("Format:");
emailTitledBorder.setTitle("E-mail");
emailLabel.setText("E-mail address:");
mailFormatLabel.setText("Mail Format:");
addButton.setText("Add");
editButton.setText("Edit");
removeButton.setText("Remove");
asDefaultButton.setText("As Default");
htmlRadioButton.setText("HTML");
plainTextRadioButton.setText("Plain Text");
customTextRadioButton.setText("Custom");
okButton.setText("OK");
cancelButton.setText("Cancel");
}
}
}
The code was written in Java 7. A maven pom.xml file to go with it could be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackoverflow</groupId>
<artifactId>stackoverflow</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.miglayout</groupId>
<artifactId>miglayout-core</artifactId>
<version>4.2</version>
</dependency>
<dependency>
<groupId>com.miglayout</groupId>
<artifactId>miglayout-swing</artifactId>
<version>4.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
I'd say border layout will work alright for you if you are looking for Java library layout managers. A more advanced one would be MiG Layout. You can google it for the info.
You do know that you can nest layout managers right? As in, one JPanel has one layoutmanager and another has a different one. So one could have border layout and another flow layout.
You can try NetBeans if you want a simple Swing designer, but IMHO Miglayout is the shortest way to get your UI's done as you intended. After the initial learning curve of course...
Try to visualize your screen in grids, and then you can use both gridbag and miglayout.
I am adding list of JTree items inside JPanel. I want the parent JPanel to have BoxLayout so that the tree can be added vertically one after another.
The parent JPanel is initialized using :
holder.setLayout(new BoxLayout(holder, BoxLayout.Y_AXIS));
holder.setMaximumSize(new java.awt.Dimension(32767, 24000));
holder.setMinimumSize(new java.awt.Dimension(600, 100));
holder.setPreferredSize(new java.awt.Dimension(600, 100));
The multiple JTree components are added inside :
holder.add(tree);
So i expect the JTree nodes to be occupying the entire width of my parent JPanel but somehow it is coming like this
So as you can see it coming in some portion of the parent JPanel. I want it to fill the entire parent Panel(width wise) and be aligned towards left.
EDIT
After trying the top-aligned approach mentioned by VGR I got this :
So the tree are not occupying the entire space still. And when i expand any tree then everything disappears.
I should have also mentioned this earlier that when the initilization of the parent panel(holder) is done in some other code like this
holder.setMaximumSize(new java.awt.Dimension(32767, 24000));
holder.setMinimumSize(new java.awt.Dimension(600, 100));
holder.setPreferredSize(new java.awt.Dimension(600, 100));
holder.setLayout(new java.awt.GridLayout(1, 0));
add(holder); // add to the top parent
This part is not reachable :( for me. I can only re-change the parent holder as per my requirement.
SSCCE after suggested changes from VGR. This is not compilable but i hope SSC.
public BasePanel() extends JPanel{
private javax.swing.JPanel holder;
private GridBagConstraints gbc;
private JPanel treesPanel;
BasePanel(){
init();
}
public init(){ can't access this method
holder.setMaximumSize(new java.awt.Dimension(32767, 25000));
holder.setMinimumSize(new java.awt.Dimension(600, 0));
holder.setPreferredSize(new java.awt.Dimension(600, 0));
holder.setLayout(new java.awt.GridLayout(1, 0));
add(holder);
}
public initTreeComponents(){ // i need to call this for each tree
this.holder.setLayout(new BorderLayout());
treesPanel = new JPanel(new GridBagLayout());
this.holder.add(treesPanel, BorderLayout.PAGE_START);
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
}
public addTree(JTree tree){// to be called for each tree
treesPanel.add(tree,gbc);
}
I don't think BoxLayout makes child components fill the container. From the documentation:
… for a vertical layout, BoxLayout attempts to make all components in the column as wide as the widest component.
So your JTrees will all be the same width, but that doesn't guarantee they'll be as wide as the container.
Instead, I would use a GridBagLayout:
holder.setLayout(new GridBagLayout());
// etc.
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
holder.add(tree, gbc);
That will result in the JTrees being vertically centered. If you want them top-aligned, you should put a GridBagLayout panel inside another panel:
holder.setLayout(new BorderLayout());
JPanel treesPanel = new JPanel(new GridBagLayout());
holder.add(treesPanel, BorderLayout.PAGE_START);
// etc.
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
treesPanel.add(tree, gbc);
Try adding JTrees inside a JScrollPane, ie
holder.add(new JScrollPane(tree));
I have a Swing Form that contains a JScrollPane(activityScrollPane) for a JPanel(activityPanel). The panel contains a JTextField and a JButton (that is used to add more fields to the Panel). Now the problem is that the elements start from the center of the panel as in the image below (with the borders marking the activityScrollPane boundary)
Following is the code I am currently using to make the scroll pane and associated components.
//part of the code for creating the ScrollPane
final JPanel activityPanel = new JPanel(new GridBagLayout());
gbc.gridx=0;
gbc.gridy=0;
JScrollPane activityScrollPane = new JScrollPane(activityPanel);
//adding activity fields
activityFields = new ArrayList<JTextField>();
fieldIndex = 0;
activityFields.add(new JTextField(30));
final GridBagConstraints activityGBC = new GridBagConstraints();
activityGBC.gridx=0;
activityGBC.gridy=0;
activityGBC.anchor = GridBagConstraints.FIRST_LINE_START;
activityPanel.add(activityFields.get(fieldIndex),activityGBC);
fieldIndex++;
JButton btn_more = (new JButton("more"));
activityGBC.gridx=1;
activityPanel.add(btn_more,activityGBC);
How can I make the JTextField and the JButton or for that matter any component to appear on the top left corner of the JScrollPane. I have already tried using
activityConstraints.anchor = GridBagConstraints.NORTHWEST;
as pointed in the SO post, but it does not at all seem to work.
You simply forgot to provide any weightx/weighty values, atleast one having a non-zero value will do. have a look at this code example :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Latest EDIT : No spacing along Y-Axis
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private JTextField tfield2;
private JButton button2;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
//gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
tfield2 = new JTextField(10);
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield2, gbc);
button2 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button2, gbc);
JScrollPane scroller = new JScrollPane(contentPane);
frame.add(scroller);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Sorry as my answer me be on the off-side of what you have asked, but why dont you use GroupLayout instead of GridBag Layout, thats much more easier to handle
try it with BorderLayout: controls.setLayout(new BorderLayout()); and then apply it for your JPanel controls.add(yourPanel, BorderLayout.PAGE_START);
I also have problems with GridBagLayout so i solved it with BorderLayout and it works so fine.
So i wrote for your little example:
private void initComponents() {
controls = new Container();
controls = getContentPane();
controls.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
field = new JTextField(20);
c.gridx = 0;
c.gridy = 0;
panel.add(field, c);
one = new JButton("Go!");
c.gridx = 1;
c.gridy = 0;
panel.add(one, c);
controls.add(panel, BorderLayout.PAGE_START);
}
Hope it helps!
I think this could be simple and possible, you can
put Nested JPanel to the JScrollPane
to this JPanel
put JPanels contains JComponent to the GridLayout (notice about scrolling, you have to change scrolling increment)
or use most complex JComponents as
put JPanels contains JComponent as Item to the JList
put JPanels contains JComponent as row to the JTable (with only one Column, with or without TableHeader)
Add one panel at the right and one at the bottom.
Right Panel:
Set Weight X to 1.0.
Set Fill to horizontal.
Bottom Panel:
Set Weight Y to 1.0.
Set Fill to vertical
There may be better ways to that, but this one worked for me.
I have 3 JPanels and I want to place them all in one JPanel. I used the GridBagLayout for the main panel. But only one panel is getting added. Why might this be?
gblayout=new GridBagLayout();
gbc=new GridBagConstraints();
panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(gblayout);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.NORTHWEST;
gbc.weightx=1;
gbc.weighty=1;
gbc.gridheight=GridBagConstraints.REMAINDER;
add(panel1, gbc);
add(panel2, gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
add(panel3, gbc);
The customizer methods are ones which add items into these panels.
I am not sure but I think you need to add a GridBagConstraints to your GridBagLayout. Try look at this site to get the idea on how to work with GridBagLayout:
link
Or maybe just use another Layout for your JFrame, maybe BorderLayout or GridLayout to arrange your Panels correctly
You should change gbc.gridx and/or gbc.gridy to be different for each panel
you have to read How to Use GridBagLayout, examples for that here and GridBagConstraints, change your gbc.fill=GridBagConstraints.HORIZONTAL;, if you have problem(s) with JComponent's Size then add setPreferedSize(); for example
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GBLFillBoth extends JFrame {
private static final long serialVersionUID = 1L;
public GBLFillBoth() {
JPanel panel = new JPanel();
GridBagLayout gbag = new GridBagLayout();
panel.setLayout(gbag);
GridBagConstraints c = new GridBagConstraints();
JButton btn1 = new JButton("One");
c.fill = GridBagConstraints.BOTH;
//c.fill = GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.NORTHWEST;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.5;
c.weighty = 0.5;
panel.add(btn1, c);
JButton btn2 = new JButton("Two");
c.gridx++;
panel.add(btn2, c);
//c.fill = GridBagConstraints.BOTH;
JButton btn3 = new JButton("Three");
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
panel.add(btn3, c);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
GBLFillBoth gBLFillBoth = new GBLFillBoth();
}
}
You might consider using a MigLayout instead, the code is much simpler:
panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(new MigLayout("fill, wrap 3"));
add(panel1, "grow");
add(panel2, "grow");
add(panel3, "grow");