Nesting FlowLayout Panels - java

I'm trying to create a GUI using JAVA for a BMR calculator.
I'm having some problems with getting the GUI right so I have been experimenting with different layout managers/nesting Jpanels.
My current code has an age and gender label, both contained in separate JPanels in a flow layout, but the problem is that they appear next to eachother rather than on seperate lines as I want them to.
How can I acheive this with my code? My current laoyut is as below, I want Gender to be below age, and have been playing with this for some time but can't get it to work.
Cheers.
package v2;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.FlowLayout;
public class BmrCalcv2 extends JFrame {
static JFrame mainFrame;
static JPanel mainPanel;
static JMenuBar menuBar;
static JMenu fileMenu, editMenu;
static JPanel agePanel;
private JLabel ageLabel;
private JTextField ageTextField;
static JPanel genderPanel;
private JLabel genderLabel;
public BmrCalcv2() {
// Main JFrame
mainFrame = new JFrame("BMR/TDEE Calculator");
mainPanel = new JPanel();
// All JPanel declarations
menuBar = new JMenuBar();
agePanel = new JPanel();
genderPanel = new JPanel();
// JPanel layout managers
agePanel.setLayout(new FlowLayout(10));
genderPanel.setLayout(new FlowLayout(10));
// Menu JPanel
fileMenu = new JMenu("File");
editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
// Age JPanel
ageLabel = new JLabel("Age:");
ageTextField = new JTextField(5);
agePanel.add(ageLabel);
agePanel.add(ageTextField);
// Gender JPanel
genderLabel = new JLabel("Gender:");
genderPanel.add(genderLabel);
// Adding sub JPanels to main JPanel
mainPanel.add(agePanel);
mainPanel.add(genderPanel);
// Adding main JPanel/menubar to JFrame
mainFrame.setJMenuBar(menuBar);
mainFrame.add(mainPanel);
}
public static void main(String[] args) {
BmrCalcv2 frame = new BmrCalcv2();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setSize(330, 300);;
mainFrame.setResizable(false);
}
}

If you don't care about alignment:
mainFrame.getContentPane().setLayout(new BoxLayout(mainFrame.getContentPane(), BoxLayout.X_AXIS));
// quick pseudocode incoming
for(int x = 0; x < components.size(); x++) {
JPanel j = new JPanel();
j.setLayout(new FlowLayout(FlowLayout.CENTER)); // I think CENTER is the default anyhow
j.add(getLabel(x));
j.add(getField(x));
mainFrame.add(j);
}
If you care about alignment, swap the FlowLayout for a BoxLayout along the Y_AXIS and put some horizontal glue between the label and the input field(s).

Something like this should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class GridBagLayoutExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("BMI Calculator");
// create the gui elements
JLabel ageLabel = new JLabel("Age:");
JTextField ageTxt = new JTextField(20);
JLabel genderLabel = new JLabel("Gender:");
JTextField genderTxt = new JTextField(20);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.HORIZONTAL;
// age label
cons.gridx = 0;
cons.gridy = 0;
pan.add(ageLabel, cons);
// age text
cons.gridx = 1;
cons.gridy = 0;
pan.add(ageTxt, cons);
// gender label
cons.gridx = 0;
cons.gridy = 1;
pan.add(genderLabel, cons);
// gender text
cons.gridx = 1;
cons.gridy = 1;
pan.add(genderTxt, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 200);
jframe.setVisible(true);
}
}
Looks like this:

Related

How to control where in my window or JFrame panels appear

this has seriously been the biggest issue in my code. I just want to create a simple pizza order taker using multiple panels. I want to be able to dictate the specific area each panel is located. Can someone please just pretend I'm a complete idiot and help me point this out?
I've attached my code as well as an image of how it looks so far. I want to be able to place individual segments like getting the user's information, choosing pizza size, then toppings, then a section where I will display the receipt with all of the order total.
I can do the calculations and take in values, I just need to figure out the appearance.
import javax.swing.*;
import java.awt.*;
public class PIZZA extends JFrame {
Container window = getContentPane();
ButtonGroup ordertype;
JRadioButton delivery, takeout;
JRadioButton small, medium, large;
JLabel fname, phonenum, zipcode;
JTextField ufname, uphonenum, uzipcode;
JPanel userinfoinput;
JPanel delivery_type;
JPanel userinfolabel;
JButton start;
BoxLayout userbox, labelbox, deliverybox;
ImageIcon starticon = new ImageIcon("start.png");
public PIZZA() {
}
public static void main(String[] args){
PIZZA frame = new PIZZA();
new PIZZA();
frame.setSize(new Dimension(600,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("KRUSTY KRAB PIZZA");
frame.deliverymethod();
frame.getuserinfo();
frame.userinfolabels();
frame.getpizzasize();
frame.toppings_meat();
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
private void deliverymethod(){
delivery_type = new JPanel();
ordertype = new ButtonGroup();
delivery = new JRadioButton("Delivery (Currently Unavailable)");
delivery.setEnabled(false);
takeout = new JRadioButton("Take Out");
ordertype.add(takeout);
ordertype.add(delivery);
delivery_type.add(takeout);
delivery_type.add(delivery);
delivery_type.setSize(100,100);
window.add(delivery_type,BorderLayout.NORTH);
}
private void getuserinfo(){
userinfoinput = new JPanel();
//start = new JButton("Start", starticon);
//start.setLayout(null);
ufname = new JTextField(12);
uphonenum = new JTextField(12);
uzipcode = new JTextField(12);
userinfoinput.add(ufname);
userinfoinput.add(uphonenum);
userinfoinput.add(uzipcode);
//userinfoinput.add(start);
GridLayout lay = new GridLayout(3,1);
userinfoinput.setLayout(lay);
window.add(userinfoinput, BorderLayout.CENTER);
}
private void userinfolabels(){
userinfolabel = new JPanel();
fname = new JLabel("First Name");
phonenum = new JLabel("Phone Number");
zipcode = new JLabel("Zip Code");
userinfolabel.add(fname);
userinfolabel.add(zipcode);
userinfolabel.add(phonenum);
labelbox = new BoxLayout(userinfolabel, BoxLayout.Y_AXIS);
GridLayout label = new GridLayout(3,1);
userinfolabel.setLayout(label);
window.add(userinfolabel, BorderLayout.CENTER);
}
private void getpizzasize(){
JPanel pizzasize = new JPanel();
ButtonGroup size = new ButtonGroup();
small = new JRadioButton("Small");
medium = new JRadioButton("Medium");
large = new JRadioButton("Large");
size.add(small);
size.add(medium);
size.add(large);
pizzasize.add(small);
pizzasize.add(medium);
pizzasize.add(large);
pizzasize.setLayout(new FlowLayout());
pizzasize.setSize(100,100);
window.add(pizzasize, BorderLayout.SOUTH);
}
private void toppings_meat(){
JPanel meat = new JPanel();
meat.setLayout(new BoxLayout(meat, BoxLayout.Y_AXIS));
JCheckBox pepperoni = new JCheckBox("Pepperoni");
JCheckBox meatball = new JCheckBox("Meatball");
JCheckBox chicken = new JCheckBox("Grilled Chicken");
JCheckBox sausage = new JCheckBox("Italian Sausage");
JCheckBox bacon = new JCheckBox("Bacon");
meat.add(pepperoni);
meat.add(meatball);
meat.add(chicken);
meat.add(sausage);
meat.add(bacon);
window.add(meat);
}
}
This pizza GUI uses several Swing layout managers in different JPanels.
The main layout managers that I want to talk about are the JFrame BorderLayout and the input form GridBagLayout.
A BorderLayout is rather flexible in that you can put Swing components in various locations. The JPanels I created for this GUI are in the BEFORE_FIRST_LINE, CENTER, AFTER_LAST_LINE, and AFTER_LINE_ENDS positions of the BorderLayout.
The input form uses a GridBagLayout to position the JLabels and the input JTextFields in a column. The GridBagLayout is more flexible than a GridLayout because the grid cells don't have to be the same size in a GridBagLayout.
The Oracle Swing tutorial A Visual Guide to Layout Managers shows the different Swin layout managers, and how to use them.
Here's the code I used to create the pizza GUI. I created each subordinate JPanel in a separate method. All of the JFrame code is in the run method. Separating different parts of the GUI allows me to focus on one part of the GUI at a time. I can test each JPanel method separately.
I create the Swing components from left to right, top to bottom within a JPanel. This allows me to visually verify that I've included all the appropriate methods for a component. This also allows me to zero in on any component that isn't correct.
import java.awt.BorderLayout;
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.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PizzaOrdering implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PizzaOrdering());
}
#Override
public void run() {
JFrame frame = new JFrame("KRUSTY KRAB PIZZA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getDeliveryMethodPanel(),
BorderLayout.BEFORE_FIRST_LINE);
frame.add(getUserInformationPanel(),
BorderLayout.CENTER);
frame.add(getPizzaSizePanel(),
BorderLayout.AFTER_LAST_LINE);
frame.add(getMeatToppingsPanel(),
BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getDeliveryMethodPanel() {
JPanel deliveryMethodPanel = new JPanel(new FlowLayout());
ButtonGroup orderTypeGroup = new ButtonGroup();
JRadioButton takeoutRadioButton =
new JRadioButton("Take Out");
orderTypeGroup.add(takeoutRadioButton);
deliveryMethodPanel.add(takeoutRadioButton);
JRadioButton deliveryRadioButton =
new JRadioButton("Delivery (Currently Unavailable)");
deliveryRadioButton.setEnabled(false);
orderTypeGroup.add(deliveryRadioButton);
deliveryMethodPanel.add(deliveryRadioButton);
return deliveryMethodPanel;
}
private JPanel getUserInformationPanel() {
JPanel userInformationPanel = new JPanel(new GridBagLayout());
userInformationPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1d;
JLabel nameLabel = new JLabel("First Name:");
userInformationPanel.add(nameLabel, gbc);
gbc.gridx++;
JTextField userNameField = new JTextField(20);
userInformationPanel.add(userNameField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel phoneNumberLabel = new JLabel("Phone Number:");
userInformationPanel.add(phoneNumberLabel, gbc);
gbc.gridx++;
JTextField userPhoneNumberField = new JTextField(20);
userInformationPanel.add(userPhoneNumberField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel zipCodeLabel = new JLabel("Zip Code:");
userInformationPanel.add(zipCodeLabel, gbc);
gbc.gridx++;
JTextField userZipCodeField = new JTextField(20);
userInformationPanel.add(userZipCodeField, gbc);
return userInformationPanel;
}
private JPanel getPizzaSizePanel() {
JPanel pizzaSizePanel = new JPanel(new FlowLayout());
ButtonGroup sizeGroup = new ButtonGroup();
JRadioButton smallRadioButton = new JRadioButton("Small");
sizeGroup.add(smallRadioButton);
pizzaSizePanel.add(smallRadioButton);
JRadioButton mediumRadioButton = new JRadioButton("Medium");
sizeGroup.add(mediumRadioButton);
pizzaSizePanel.add(mediumRadioButton);
JRadioButton largeRadioButton = new JRadioButton("Large");
sizeGroup.add(largeRadioButton);
pizzaSizePanel.add(largeRadioButton);
return pizzaSizePanel;
}
private JPanel getMeatToppingsPanel() {
JPanel meatToppingsPanel = new JPanel();
meatToppingsPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
meatToppingsPanel.setLayout(new BoxLayout(
meatToppingsPanel, BoxLayout.Y_AXIS));
JCheckBox pepperoniCheckBox = new JCheckBox("Pepperoni");
meatToppingsPanel.add(pepperoniCheckBox);
JCheckBox meatballCheckBox = new JCheckBox("Meatball");
meatToppingsPanel.add(meatballCheckBox);
JCheckBox chickenCheckBox = new JCheckBox("Grilled Chicken");
meatToppingsPanel.add(chickenCheckBox);
JCheckBox sausageCheckBox = new JCheckBox("Italian Sausage");
meatToppingsPanel.add(sausageCheckBox);
JCheckBox baconCheckBox = new JCheckBox("Bacon");
meatToppingsPanel.add(baconCheckBox);
return meatToppingsPanel;
}
}

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

Adding an action listener to JButtons created by a loop

I am having trouble finding a way to invoke an action listener that returns the value of the button clicked in the text area at the bottom.
I made the buttons using a for loop and did not expressly give the buttons a name so I do not know how to reference them when trying to incorporate an ActionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
buttonGrid.add(new JButton(val));
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}
I created an action listener to put the value in the text area at the bottom of the GUI.
I fixed a few problems with your code.
In the main method, I called the SwingUtilities invokeLater method to put the Swing GUI on the Event Dispatch thread (EDT). Swing components must be created and updated on the EDT.
The name of a Java class must start with a capital letter.
It's safer to put your Swing components on a JPanel, rather than add them directly to a JFrame.
I separated the code that creates the JFrame from the code that creates the JPanels. It should be easier for any reader of your code, including yourself, to understand what's going on.
In the createMainPanel method, I grouped the code so that everything having to do with the buttonGrid JPanel, to take one instance, is in one place in the code.
I added the action listener to the code that creates the buttonGrid JPanel.
I wrote action listener code that updates the JTextArea with the left clicked button label.
Here's the corrected code.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Buttoner implements ActionListener {
// JFrame
private JFrame frame = new JFrame("Button Game");
// Make JPanels
private JPanel panelLabel = new JPanel();
private JPanel buttonGrid = new JPanel(new GridLayout(0, 10));
private JPanel bottomPanel = new JPanel();
// JLabel
private JLabel label1 = new JLabel("The Button Game");
private JTextArea jta;
public Buttoner() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Change label color
label1.setForeground(Color.RED);
// add Label
panelLabel.add(label1);
panel.add(panelLabel, BorderLayout.NORTH);
// add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton button = new JButton(val);
button.addActionListener(this);
buttonGrid.add(button);
}
panel.add(buttonGrid, BorderLayout.CENTER);
// Add JText Area to bottom JPanel
String num = "value";
jta = new JTextArea(num, 1, 1);
jta.setEditable(false);
bottomPanel.add(jta);
panel.add(bottomPanel, BorderLayout.SOUTH);
return panel;
}
public static void main(String args[]) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new Buttoner();
}
};
SwingUtilities.invokeLater(runnable);
}
public void actionPerformed(ActionEvent a) {
JButton button = (JButton) a.getSource();
jta.setText(button.getText());
}
}
Try creating an array of buttons and add the newly created button to the array. See comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
private JButton buttons[] = new JButton[60]; //create an array of button for future reference
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton btn = new JButton(val);
btn.addActionListener(this); //add an actionListener right away
buttons[i] = btn; //add the button in the array for future reference
buttonGrid.add(btn);
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}

setVgap(0), setHgap(0) not working in gridlayout?

I am trying to build an app that has some components such as buttons, labels, text fields, a menu bar and a picture (I didn't tackle the image problem yet so there is no code for that).
So I made a grid layout for my frame and constructed 6 panels with their respective components as explained in the code bellow. But when I run it it doesn't show anything at first, just a blank frame, unless I maximize the window. Because when I do that everything appears to be working fine. Except for 2 things.
I have setVgap() and setHgap() to zero but there are still gaps between the components. and the 2nd thing is that the BorderLayout.NORTH, (..).SOUTH etc don't seem to work either.
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel menupanel = new JPanel();
public Window() {
super("Image Application");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
requestFocus();
// Setting Layout
GridLayout grid = new GridLayout(6, 0, 0, 0);
//grid.setVgap(0);
//grid.setHgap(0);
this.setLayout(grid);
// Menu
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Options");
JButton button = new JButton("Reset");
// Buttons
menupanel.add(new JButton("Allign Left"));
menupanel.add(new JButton("Allign Center"));
menupanel.add(new JButton("Allign Right"));
// Picture
JPanel p1 = new JPanel();
// 2x JLabels and ComboBoxes to get the preferred dimensions
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JLabel b2 = new JLabel("Width: ");
JLabel b3 = new JLabel("Height: ");
JTextField box1 = new JTextField(25);
JTextField box2 = new JTextField(25);
// Resize Button
JPanel p4 = new JPanel();
JButton b4 = new JButton("Resize");
// Adding Components to their panels
p2.add(b2);
p2.add(box1);
p3.add(b3);
p3.add(box2);
p4.add(b4);
menu.add(button);
menubar.add(menu);
// add all of the panels to JFrame
this.add(menupanel);
this.add(p1, BorderLayout.NORTH);
this.add(p2, BorderLayout.SOUTH);
this.add(p3, BorderLayout.WEST);
this.add(p4, BorderLayout.EAST);
this.setJMenuBar(menubar);
pack();
setVisible(true);
}
public static void main(String args[]) {
Window w = new Window();
}
}
Any ideas?
~EDIT1 changed according to first 2 comments, the pack(); seems to fix the problem that i needed to maximise the window to see the comp's ( -Thanks ), but the setVgap() problem remains.
~EDIT2 when I run it this window is shown:
While I want it to look more like this:
AGAIN Ignore the picture
~EDIT3 Well, I changed the value that was passed in the constructor for the Hgap and it does change accordingly for different values but it seems that zero Hgap is still ~10 pixels wide?! Also I noted that the gap doesn't change between the menubar and the first Jbuttons, but only for the ret of the components.
~EDIT4 It also works for negative int's..?! I am lost here..
please to compare, you should using second parameter for GridLayout, then setVgap() will works (frame.setLayout(new GridLayout(6, 0, 5, 5));), here is only zero value,
Window is reserved word in Java for awt.Window, don't to use this Object name as class name
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyWindow {
private static final long serialVersionUID = 1L;
private JPanel menupanel = new JPanel();
private JFrame frame = new JFrame("Image Application");
public MyWindow() {
// Menu
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Options");
JButton button = new JButton("Reset");
// Buttons
menupanel.add(new JButton("Allign Left"));
menupanel.add(new JButton("Allign Center"));
menupanel.add(new JButton("Allign Right"));
// Picture
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
// 2x JLabels and ComboBoxes to get the preferred dimensions
JPanel p2 = new JPanel();
p2.setBackground(Color.ORANGE);
JLabel b2 = new JLabel("Width: ");
p2.add(b2);
JTextField box1 = new JTextField(25);
p2.add(box1);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
JLabel b3 = new JLabel("Height: ");
JTextField box2 = new JTextField(25);
p3.add(b3);
p3.add(box2);
// Resize Button
JPanel p4 = new JPanel();
p4.setBackground(Color.MAGENTA);
JButton b4 = new JButton("Resize");
// Adding Components to their panels
p4.add(b4);
menu.add(button);
menubar.add(menu);
// add all of the panels to JFrame
frame.setLayout(new GridLayout(6, 0, 5, 5));
frame.add(menupanel);
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.add(p4);
frame.setJMenuBar(menubar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyWindow w = new MyWindow();
}
});
}
}

Java: How do I change the order of my JLabels in a 2x2 GridLayout?

I have a problem in that I'm trying to get my program to print out one particular JPanel as a 2x2 GridLayout with Icons of playing cards on top, and text indicating which player's card is it on bottom, but no matter what I do, the result is reverse, like so. I have tried changing the order in which I add the elements to no avail.
CardTable myCardTable
= new CardTable("CS 1B CardTable", NUM_CARDS_PER_HAND, NUM_PLAYERS);
myCardTable.setSize(800, 600);
myCardTable.setLocationRelativeTo(null);
myCardTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// show everything to the user
myCardTable.setVisible(true);
myCardTable.getGamePanel().setBorder(new TitledBorder("Playing Area"));
myCardTable.getGamePanel().add(playerCard, JLabel.CENTER);
myCardTable.getGamePanel().add(computerCard, JLabel.CENTER);
for(int i = 0; i < NUM_PLAYERS; i++)
{
JLabel temp = new JLabel(GUICard.getIcon(generateRandomCard()));
myCardTable.getGamePanel().add(temp);
}
Below is the constructor of the class that I made, CardTable, that extends JFrame.
static int MAX_CARDS_PER_HAND = 57;
static int MAX_PLAYERS = 2; // for now, we only allow 2 person games
private int numCardsPerHand;
private int numPlayers;
private JPanel computerPanel, playerPanel, gamePanel;
public CardTable(String title, int numCardsPerHand, int numPlayers)
{
super(title);
setComputerPanel(new JPanel(new GridLayout(1 , numCardsPerHand)));
setPlayerPanel(new JPanel(new GridLayout(1 , numCardsPerHand)));
setGamePanel(new JPanel(new GridLayout(2 , numPlayers)));
setLayout (new BorderLayout(20, 10));
add(getComputerPanel(), BorderLayout.NORTH );
add(getGamePanel(), BorderLayout.CENTER);
add(getPlayerPanel(), BorderLayout.SOUTH);
}
"GridLayout with Icons of playing cards on top, and text indicating which player's card is it on bottom,"
You can put text and an icon in the same label and just set the text positions with setXxxTextPosition(). Maybe you'd prefer this. IMO it looks much cleaner than separating the icon and text so far apart from each other.
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class PlayerCard {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ImageIcon playerIcon = new ImageIcon(getClass().getResource("/resources/1.png"));
ImageIcon compIcon = new ImageIcon(getClass().getResource("/resources/14.png"));
JLabel playerLabel = new JLabel(playerIcon);
JLabel compLabel = new JLabel(compIcon);
playerLabel.setText("Player Card");
compLabel.setText("Computer Card");
playerLabel.setVerticalTextPosition(JLabel.BOTTOM);
compLabel.setVerticalTextPosition(JLabel.BOTTOM);
playerLabel.setHorizontalTextPosition(JLabel.CENTER);
compLabel.setHorizontalTextPosition(JLabel.CENTER);
JPanel playerPanel = new JPanel();
playerPanel.setBorder(new TitledBorder("Player"));
playerPanel.add(playerLabel);
JPanel compPanel = new JPanel();
compPanel.setBorder(new TitledBorder("Computer"));
compPanel.add(compLabel);
JPanel panel = new JPanel();
panel.add(playerPanel);
panel.add(compPanel);
JOptionPane.showMessageDialog(null, panel);
}
});
}
}
UPDATE
If you really must stick with the GridLayout, you need to make sure to add the cards first, then add the text labels.
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PlayerCard {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ImageIcon playerIcon = new ImageIcon(getClass().getResource("/resources/1.png"));
ImageIcon compIcon = new ImageIcon(getClass().getResource("/resources/14.png"));
JLabel playerLabel = new JLabel(playerIcon);
JLabel compLabel = new JLabel(compIcon);
JLabel playerText = new JLabel("Player Card");
JLabel compText = new JLabel("Computer Card");
playerLabel.setHorizontalAlignment(JLabel.CENTER);
compLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel playerCardPanel = new JPanel();
playerCardPanel.add(playerLabel);
JPanel compCardPanel = new JPanel();
compCardPanel.add(compLabel);
JPanel panel = new JPanel(new GridLayout(2, 2));
panel.add(playerCardPanel);
panel.add(compCardPanel);
panel.add(playerText);
panel.add(compText);
JOptionPane.showMessageDialog(null, panel);
}
});
}
}

Categories

Resources