Fixed size of buttons - java

There is a JPanel with buttons and textField. TextField filters unnecessary buttons by name. But after delete the size of rest buttons is changing.
The height of buttons must not change after filtering in the textField. How to achieve this?
public class TestViewer {
public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog dialog = new TestDialog();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setTitle("Type text and press Enter");
dialog.setSize(300, 700);
dialog.setVisible(true);
dialog.setLocationRelativeTo(null);
dialog.setModal(true);
}
});
}
}
class TestDialog extends JDialog {
public TestDialog() {
getContentPane().add(new JPan
el(), BorderLayout.CENTER);
getContentPane().add(createBtnPanel(), BorderLayout.CENTER);
}
private JPanel createBtnPanel() {
int n = 100;
Final String ArrButtonNames[] = new String[n];
for (int h = 0; h < ArrButtonNames.length; h++) {
if ((h%2)==0){
ArrButtonNames[h]="Filter"+h;
}
else{
ArrButtonNames[h]="Button"+h;
}
}
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel(new GridLayout(0, ArrButtonNames.length, 1,1));
btnPanel.setLayout(new GridLayout(0, 1));
final JTextField textField = new JTextField();
textField.setColumns(23);
btnPanel.add(textField);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
Dimension d = button.getPreferredSize();
d.setSize(d.getWidth(), d.getHeight()*1);
button.setPreferredSize(d);
button.setSize(d);
button.setMinimumSize(d);
button.setMaximumSize(d);
btnPanel.add(button);
ArrButton[i] = button;
}
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int k = 0; k < ArrButtonNames.length; k++) {
if(ArrButtonNames[k].indexOf(textField.getText())==-1) {
btnPanel.remove(ArrButton[k]);
btnPanel.revalidate();
btnPanel.repaint();
}
}
}
});
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new BorderLayout());
MainPanel.add(btnPanel, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane(btnPanel);
MainPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
return MainPanel;
}
}

You have that effect, because you use GridLayout, which resize components to fill whole cell.
For your purposes I recommend you to use GridBagLayout, that can do what you want.
Try to use next code for filling your btnPanel instead of yours:
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx=0;
c.gridy=0;
btnPanel.setLayout(new GridBagLayout());
final JTextField textField = new JTextField();
btnPanel.add(textField,c);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
c.gridy ++;
btnPanel.add(button,c);
ArrButton[i] = button;
}
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.gridy ++;
btnPanel.add(new JLabel(""),c);
And it looks like:
ALso use pack() method instead of setSize(...), and don't use setPreferedSize(...) and others size methods read about that here.

Related

Changing boolean in actionlistener

I have an actionlistener on a button that is to change a boolean called flood to true when clicked, this is then used in an if statement to call a method that will change a frame. My problem is nothing is happening when the button is clicked. I am using a debug log to check for the problem but I'm stumped.
public class Stop_The_Flood extends JFrame implements ActionListener{
final Button StopTheFlood = new Button("Stop The Flood!");
boolean flood = false;
public Stop_The_Flood(char[][] array) {
setTitle("Stop The Flood!");
setSize(1024,768);
//Container panel
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
//map panel
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(700, 900));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = array[0].length;
gbc.gridheight = array.length;
gbc.fill = GridBagConstraints.BOTH;
//Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.gridwidth = 1;
g.gridheight = 1;
g.gridx = 8;
g.gridy = 15;
g.fill = GridBagConstraints.BOTH;
buttonPanel.setSize(350,350);
//Add to everything to frame
getContentPane().add(container);
container.add(panel, gbc);
container.add(buttonPanel, g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 100, 100);
StopTheFlood.setBackground(Color.cyan);
StopTheFlood.addActionListener(this);
JLabel[][] labelArray = new JLabel[array.length][array[0].length];
//Initialize JLabel array with the array that contains the data
labels(panel, labelArray, array);
buttonPanel.add(StopTheFlood);
setVisible(true);
if(flood == true) {
final Logger logger = Logger.getLogger("Stop_The_Flood");
logger.warning("found water");
}
}
public void actionPerformed(ActionEvent event) {
flood = true;
}
Nothing is being performed in your actionPerformed method, so you could try to create a new ClickListener class:
private class Clicklistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == StopTheFlood)
{
flood = true;
}
}
}
Then on your "Stop_The_Flood" class create an object of ClickListener and add it to .addActionLister():
Clicklistener click= new Clicklistener();
StopTheFlood.addActionListener(click);
P.S don't forget to pass StopTheFlood to the ClickListener since I did not add that to the code.

Jpanels with Gridbaglayout inside a JPanel with GridbagLayout problems

I'm trying to get the CardLayout working correctly. - I have the first "card" in my deck", which i've called firstPanel (Gridbaglayout). Inside that panel i want some other panels with the same layout (Gridbaglayout) which ofc has some components.
as example under here - I'm showing one of the JPanels with Gridbaglayout that i want inside my firstPanel (Jpanel) called textFieldForPlayers.
I hope you understand what i mean. if not i'll try to explain it more detailed. :)
public void run() {
deck.setLayout(cl);
c = new GridBagConstraints();
firstPanel.setLayout(new GridBagLayout());
secondPanel.setLayout(new GridBagLayout());
thirdPanel.setLayout(new GridBagLayout());
GamePanel gamePanel = new GamePanel();
c.gridx = 0;
c.gridy = 0;
firstPanel.add(textFieldForPlayers(humanPLayers), c);
c.gridx = 0;
c.gridy = 1;
firstPanel.add(botPreferences(), c);
c.gridx = 0;
c.gridy = 2;
firstPanel.add(next = new JButton("Next"), c);
c.gridx = 0;
c.gridy = 0;
secondPanel.add(new JLabel("Bot preferences"), c);
c.gridx = 0;
c.gridy = 0;
thirdPanel.add(gamePanel, c);
deck.add(firstPanel, "1");
deck.add(secondPanel, "2");
deck.add(thirdPanel, "3");
cl.show(deck, "1");
events();
}
private JPanel textFieldForPlayers(int hplayers) {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
c = new GridBagConstraints();
JLabel text = new JLabel("Name of the human players");
c.gridx = 0;
c.gridy = 0;
panel.add(text, c);
boxes = new ArrayList<>();
boxes.add(new JTextField());
boxes.add(new JTextField());
boxes.add(new JTextField());
boxes.add(new JTextField());
boxes.add(new JTextField());
boxes.add(new JTextField());
for (int i = 1; i <= hplayers; i++) {
boxes.get(i).setPreferredSize(new Dimension(165, 18));
c.gridx = 1;
c.gridy = i;
panel.add(boxes.get(i), c);
c.gridx = 0;
c.gridy = i;
panel.add(new JLabel("Player " + i + ": "), c);
}
return panel;
}
Picture 3 - This is what it looks like now
Picture 4 - Should be - 1 in the top, 2 in the middle and 3 in the bottom. All of them centeret.
Your CardLayout, cl, is not behaving as a true CardLayout, suggesting something is wrong with code not shown. Myself, I try to modularize my gui creation, including using a separate utility method to help create gridbagconstraints if any complex constraints are needed.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class GridBagEg extends JPanel {
public static final int PLAYER_COUNT = 5;
private CardLayout cardLayout = new CardLayout();
private JPanel deckPanel = new JPanel(cardLayout);
private NextAction nextAction = new NextAction("Next");
private PlayerPanel playerPanel = new PlayerPanel(PLAYER_COUNT);
private BotDifficultyPanel botDifficultyPanel = new BotDifficultyPanel();
public GridBagEg() {
deckPanel.add(playerPanel, PlayerPanel.NAME);
deckPanel.add(botDifficultyPanel, BotDifficultyPanel.NAME);
JPanel nextBtnPanel = new JPanel();
nextBtnPanel.add(new JButton(nextAction));
setLayout(new BorderLayout());
add(deckPanel, BorderLayout.CENTER);
add(nextBtnPanel, BorderLayout.PAGE_END);
}
private class NextAction extends AbstractAction {
public NextAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(deckPanel);
}
}
private static void createAndShowGui() {
GridBagEg mainPanel = new GridBagEg();
JFrame frame = new JFrame("GridBagEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class BotDifficultyPanel extends JPanel {
public static final String NAME = "bot difficulty panel";
public static final String[] LEVELS = {"Easy", "Mid-level", "Difficult", "Holy Mother of God Difficulty"};
private JComboBox<String> difficultyCombo = new JComboBox<>(LEVELS);
public BotDifficultyPanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Bot Difficulty:"), gbc);
gbc.gridx = 1;
gbc.insets = new Insets(0, 10, 0, 0);
add(difficultyCombo, gbc);
}
public String getSelectedDifficulty() {
String selection = (String) difficultyCombo.getSelectedItem();
return selection;
}
}
#SuppressWarnings("serial")
class PlayerPanel extends JPanel {
public static final String NAME = "player panel";
private static final String TITLE = "Name of Human Players";
private static final int EB_GAP = 10;
private static final int FIELD_COLUMNS = 15;
private static final int INS_GAP = 5;
private int playerMaxCount = 0;
private List<JTextField> playerFields = new ArrayList<>();
public PlayerPanel(int playerMaxCount) {
this.playerMaxCount = playerMaxCount;
Border outsideBorder = BorderFactory.createTitledBorder(TITLE);
Border insideBorder = BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP);
setBorder(BorderFactory.createCompoundBorder(outsideBorder, insideBorder));
setLayout(new GridBagLayout());
for (int i = 0; i < playerMaxCount; i++) {
JTextField playerField = new JTextField(FIELD_COLUMNS);
playerFields.add(playerField);
add(new JLabel("Player " + i + ":"), createGbc(0, i));
add(playerField, createGbc(1, i));
}
}
public String getFieldName(int index) {
if (index < 0 || index >= playerFields.size()) {
String text = "for playerFields index of " + index;
throw new IllegalArgumentException(text);
} else {
return playerFields.get(index).getText();
}
}
public int getPlayerMaxCount() {
return playerMaxCount;
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
// if x is 0, anchor to the left otherwise to the right
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(INS_GAP, INS_GAP, INS_GAP, INS_GAP);
if (x == 0) {
gbc.insets.right = 4 * INS_GAP; // increase gap in between
}
return gbc;
}
}
Like:
CardLayout cl = new CardLayout();
JPanel contentPane = new JPanel();
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
contentPane.setlayout(cl);
firstPanel.add(new JButton("1"));
secondPanel.add(new JButton("2"));
contentPane.add(firstPanel, "1");
contentPane.add(secondPanel, "2");
cl.show(contentPane, "1");
So now the contentPane contains 2 JPanels inside it. and now we would be seeing everything on firstPanel right? :)

How to change frame on button event Java

I am making a simple project. It has login window like this
When the user click on button log in - it should "repaint" the window(it should seem to be happened in the same window) and then the window looks like this.
The problem is - I can't "repaint" the window - the only thing I can - it's create a new frame, so there actually are 2 frames totally.
How to make the whole thing in one same frame.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPane(Container pane)
{
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
pane.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
pane.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
JPanel panel = new JPanel();
JLabel label = new JLabel("Your login:");
panel.add(label);
JTextField textField = new JTextField(15);
panel.add(textField);
JButton loginButton = new JButton("log in");
panel.add(loginButton);
JButton exitButton = new JButton("exit");
panel.add(exitButton);
frame.add(panel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
frame = null;
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
}
Use CardLayout.
This layout allows developers to switch between panels. It works by creating a "deck" panel that'll contain all of panels that'll potentially be displayed:
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
When you click on a button, that button's ActionListener should call show(Container, String), next(Container) or previous(Container) on the CardLayout to switch which panel is being displayed:
public void actionPerformed(ActionEvent e) {
layout.show(deck, "second");
}
One of the solutions
You can create two panels (one for each view) and add the required components to them. First, you add first panel to the frame (using frame.add(panel1)). If you want to show the second panel in the same window, you can delete first panel (using frame.remove(panel1)) and add the second panel (using frame.add(panel2)). At the end you've to call frame.pack().
This's your code with above solution:
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPanel2()
{
panel2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
panel2.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
panel2.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
panel1 = new JPanel();
JLabel label = new JLabel("Your login:");
panel1.add(label);
JTextField textField = new JTextField(15);
panel1.add(textField);
JButton loginButton = new JButton("log in");
panel1.add(loginButton);
JButton exitButton = new JButton("exit");
panel1.add(exitButton);
frame.add(panel1, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
panel2 = new JPanel();
addComponentsToPanel2();
frame.remove(panel1);
frame.add(panel2);
//frame.repaint();
frame.pack();
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
private JPanel panel1;
private JPanel panel2;
}

Swing: Panel Size Issue

I am designing an application, in which there should be 5 different JPanels containing different Swing components. For the JRadioButton part, I ran into an issue for which couldn't find proper solution. The 'radioSizePanel' is supposed to be placed somewhere in upper middle of the main panel. Has anyone solved this problem before ? Here is the code, that I am using :
import java.awt.*;
import javax.swing.*;
public class PizzaShop extends JFrame
{
private static final long serialVersionUID = 1L;
private JRadioButton[] radio_size = new JRadioButton[3];
private JRadioButton[] radio_type = new JRadioButton[3];
public PizzaShop()
{
initializaUI();
}
private void initializaUI()
{
setSize(700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel container to wrap checkboxes and radio buttons
JPanel panel = new JPanel();
//sizes radio buttons
String Size[] = {"Small: $6.50", "Medium: $8.50", "Large: $10.00"};
JPanel radioSizePanel = new JPanel(new GridLayout(3, 1));
ButtonGroup radioSizeGroup = new ButtonGroup();
for (int i=0; i<3; i++)
{
radio_size[i] = new JRadioButton(Size[i]);
radioSizePanel.add(radio_size[i]);
radioSizeGroup.add(radio_size[i]);
}
radioSizePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Size"));
radioSizePanel.setPreferredSize(new Dimension(100, 200));
//
panel.add(radioSizePanel);
setContentPane(panel);
setContentPane(radioSizePanel);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PizzaShop().setVisible(true);
}
});
}
}
Here is what I want as an expected OUTPUT :
Please do watch the code example and Please do watch everything carefully , the sequence of adding things to the JFrame. Since in your example you calling setSize() much before something has been added to the JFrame, hence first add components to the container, and then call it's pack()/setSize() methods, so that it can realize that in a good way.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PizzaLayout
{
/*
* Five JPanels we will be using.
*/
private JPanel headerPanel;
private JPanel footerPanel;
// This JPanel will contain the middle components.
private JPanel centerPanel;
private JPanel toppingPanel;
private JPanel sizePanel;
private JPanel typePanel;
private JPanel buttonPanel;
private String[] toppings = {
"Tomato",
"Green Pepper",
"Black Olives",
"Mushrooms",
"Extra Cheese",
"Pepproni",
"Sausage"
};
private JCheckBox[] toppingsCBox;
private String[] sizePizza = {
"Small $6.50",
"Medium $8.50",
"Large $10.00"
};
private JRadioButton[] sizePizzaRButton;
private String[] typePizza = {
"Thin Crust",
"Medium Crust",
"Pan"
};
private JRadioButton[] typePizzaRButton;
private JButton processButton;
private ButtonGroup bGroupType, bGroupSize;
private JTextArea orderTArea;
private StringBuilder sBuilderOrder;
private void displayGUI()
{
JFrame frame = new JFrame("Pizza Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*
* This JPanel is the base of all the
* other components, and at the end
* we will set this as Content Pane
* for the JFrame.
*/
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(10, 10, 10, 10));
/*
* TOP PART of the LAYOUT.
*/
headerPanel = new JPanel();
JLabel headerLabel = new JLabel(
"Welcome to Home Style Pizza Shop"
, JLabel.CENTER);
headerLabel.setForeground(Color.RED);
headerPanel.add(headerLabel);
/*
* CENTER PART of the LAYOUT.
*/
centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.weightx = 0.3;
gbc.weighty = 1.0;
/*
* Above Constraints are for this part.
*/
toppingPanel = new JPanel();
toppingPanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Each Topping $1.50"));
JPanel checkBoxesPanel = new JPanel();
checkBoxesPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
checkBoxesPanel.setLayout(new GridLayout(0, 1, 5, 5));
toppingsCBox = new JCheckBox[toppings.length];
for (int i = 0; i < toppings.length; i++)
{
toppingsCBox[i] = new JCheckBox(toppings[i]);
checkBoxesPanel.add(toppingsCBox[i]);
}
toppingPanel.add(checkBoxesPanel);
centerPanel.add(toppingPanel, gbc);
// Till this.
gbc.gridx = 1;
gbc.gridheight = 1;
gbc.weighty = 0.7;
/*
* Above Constraints are for this part.
*/
sizePanel = new JPanel();
sizePanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Pizza Size"));
JPanel radioBoxesPanel = new JPanel();
radioBoxesPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
radioBoxesPanel.setLayout(new GridLayout(0, 1, 10, 10));
sizePizzaRButton = new JRadioButton[sizePizza.length];
bGroupSize = new ButtonGroup();
for (int i = 0; i < sizePizza.length; i++)
{
sizePizzaRButton[i] = new JRadioButton(sizePizza[i]);
bGroupSize.add(sizePizzaRButton[i]);
radioBoxesPanel.add(sizePizzaRButton[i]);
}
sizePanel.add(radioBoxesPanel);
centerPanel.add(sizePanel, gbc);
// Till this.
gbc.gridx = 2;
gbc.weighty = 0.7;
/*
* Above Constraints are for this part.
*/
typePanel = new JPanel();
typePanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Pizza Type"));
JPanel radioBoxesTypePanel = new JPanel();
radioBoxesTypePanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
radioBoxesTypePanel.setLayout(new GridLayout(0, 1, 10, 10));
typePizzaRButton = new JRadioButton[typePizza.length];
bGroupType = new ButtonGroup();
for (int i = 0; i < typePizza.length; i++)
{
typePizzaRButton[i] = new JRadioButton(typePizza[i]);
bGroupType.add(typePizzaRButton[i]);
radioBoxesTypePanel.add(typePizzaRButton[i]);
}
typePanel.add(radioBoxesTypePanel);
centerPanel.add(typePanel, gbc);
// Till this.
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weighty = 0.3;
gbc.gridwidth = 2;
processButton = new JButton("Process Selection");
processButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
sBuilderOrder = new StringBuilder();
sBuilderOrder.append("Pizza type : ");
for (int i = 0; i < typePizza.length; i++)
{
if (typePizzaRButton[i].isSelected())
sBuilderOrder.append(typePizzaRButton[i].getText());
}
sBuilderOrder.append("\n");
sBuilderOrder.append("Pizza Size : ");
for (int i = 0; i < sizePizza.length; i++)
{
if (sizePizzaRButton[i].isSelected())
sBuilderOrder.append(sizePizzaRButton[i].getText());
}
sBuilderOrder.append("\n");
sBuilderOrder.append("Toppings : ");
/*
* I hope you can do this part yourself now :-)
*/
orderTArea.setText(sBuilderOrder.toString());
}
});
centerPanel.add(processButton, gbc);
footerPanel = new JPanel();
footerPanel.setLayout(new BorderLayout(5, 5));
footerPanel.setBorder(
BorderFactory.createTitledBorder("Your Order : "));
orderTArea = new JTextArea(10, 10);
footerPanel.add(orderTArea, BorderLayout.CENTER);
contentPane.add(headerPanel, BorderLayout.PAGE_START);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new PizzaLayout().displayGUI();
}
});
}
}
Here is the output of the same :

prevent GridBagLayout from resizing columns

Another problem with swing. How can I stop GridBagLayout from respacing components if one of them changes size? For example, I have few columns, in one of which there is a JLabel with text "text". When I change it to "texttext" layout manager resizes the whole column. I don't want it to do that. Is there any way to prevent it?
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ResizeIssue {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
It is visible while 9 -> 10 or anytime text changes width.
GridBagLayout ignores maximumWidth/Height. There's not an easy way to set the maximum size of the JLabel.
But, what I think you really want is the layout to not shift when the text in the JLabel changes.
That can be done by making the JLabel wide enough to hold the largest value it needs to display. For example:
jLabel1.setFont(new Font("monospace", Font.PLAIN, 12));
FontMetrics fm = jLabel1.getFontMetrics(jLabel1.getFont());
int w = fm.stringWidth("0000");
int h = fm.getHeight();
Dimension size = new Dimension(w, h);
jLabel1.setMinimumSize(size);
jLabel1.setPreferredSize(size);
Update:
To center the label text, just add:
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
This might work:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ResizeIssue2 {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
//*
c.gridy = 1;
int w = 32; //incButton.getPreferredSize().width;
for(c.gridx=0;c.gridx<3;c.gridx++) {
panel.add(Box.createHorizontalStrut(w), c);
}
// */
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}

Categories

Resources