I need to format my multiple panels into my main panel, however I'm troubled with which layout to use and more so on how to do it with a specific layout.
The layout I need is like this
So far the code I have is this:
public TDPanel(){
this.setPreferredSize(new Dimension(1150,800));
this.setBackground(Color.gray);
this.tdWorld = towerOfDefenses;
this.setLayout(new FlowLayout());
game = new JPanel();
game.setBackground(Color.blue);
game.setPreferredSize(new Dimension(300,300));
textBox = new JTextField();
textBox.setBackground(Color.ORANGE);
textBox.setPreferredSize(new Dimension(400,300));
menuPanel = new JPanel();
menuPanel.setPreferredSize(new Dimension(100,800));
menuPanel.setBackground(Color.red);
this.add(game);
this.add(textBox);
this.add(menuPanel);
}
I would appreciate any help given!
I would combine at least 3 BorderLayouts. Why? Because the component you put in CENTER will be maximized and for the others you can set a static width (or height) and don't have to do further configuration to get the desired behaviour.
+-------------------------+-----------------------+
| BorderLayout.CENTER (1) | BorderLayout.EAST (2) |
+-------------------------+-----------------------+
In (1) you put the game panel (3) and the "game controls" (4):
+-------------------------+
| BorderLayout.CENTER (3) |
+-------------------------+
| BorderLayout.SOUTH (4) |
+-------------------------+
If you want the text field and the button in (4) to have the same size and maximized (width) then use a GridLayout, othewise you can use FlowLayout to have them layed out with some space after it. But what I recommend doing here is the same as for the game and menu panel in (2): use a BorderLayout and put the component you want to be maximized in the center.
You could use more sophisticated LayoutManagers like BoxLayout or GridBagLayout but it is not really needed for this simple layout (guess it's a matter of taste).
First,I recommend you use Swing Desinger,it's a plug-in unit to visualize your operation.
I'm using GridBagLayout to format these panel,and here is an example.
This is the effect drawing adress
public test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 685, 485);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{175, 40, 180, 217, 0};
gbl_contentPane.rowHeights = new int[]{15, 58, 220, 49, 55, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JPanel gamepanel = new JPanel();
GridBagConstraints gbc_gamepanel = new GridBagConstraints();
gbc_gamepanel.fill = GridBagConstraints.BOTH;
gbc_gamepanel.insets = new Insets(0, 0, 5, 5);
gbc_gamepanel.gridheight = 2;
gbc_gamepanel.gridwidth = 3;
gbc_gamepanel.gridx = 0;
gbc_gamepanel.gridy = 1;
contentPane.add(gamepanel, gbc_gamepanel);
gamepanel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.gridx = 3;
gbc_scrollPane.gridy = 1;
contentPane.add(scrollPane, gbc_scrollPane);
JPanel panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridheight = 3;
gbc_panel.gridx = 3;
gbc_panel.gridy = 2;
contentPane.add(panel, gbc_panel);
panel.setLayout(null);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.BOTH;
gbc_textField.insets = new Insets(0, 0, 0, 5);
gbc_textField.gridx = 0;
gbc_textField.gridy = 4;
contentPane.add(textField, gbc_textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.fill = GridBagConstraints.BOTH;
gbc_btnNewButton.insets = new Insets(0, 0, 0, 5);
gbc_btnNewButton.gridx = 2;
gbc_btnNewButton.gridy = 4;
contentPane.add(btnNewButton, gbc_btnNewButton);
}
If you want the GUI can be resizable,you can set the weghitx and weghity properties.
Related
The problem
I have a JPanel with the GridBagLayout as a layout manager. I want the columns of the layout to have certain widths. Sometimes the width of a column might be lower than the preferred width of a component inside. In this case, the column should force a component to take only the available space of the column.
But, for now, a component inside a cell doesn't shrink if the column width constraint is less than the component's preferred width.
Example
Below is the demo with 4x4 grid. I want the JLabel in the top-left corner to shrink in accordance with the min widths I have set when initialized GridBagLayout (10 px)
As I run the example below, the following result is obtained:
The cell in the top-left takes more space than it was allowed initially by the GridBagLayout
public class ResizeDemo extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ResizeDemo resizeDemo = new ResizeDemo();
resizeDemo.pack();
resizeDemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
resizeDemo.setVisible(true);
});
}
public ResizeDemo() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
JPanel panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 0;
getContentPane().add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
// ============ Set the column widths here ============
// Note that the width of the first column is 10 px
gbl_panel.columnWidths = new int[] {10, 150, 0};
// =====================================================
gbl_panel.rowHeights = new int[]{0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0};
gbl_panel.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel label1 = new JLabel("A very long string here");
label1.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_label1 = new GridBagConstraints();
gbc_label1.fill = GridBagConstraints.HORIZONTAL;
gbc_label1.gridx = 0;
gbc_label1.gridy = 0;
panel.add(label1, gbc_label1);
JLabel label2 = new JLabel("Label");
GridBagConstraints gbc_label2 = new GridBagConstraints();
gbc_label2.gridx = 1;
gbc_label2.gridy = 0;
panel.add(label2, gbc_label2);
JLabel label3 = new JLabel("Label");
GridBagConstraints gbc_label3 = new GridBagConstraints();
gbc_label3.fill = GridBagConstraints.HORIZONTAL;
gbc_label3.gridx = 0;
gbc_label3.gridy = 1;
panel.add(label3, gbc_label3);
JLabel label4 = new JLabel("Label");
GridBagConstraints gbc_label4 = new GridBagConstraints();
gbc_label4.gridx = 1;
gbc_label4.gridy = 1;
panel.add(label4, gbc_label4);
}
}
Question:
How can I force the JLabel inside a GridBagLayout cell to shrink itself?
The GridBagLayout sizes each column based on the largest "preferred size" of any component added to the column.
The "columnWidths" is used to set the minimum value for any column. This is used when you resize the frame. If there is not enough space to display the component at it preferred size and you have set a resize weight for the component, then the component will shrink in size from its preferred size to its minimum size.
How can I force the JLabel inside a GridBagLayout cell to shrink itself?
One possibility is to wrap the label in a panel using a BoxLayout. The BoxLayout will respect the maximum size of size of the component. The basic logic would be:
//panel.add(label1, gbc_label1);
Dimension max = label1.getPreferredSize();
max.width = 10;
label1.setMaximumSize(max);
Box wrapper = Box.createHorizontalBox();
wrapper.add(label1);
panel.add(wrapper, gbc_label1);
Don't know what your real application is, but if you are only using labels, then maybe you can use a JTable. With a JTable you can control the actual column width.
This is the piece in your code that is setting the widths. Lack of setting the column width defaults shrinking to fit the enclosed component.
gbl_panel.columnWidths = new int[] {10, 150, 0};
So I'm trying to make it so that my JList consists of random values everytime I boot my program up (I was using a string array to randomize values from 2 different arrays). I have been struggling to get this working. The elements show when I use one array, but it doesn't work when I use the new array that consists of a string with 2 values from those 2 arrays. How can I make it so that the array with both random values from 2 arrays show up on my JList. I have tried everything starting with making a new array to using DeaultListModel. Any help is appreciated.
Here is my code:
public class game extends JFrame {
private JPanel contentPane;
private JTextField textField_1;
private JTextField textField_2;
//\u21BA is Skip, \u20E0 is Reverse. Action and colorName are the arrays I'm randomizing into the JList
private String[] action = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+2", "\u21BA", " \u20E0"};
private Color[] color = {Color.red, Color.blue, Color.green, Color.yellow};
private String[] colorName = {"Red", "Blue", "Green", "Yellow"};
private DefaultListModel deck;
/**
* Launch the application.
*/
public static void main (String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
game frame = new game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public game() {
setTitle("Uno");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JTextArea textArea = new JTextArea();
textArea.setRows(5);
contentPane.add(textArea, BorderLayout.SOUTH);
\\What I'm struggling with
deck = new DefaultListModel();
for (int i = 0; i <= 7; i++) {
Random r = new Random();
deck.addElement(colorName[r.nextInt(colorName.length)] + " " + action[r.nextInt(action.length)]);
}
JList list = new JList(deck);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFont(UIManager.getFont("ColorChooser.font"));
contentPane.add(list, BorderLayout.WEST);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.EAST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] {44, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Player 1 Card Amount");
lblNewLabel.setFont(new Font("Dialog", Font.PLAIN, 12));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 3;
panel.add(lblNewLabel, gbc_lblNewLabel);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setFont(new Font("Dialog", Font.PLAIN, 12));
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 0;
gbc_textField_1.gridy = 4;
panel.add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("CPU Card Amount");
lblNewLabel_1.setFont(new Font("Dialog", Font.PLAIN, 12));
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 6;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
textField_2 = new JTextField();
textField_2.setFont(new Font("Dialog", Font.PLAIN, 12));
textField_2.setEditable(false);
GridBagConstraints gbc_textField_2 = new GridBagConstraints();
gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_2.gridx = 0;
gbc_textField_2.gridy = 7;
panel.add(textField_2, gbc_textField_2);
textField_2.setColumns(10);
}
}
JList and DefaultListModel are both generic types. They should be JList<String> and DefaultListModel<String> in this case, although that isn't causing your problem. Also, the normal convention for Java is for class names to be capitalized (Game instead of game).
You certainly shouldn't be creating a new Random every time around the loop. It doesn't make sense to me to create random cards, here. They could all be Red 5's. I would create a deck, shuffle it with Fisher-Yates (Collections.shuffle), and take the first seven cards for the player's hand.
If that variable is meant to hold the player's hand, and not the deck, then calling it deck could definitely be confusing. It sounds like that's the player's hand. Better to call it hand.
As you can see in my code, there are two scroll panes at the bottom. I need my gui to show both of these scroll panes on the right side, the smaller one(displaying the current amount of money the player has, this one I need to stay one line thick) and the second one, which will be constantly spitting out information of the player's rolls on the bottom.
Also how do I make it so that my combo box listener will give every item a 10 to its output to start out with then when it is being sent out it gives each 1 more so that they have their unique number starting at 11 then 12, 13, and so on.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dicebot extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
private JButton btnConfirm;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dicebot frame = new dicebot();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dicebot() {
setTitle("Dice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldStartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMultiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_textFieldPassword = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldOdds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMaxBet = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}else if (e.getSource() == btnConfirm){
Dicebotcode dbc = new Dicebotcode();
dbc.dbc();
}
}
}
Two things...
One, if you've added the same scroll pane twice...
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
^--- Note no "l"
And, even if you have added the two scroll pane instances, you've added them to the same place, BorderLayout.CENTER
BorderLayout only allows a single component to be added to one of the available positions it supports, so, in this case, only the second scroll pane would be visible
I want to repeat a JLabel "n" no. of times where "n" is given by user.
This implementation, using WindowBuilder's Grid layout, doesn't work, prints nothing at all.
What am I doing wrong?
JLabel lblNewLabel_1[]=new JLabel[20];
GridBagConstraints gbc_lblNewLabel_1[] = new GridBagConstraints[20];
for(int i=0;i<n;i++)
{
lblNewLabel_1[i] = new JLabel("Table #");
gbc_lblNewLabel_1[i].insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1[i].gridx = 0;
gbc_lblNewLabel_1[i].gridy = 4+i;
frame.getContentPane().add(lblNewLabel_1[i], gbc_lblNewLabel_1[i]);
}
Full Method, my content pane is grid layout.
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 507, 432);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{57, 377, 0};
gridBagLayout.rowHeights = new int[]{60, 37, 35, 20, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
textField = new JTextField();
textField.setToolTipText("Max: 20");
textField.setText("0");
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==textField)
n = Integer.parseInt(arg0.getActionCommand());
}
});
JLabel lblNewLabel = new JLabel("Enter The Number of Tables");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 30));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 1;
frame.getContentPane().add(lblNewLabel, gbc_lblNewLabel);
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
frame.getContentPane().add(textField, gbc_textField);
textField.setColumns(10);
GridBagConstraints gbc_lblNewLabel_1[] = new GridBagConstraints[20];
for(int i=0;i<n;i++){
lblNewLabel_1[i] = new JLabel("Table #");
gbc_lblNewLabel_1[i].insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1[i].gridx = 0;
gbc_lblNewLabel_1[i].gridy = 4+i;
frame.getContentPane().add(lblNewLabel_1[i], gbc_lblNewLabel_1[i]);
}
}
The default layout for a JFrame is a BorderLayout.
If you want to use a GridBagLayout then you need to set the layout of the content pane to use a GridBagLayout.
I suggest you read the section from the Swing turial on How to Use GridBagLayout for more explanation and working examples.
If you want to use a GridLayout, then you also need to set the layout manager of the content pane to a GridLayout and you don't use any constraints. Again, read the tutorial for examples.
I want to have arbitrary JPanels containing a JLabel sacling dynamically in a container (JPanel) with a fixed size. So something like this:
__________________________________
| _____________ _____________ |
| | Test Label| | Test Label| |
| |___________| |___________| |
|________________________________|
scaling to this
__________________________________
| ________ ________ ________ |
| |Tes...| |Tes...| |Tes...| |
| |______| |______| |______| |
|________________________________|
I tried to use a BoxLayout (X-Orientation), setting a maximum size for each contained JPanel:
OuterContainer.Width / NumberOfContainedJPanels
without success. The containers around the labels never fall below a specific width.
Further more using a GridBagLayout does not work good, because i want to dynamically add more containers so it wouldn't be a good way to generate the GridBagLayout constraints on each adding.
Is there a good solution for this problem? The following is a SSCCE for my problem:
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import java.awt.Dimension;
public class DynScalingExample extends JFrame {
public DynScalingExample() {
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
//---Panel 1
JPanel panel = new JPanel();
panel.setMaximumSize(new Dimension(20, 32767));
getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Test label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
panel.add(lblNewLabel, gbc_lblNewLabel);
//---Panel 2
JPanel panel_1 = new JPanel();
getContentPane().add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{0, 0};
gbl_panel_1.rowHeights = new int[]{0, 0};
gbl_panel_1.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel label = new JLabel("Test label");
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.anchor = GridBagConstraints.WEST;
gbc_label.gridx = 0;
gbc_label.gridy = 0;
panel_1.add(label, gbc_label);
//---Panel 3
JPanel panel_2 = new JPanel();
getContentPane().add(panel_2);
GridBagLayout gbl_panel_2 = new GridBagLayout();
gbl_panel_2.columnWidths = new int[]{0, 0};
gbl_panel_2.rowHeights = new int[]{0, 0};
gbl_panel_2.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_2.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panel_2.setLayout(gbl_panel_2);
JLabel label_1 = new JLabel("Test label");
GridBagConstraints gbc_label_1 = new GridBagConstraints();
gbc_label_1.anchor = GridBagConstraints.WEST;
gbc_label_1.gridx = 0;
gbc_label_1.gridy = 0;
panel_2.add(label_1, gbc_label_1);
}
}
As #Andrew Thompson suggested, a GridLayout works perfectly for this purpose. As example, see the following:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DynScalingExample extends JFrame {
public DynScalingExample() {
getContentPane().setLayout(new GridLayout(1, 0, 0, 0));
//---Panel 1
JPanel panel = new JPanel();
getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Test label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
panel.add(lblNewLabel, gbc_lblNewLabel);
//---Panel 2
JPanel panel_1 = new JPanel();
getContentPane().add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{0, 0};
gbl_panel_1.rowHeights = new int[]{0, 0};
gbl_panel_1.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel label = new JLabel("Test label");
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.anchor = GridBagConstraints.WEST;
gbc_label.gridx = 0;
gbc_label.gridy = 0;
panel_1.add(label, gbc_label);
//---Panel 3
JPanel panel_2 = new JPanel();
getContentPane().add(panel_2);
GridBagLayout gbl_panel_2 = new GridBagLayout();
gbl_panel_2.columnWidths = new int[]{0, 0};
gbl_panel_2.rowHeights = new int[]{0, 0};
gbl_panel_2.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_2.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panel_2.setLayout(gbl_panel_2);
JLabel label_1 = new JLabel("Test label");
GridBagConstraints gbc_label_1 = new GridBagConstraints();
gbc_label_1.anchor = GridBagConstraints.WEST;
gbc_label_1.gridx = 0;
gbc_label_1.gridy = 0;
panel_2.add(label_1, gbc_label_1);
}
}