add scrollpane to jpanel when the panel is full (java) - java

I am working on java swing application and I am adding components dynamically in a JPanel. I want to set a JScrollPane on this panel and only if the panel is full we can see this scrollpane.
How can I do it on this :
package add_button;
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.JTextField;
import javax.swing.border.LineBorder;
public class MyExample
{
// 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>();
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);
// Construct panel
panel.setPreferredSize(new Dimension(600, 600));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frameConstraints.weighty = 1;
frame.add(panel, frameConstraints);
// 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("Label " + 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(10, 10, 10, 10);
// 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;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
panel.updateUI();
}
}
}

Here you go
// Construct panel
//panel.setPreferredSize(new Dimension(600, 600)); // No need for panel as it will get added to scrollpane
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
JScrollPane 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(scrollPane, frameConstraints); // add acrollpane to frame
I have created a JScrollPane, added panel as its component and then added scrollPane to frame
Here

frame = new JFrame();
frame.setBounds(0, 0, 820, 950);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setLayout(null);
final JScrollPane scrollPanel = new JScrollPane(
panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
);
scrollPanel.setBounds(0, 0, 800, 900);
panel.setBounds(0, 0, 1920, 1080);
panel.setPreferredSize(new Dimension(1920, 1080));
frame.getContentPane().add(scrollPanel);
This code will work in general to add JScrollPane to JPanel. Adjust bounds of frame, panel and scrollpane according to your requirements but ensure that the bounds of JScrollPane are within the bounds of the frame otherwise the scrollpane will not be visible.

Add panel into JScrollPane, but create ScrollPane by this constractor
JScrollPane scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
ScrollBars became visible only when panel size became bigger then parent component size.

On you jscrollpane you need to set vertical and horizontal bar schemes. for example
import java.awt.BorderLayout;
import java.awt.FlowLayout;
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.JScrollPane;
import javax.swing.JTextArea;
public class windows_test {
JFrame login = null;
JFrame inner_frame = null;
public windows_test() {
login = new JFrame();
login.setBounds(10, 10, 300, 300);
login.setLayout(new BorderLayout());
JPanel temp_panel = new JPanel();
temp_panel.add(new JTextArea("asd fsj adhf jsad kjfh sa dj kfh j sak ds fda f hsa kj d hf ks ad hf kjs ad h fk js ad h fjs da hf k j sahd kjfsh d jk fhs ad"));
login.setVisible(true);
JScrollPane scroll_pane = new JScrollPane(temp_panel);
scroll_pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //SETTING SCHEME FOR HORIZONTAL BAR
scroll_pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
login.add(scroll_pane);
}
}
hope it will help you. if you are facing any problem then you can ask i will try to solve it.

Related

How do I center label and button?

I want my Game to look like this:
but it wont and I don't know why.. everything just doesn't go in the places I want it to be.
Could someone help me? What am I doing wrong?
It looks like this:
The color-changing isn't the problem.. its just where all the stuff is located.
package view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WelcomeScreen extends JFrame{
JButton button;
JLabel label;
ActionListener action;
GridBagLayout gb = new GridBagLayout();
public <button> WelcomeScreen(ActionListener action){
JPanel panel = new JPanel();
this.setSize(800,600);
GridBagConstraints gcon = new GridBagConstraints();
gcon.weightx = 1;
gcon.weighty = 1;
gcon.fill = GridBagConstraints.HORIZONTAL;
gcon.insets = new Insets(5,5,5,5);
button = new JButton("Start");
button.setPreferredSize(new Dimension(200, 50));
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.LEFT);
label = new JLabel("Game");
label.setPreferredSize(new Dimension(200, 50));
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
this.action = action;
panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));
panel.setLayout(gb);
//label
gcon.gridx = 2;
gcon.gridy = 0;
//gcon.gridwidth = 4;
//gcon.gridheight = 1;
gb.setConstraints(label,gcon);
panel.add(label);
//button
gcon.gridx = 2;
gcon.gridy = 1;
//gcon.gridwidth = 2;
//gcon.gridheight = 1;
gb.setConstraints(button,gcon);
panel.add(button);
this.add(panel,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Start");
this.setVisible(true);
button.addActionListener(action);
}
}
As I understand you want the label and the button to be centered in the frame.
For this purpose do not set weightx and weighty since they will tell to layout manager to expand to the available space.
So remove
gcon.weightx = 1;
gcon.weighty = 1;
then, replace the following code
//label
gcon.gridx = 2;
gcon.gridy = 0;
//gcon.gridwidth = 4;
//gcon.gridheight = 1;
gb.setConstraints(label,gcon);
panel.add(label);
//button
gcon.gridx = 2;
gcon.gridy = 1;
//gcon.gridwidth = 2;
//gcon.gridheight = 1;
gb.setConstraints(button,gcon);
panel.add(button);
with this
//label
gcon.gridx = 0;
gcon.gridy = 0;
panel.add(label, gcon);
//button
gcon.gridx = 0;
gcon.gridy = 1;
panel.add(button, gcon);
Since no row and column has weight greater than 0 the layout manager will automatically place the label-button block in the middle.
Complete code
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class WelcomeScreen extends JFrame{
JButton button;
JLabel label;
ActionListener action;
GridBagLayout gb = new GridBagLayout();
public <button> WelcomeScreen(ActionListener action){
JPanel panel = new JPanel();
this.setSize(800,600);
GridBagConstraints gcon = new GridBagConstraints();
gcon.fill = GridBagConstraints.HORIZONTAL;
gcon.insets = new Insets(5,5,5,5);
button = new JButton("Start");
button.setPreferredSize(new Dimension(200, 50));
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.CENTER);
label = new JLabel("Game");
label.setPreferredSize(new Dimension(200, 50));
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
this.action = action;
panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));
panel.setLayout(gb);
//label
gcon.gridx = 0;
gcon.gridy = 0;
panel.add(label, gcon);
//button
gcon.gridx = 0;
gcon.gridy = 1;
panel.add(button, gcon);
this.add(panel,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Start");
this.setVisible(true);
button.addActionListener(action);
}
public static void main(String[] args) {
new WelcomeScreen(null).setVisible(true);
}
}
If you're willing to use Libraries I can recommend MigLayout.
Solution:
With MigLayout the code looks a bit more readable and it's generally easier:
JPanel contentPane = new JPanel(new MigLayout("", "[grow, center]", "[grow, center]"));
JPanel panel = new JPanel(new MigLayout("wrap 1", "[grow, fill]", "[]20px[]"));
JLabel label = new JLabel("Game");
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
panel.add(label);
JButton button = new JButton("Start");
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(button);
contentPane.add(panel);
setContentPane(contentPane);
Explanation:
The 'panel' is still the JPanel holding the components. The content is controlled by the layouts contraints:
The first argument of its MigLayout are the layout contrains and in that case it just auto wraps to the next line after each added component.
The second argument are the column contraints. Here it makes sure that the 'cells' (the layout manager works like a table) expand with 'grow' and the component inside that cell fill the whole cell with 'fill'.
The third argument are the row constraints. Here they just defines the gap between the rows. The '[]' in the column & row contrains stand for a column / row respectively. Anything inside that bracket defines how the cell and its content behaves, anything outside the brackets is used for defining gaps.
The 'contentPane' just makes sure that the 'panel' is centered inside using the same methods described above. It can then be added to a bigger component (like a frame) and expand, still keeping the content centered.
You should find all the info abould the Layouts capabilities at http://www.miglayout.com/whitepaper.html

How to set correctly sizes of a jpanels?

I have a two jpanels: jpanel1 and jpanel2 which must have correct minimal size according to their content. jpanel0 is the container for these two panels, it must be on the left side of a frame. And here is jpanel3 that should take the rest of the available space on the right side.
How to set the size of a jpanel to all available space?
My desired output:
My current output:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Panels {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
myFrame.setLayout(new BorderLayout());
JTabbedPane jtp = new JTabbedPane();
JPanel jPaneTab1 = new JPanel();
jPaneTab1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel jpanel0 = new JPanel();
jpanel0.setLayout(new BoxLayout(jpanel0, BoxLayout.Y_AXIS));
jpanel0.setBorder(BorderFactory.createTitledBorder("jpanel0"));
jpanel0.setBackground(Color.RED);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridBagLayout());
jpanel1.setBorder(BorderFactory.createTitledBorder("jpanel1"));
GridBagConstraints gc = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel1 = new JLabel("jlabel1");
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel1, gc);
JLabel jlabel2 = new JLabel("jlabel2");
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel2, gc);
JPanel jpanel2 = new JPanel();
jpanel2.setLayout(new GridBagLayout());
jpanel2.setBorder(BorderFactory.createTitledBorder("jpanel2"));
GridBagConstraints gc2 = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel3 = new JLabel("jlabel3");
gc2.gridx = 0;
gc2.gridy = 0;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel3, gc2);
JLabel jlabel4 = new JLabel("jlabel4");
gc2.gridx = 0;
gc2.gridy = 1;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel4, gc2);
JPanel jpanel3 = new JPanel();
jpanel3.setBackground(Color.YELLOW);
JLabel jlabel5 = new JLabel("jpanel3");
jpanel3.add(jlabel5);
jpanel0.add(jpanel1);
jpanel0.add(jpanel2);
jPaneTab1.add(jpanel0, BorderLayout.WEST);
jPaneTab1.add(jpanel3, BorderLayout.CENTER);
JPanel jPaneTab2 = new JPanel();
jtp.addTab("tab1", jPaneTab1);
jtp.addTab("tab2", jPaneTab2);
myFrame.add(jtp);
myFrame.setSize(800, 600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Addition:
When I use BorderLayout for main(tab panel) I'm getting another problem:
Layouts work easier when you break down the layout into logical panels and then nest panels with different layout managers.
For example, use a panel with a BorderLayout as the content for the tabbed pane.
Then you create a "ride side panel" and add it to this panel and a "center panel"
JPanel main = new JPanel( new BorderLayout() );
JPanel rightSide = new JPanel( ... );
JPanel center = new JPanel(...);
main.add(rightSide, BorderLayout.LINE_START);
main.add(center, BorderLayout.CENTER);
Then you set the layouts for the "rightSide" and "center" panels and add components to each of those panels.
You should not be using GridBagLayout, BorderLayout, or BoxLayout managers. These are outdated managers from the 90s.
For instance, when you do this:
gc.insets = new Insets(0, 0, 0, 2);
you are hardcoding pixel-width spaces between components, which
will not work across the wide variety of today's screens.
Insted, one should choose either GroupLayout or MigLayout.
Here is a working example with the MigLayout manager. Notice how easy
is to create the layout with this manager. (Four lines of code.) Also, we use logical pixels (lp) instead of physical pixels.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
public class PanelsEx extends JFrame {
public PanelsEx() {
initUI();
}
private void initUI() {
JTabbedPane tabpane = new JTabbedPane();
JPanel mainPanel = new JPanel();
JPanel pnl1 = createPanel("Panel 1");
JPanel pnl2 = createPanel("Panel 2");
JPanel pnl3 = createPanel("Panel 3");
mainPanel.setLayout(new MigLayout("ins 10lp"));
mainPanel.add(pnl1, "w 150lp, h 100lp, split 2, flowy, ay top");
mainPanel.add(pnl2, "w 150lp, h 100lp");
mainPanel.add(pnl3, "push, grow");
tabpane.add("First", mainPanel);
add(tabpane);
pack();
setTitle("Panels");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JPanel createPanel(String text) {
JLabel lbl = new JLabel(text);
JPanel pnl = new JPanel();
pnl.add(lbl);
pnl.setBorder(BorderFactory.createEtchedBorder());
return pnl;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
PanelsEx ex = new PanelsEx();
ex.setVisible(true);
});
}
}
And here is a screenshot:

Align 2 sets/items on either side of center

I'm trying to figure out the best way to align 2 sets of items in the center of a panel in a Java Swing application. The panel is in the North position of a BorderLayout whose width is determined by the JTextField in the Center position of the layout. The problem I'm having is, I have a set of labels and smaller text fields that I want to center so that the end of the label and the start of the first text field meet at the center of the panel.
I've tried GroupLayout, but ended up with the following result:
Note: The 2 text fields separated by a + are in a sub-panel.
What I'm trying to achieve is the following:
Apparently I'm either missing something, or this is far more complicated than necessary to do. I actually run into this issue a LOT! I'm surprised there isn't a special grid layout specifically for this.
Trying to do this with a GridLayout resulted in this:
So... what IS the easiest way to get the layout I'm looking for (second image)?
GroupLayout example code below:
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
frame.setContentPane(panel);
JPanel longText = new JPanel();
JPanel shortText = new JPanel();
JPanel mediumText = new JPanel();
longText.add(new TextField(5));
longText.add(new JLabel("+"));
longText.add(new TextField(5));
shortText.add(new TextField(5));
shortText.add(new JLabel("+"));
shortText.add(new TextField(5));
mediumText.add(new TextField(5));
mediumText.add(new JLabel("+"));
mediumText.add(new TextField(5));
JLabel lExample = new JLabel("Long text example:");
JLabel sExample = new JLabel("Short:");
JLabel mExample = new JLabel("Medium Example:");
JPanel subPanel = new JPanel();
GroupLayout layout = new GroupLayout(subPanel);
subPanel.setLayout(layout);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(lExample)
.addComponent(sExample)
.addComponent(mExample))
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(longText)
.addComponent(shortText)
.addComponent(mediumText))))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(lExample)
.addComponent(longText))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(sExample)
.addComponent(shortText))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(mExample).addComponent(mediumText))
);
JTextArea textArea = new JTextArea() {
#Override
public Dimension getPreferredSize() {
return new Dimension(600,300);
}
};
textArea.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAutoscrolls(true);
panel.add(subPanel,BorderLayout.NORTH);
panel.add(textArea,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
Consider using a GridBagLayout, as it gives you a lot more control over the placement of individual components and respects the preferred size of the components where it can (unless you override them through the use of the GridBagConstraints)
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutExample {
public static void main(String[] args) {
new LayoutExample();
}
public LayoutExample() {
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() {
JLabel longText = new JLabel("Long Text Example");
JLabel shortText = new JLabel("Short Example");
JLabel medText = new JLabel("Medium Example");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(longText, gbc);
addFields(gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.EAST;
add(shortText, gbc);
addFields(gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.EAST;
add(medText, gbc);
addFields(gbc);
}
protected void addFields(GridBagConstraints gbc) {
JTextField field1 = new JTextField("0", 5);
field1.setEnabled(false);
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx++;
add(field1, gbc);
gbc.gridx++;
gbc.insets = new Insets(0, 4, 0, 4);
add(new JLabel("+"), gbc);
JTextField field2 = new JTextField(5);
gbc.gridx++;
add(field2, gbc);
}
}
}

Alignment issues with BoxLayout

I am making an application for which I am using a BoxLayout. As you can see in the following picture, when the title string is short, it's perfect. But as the string gets longer, the JLabel gets more and more misaligned.
Here's some code that is related to the problem:
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
frame.add(centerPanel, BorderLayout.CENTER);
//...
JLabel l = new JLabel(/*...*/);
l.setHorizontalAlignment(SwingConstants.CENTER); //I tried removing and adding
//this but nothing changed
centerPanel.add(l);
Is there something obvious I am missing? Google isn't being helpful with this problem.
In case it's important, the country-label-progress-bar things are just JPanels with FlowLayouts.
SSCCE:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SSCCE {
public static void main(String[] args) {
final JFrame f = new JFrame("SSCCE");
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
final JLabel[] titles = new JLabel[5];
JPanel[] smallPanels = new JPanel[titles.length];
for (int i = 0; i < smallPanels.length; i ++) {
titles[i] = new JLabel(Math.random() < 0.5 ? "foo" : "bar");
p.add(titles[i]);
smallPanels[i] = new JPanel();
smallPanels[i].add(new JLabel("foobar"));
smallPanels[i].add(new JProgressBar());
p.add(smallPanels[i]);
}
f.add(p, BorderLayout.CENTER);
final JTextField tf = new JTextField("foobar");
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
titles[2].setText(tf.getText());
f.repaint();
}
});
f.add(tf, BorderLayout.NORTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 600);
f.setVisible(true);
}
}
To operate the SSCCE, type something in the text field and press enter.
Here is an updated version of your SSCCE with a GridBagLayout. Not sure of how you want components to resize when labels or frame size changes but it should not be too hard to manage this.
import java.awt.BorderLayout;
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.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class SSCCE {
public static void main(String[] args) {
final JFrame f = new JFrame("SSCCE");
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
Insets insets = new Insets(3, 3, 3, 3);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridwidth = GridBagConstraints.REMAINDER;
gbc1.anchor = GridBagConstraints.CENTER;
gbc1.insets = insets;
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.anchor = GridBagConstraints.EAST;
gbc2.insets = insets;
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.weightx = 1.0;
gbc3.fill = GridBagConstraints.HORIZONTAL;
gbc3.gridwidth = GridBagConstraints.REMAINDER;
gbc3.insets = insets;
final JLabel[] titles = new JLabel[5];
Random random = new Random();
for (int i = 0; i < titles.length; i++) {
titles[i] = new JLabel(Math.random() < 0.5 ? "foo" : "bar");
p.add(titles[i], gbc1);
p.add(new JLabel("foobar"), gbc2);
JProgressBar progress = new JProgressBar();
progress.setStringPainted(true);
progress.setString(String.valueOf(random.nextInt(100)));
p.add(progress, gbc3);
}
f.add(p, BorderLayout.CENTER);
final JTextField tf = new JTextField("foobar");
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
titles[2].setText(tf.getText());
f.repaint();
}
});
f.add(tf, BorderLayout.NORTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
BoxLayout accepting Min, Max and PreferredSize, childs could be resizable from Min to MaxSize
FlowLayout accepting only PreferredSize, rest (Min, MaxSize) is ignored by this LayoutManager, childs aren't resizable
these XxxSize are calculated from PreferredSize came from childs placed into container (JPanel in this case)
(your question) for better help sooner post an SSCCE, short, runnable, compilable, just about your issue

Resizable Swing layout with buttons arranged according to variable dimensions

I would like to make a layout using Java Swing which looks like the following drawing.
(source: braun-abstatt.de)
On the left is a JPanel which is drawn through paintComponent() in a way that the graphics automatically scale when the window is resized. (The question isn't about that panel. That one's already done.)
Now I need some buttons (the black boxes, added in Photoshop for the drawing) to the right of the JPanel mentioned before. The height of the reddish areas at the top and bottom, next to which there should be just empty space, is calculated along the lines of CONSTANT_FACTOR * getHeight(). Next to each compartment on the left, there should be a group of buttons, lined up to the center of the respective compartment (see the blue lines).
The JPanel containing the buttons knows about the CONSTANT_FACTOR and the number of compartments, so it should be possible to feed this information into a layout manager.
Which layout manager would I best use to achieve this layout? I've read about all the different layout managers, but I can't quite figure out which one or which combination of them best fits in this case.
For example, by use of a different LayoutManager, a very easy and simple container, takes no more than 15-20 minutes:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class ThinLineFrame {
private JFrame frame = new JFrame();
private JScrollPane scrollPane;
private JPanel panel = new JPanel();
private JPanel panelNorth = new JPanel();
private JPanel panelCenter = new JPanel();
private JPanel panelCenterCh1 = new JPanel();
private JPanel panelCenterCh2 = new JPanel();
private JPanel panelCenterCh3 = new JPanel();
private JPanel panelCenterCh4 = new JPanel();
private JPanel panelCenterCh5 = new JPanel();
private JPanel panelSouth = new JPanel();
public ThinLineFrame() {
panelNorth.setBackground(Color.red.darker());
panelNorth.setPreferredSize(new Dimension(80, 30));
//
panelCenter.setBackground(Color.darkGray);
panelCenter.setLayout(new GridLayout(5, 1, 2, 2));
//
panelCenterCh1.setLayout(new BorderLayout());
JButton panelCenterCh1Button = new JButton();
panelCenterCh1.add(panelCenterCh1Button, BorderLayout.CENTER);
//
JButton panelCenterCh2Button1 = new JButton();
JButton panelCenterCh2Button2 = new JButton();
panelCenterCh2.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh2.add(panelCenterCh2Button1);
panelCenterCh2.add(panelCenterCh2Button2);
//
JButton panelCenterCh3Button1 = new JButton();
JButton panelCenterCh3Button2 = new JButton();
panelCenterCh3.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh3.add(panelCenterCh3Button1);
panelCenterCh3.add(panelCenterCh3Button2);
//
JButton panelCenterCh4Button1 = new JButton();
JButton panelCenterCh4Button2 = new JButton();
panelCenterCh4.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh4.add(panelCenterCh4Button1);
panelCenterCh4.add(panelCenterCh4Button2);
//
panelCenterCh5.setLayout(new BorderLayout());
JButton panelCenterCh5Button = new JButton();
panelCenterCh5.add(panelCenterCh5Button, BorderLayout.CENTER);
//
panelCenter.add(panelCenterCh1);
panelCenter.add(panelCenterCh2);
panelCenter.add(panelCenterCh3);
panelCenter.add(panelCenterCh4);
panelCenter.add(panelCenterCh5);
//
panelSouth.setBackground(Color.red.darker());
panelSouth.setPreferredSize(new Dimension(80, 30));
//
panel.setLayout(new BorderLayout(2, 2));
panel.add(panelNorth, BorderLayout.NORTH);
panel.add(panelCenter, BorderLayout.CENTER);
panel.add(panelSouth, BorderLayout.SOUTH);
//
scrollPane = new JScrollPane(panel);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(80, 600));
frame.setLocation(100, 150);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ThinLineFrame dlg = new ThinLineFrame();
}
});
}
}
You should try looking at MigLayout. It's a super flexible LayoutManager that is also very simple.
The code would look something like:
MigLayout layout = new MigLayout("flowy");
panel.setLayoutManager(layout);
panel.add(button1);
panel.adD(button2);
etc..
Try adding debug, flowy to the constructor to get a visual idea of what is going on.
GBC without an anchor, just with plain vanilla GridBagConstraints and preferred size.
Centered JButton with fixed size:
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainWithFixSize {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
GridBagLayout gbl = new GridBagLayout();
container.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
JButton component = new JButton();
component.setPreferredSize(new Dimension(25, 25));
gbl.setConstraints(component, gbc);
container.add(component);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(40, 90));
frame.pack();
frame.setVisible(true);
}
private MainWithFixSize() {
}
}

Categories

Resources