This question already has answers here:
How to align JLabel-JTextField pairs vertically
(7 answers)
Arrange the Label with its respective field Swing
(6 answers)
Setting JLabels in rows and placing the equivalent JTextField right next to it
(2 answers)
Closed 5 years ago.
So I am supposed to make a very simple fillout form like name: ______, and they are supposed to be underneath each other , but when I add these JTextFields and JLabels to the JFrame I get an empty JFrame.
JFrame frame = new JFrame("Name's Item Orders Calculator");
JPanel panel = new JPanel();
BorderLayout layout = new BorderLayout(0,2);
JTextField nameField = new JTextField(15);
JTextField numberField = new JTextField(15);
JTextField costField = new JTextField(15);
JTextField amountField = new JTextField(15);
JLabel name = new JLabel("Item Name: ");
JLabel number = new JLabel("Number of: ");
JLabel cost = new JLabel("Cost: ");
JLabel amount = new JLabel("Amount owed: ");
panel.add(name, BorderLayout.WEST);
panel.add(number, BorderLayout.WEST);
panel.add(cost, BorderLayout.WEST);
panel.add(amount, BorderLayout.WEST);
panel.add(nameField, BorderLayout.EAST);
panel.add(numberField, BorderLayout.EAST);
panel.add(costField, BorderLayout.EAST);
panel.add(amountField, BorderLayout.EAST);
/*
panel.add(new JLabel("North"), BorderLayout.WEST);
panel.add(new JLabel("Another North"), BorderLayout.WEST);
*/
frame.pack();
frame.add(panel);
frame.setLayout(layout);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I am trying to create a simple menu interface with 4 rows of various buttons and labels using GridLayout with FlowLayout inside each grid for organising the elements. However the space for the buttons and labels which should only take 1 line takes up a huge amount of space.
This is what my interface looks like minimized:
This is what it looks like maximized:
I am looking to set the maximum size of the labels panels/grid so that it only takes a small amount of space.
I am trying to make all the elements visible without anything being hidden with as small a window size as possible like this:
This is my code:
public class Window extends JFrame{
public Window() {
super("TastyThai Menu Ordering");
}
public static void main(String[] args) {
Window w = new Window();
w.setSize(500, 500);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel title = new JLabel("TastyThai Menu Order", SwingConstants.CENTER);
title.setFont(title.getFont().deriveFont(32f));
//generate page title
Container titlePanel = new JPanel(); // used as a container
titlePanel.setBackground(Color.WHITE);
FlowLayout flow = new FlowLayout(); // Create a layout manager
titlePanel.setLayout(flow);// assign flow layout to panel
titlePanel.add(title); // add label to panel
w.getContentPane().add(BorderLayout.NORTH,titlePanel);
//generate row containers
Container r1 = new JPanel(new FlowLayout());
Container r2 = new JPanel(new FlowLayout());
Container r3 = new JPanel(new FlowLayout());
Container r4 = new JPanel(new FlowLayout());
//generate mains radio buttons
Container mains = new JPanel(new GridLayout(7, 0));
mains.setBackground(Color.RED);
JLabel mainsHeader = new JLabel("Mains");
mains.add(mainsHeader);
String[] mainsChoices = {"Vegetarian", "Chicken", "Beef", "Pork", "Duck", "Seafood Mix"};
JRadioButton[] mainsRadioButton = new JRadioButton[6];
ButtonGroup mainsButtons = new ButtonGroup();
for(int i = 0; i < mainsChoices.length; i++) {
mainsRadioButton[i] = new JRadioButton(mainsChoices[i]);
mains.add(mainsRadioButton[i]);
mainsButtons.add(mainsRadioButton[i]);
}
//generate noodles radio buttons
Container noodles = new JPanel(new GridLayout(7, 0));
noodles.setBackground(Color.GREEN);
JLabel noodlesHeader = new JLabel("Noodles");
noodlesHeader.setFont(noodlesHeader.getFont().deriveFont(24f));
noodles.add(noodlesHeader);
String[] noodlesChoices = {"Pad Thai", "Pad Siew", "Ba Mee"};
JRadioButton[] noodlesRadioButton = new JRadioButton[3];
ButtonGroup noodlesButtons = new ButtonGroup();
for(int i = 0; i < noodlesChoices.length; i++) {
noodlesRadioButton[i] = new JRadioButton(noodlesChoices[i]);
noodles.add(noodlesRadioButton[i]);
noodlesButtons.add(noodlesRadioButton[i]);
}
//generate sauces radio buttons
Container sauces = new JPanel(new GridLayout(7, 0));
sauces.setBackground(Color.BLUE);
JLabel saucesHeader = new JLabel("Sauce");
saucesHeader.setFont(saucesHeader.getFont().deriveFont(24f));
sauces.add(saucesHeader);
String[] saucesChoices = {"Soy Sauce", "Tamarind Sauce"};
JRadioButton[] saucesRadioButton = new JRadioButton[2];
ButtonGroup saucesButtons = new ButtonGroup();
for(int i = 0; i < saucesChoices.length; i++) {
saucesRadioButton[i] = new JRadioButton(saucesChoices[i]);
sauces.add(saucesRadioButton[i]);
saucesButtons.add(saucesRadioButton[i]);
}
//generate extras check boxes
Container extras = new JPanel(new GridLayout(7, 0));
extras.setBackground(Color.YELLOW);
JLabel extrasHeader = new JLabel("Extra");
extrasHeader.setFont(extrasHeader.getFont().deriveFont(24f));
extras.add(extrasHeader);
String[] extrasChoices = {"Mushroom", "Egg", "Broccoli", "Beansrpout", "Tofu"};
JCheckBox[] extrasBoxes = new JCheckBox[5];
for(int i = 0; i < extrasChoices.length; i++) {
extrasBoxes[i] = new JCheckBox(extrasChoices[i]);
extras.add(extrasBoxes[i]);
}
JLabel selectionPrice = new JLabel("Selection Price: $ ");
JLabel selectionPriceVal = new JLabel("_______________");
JButton addToOrder = new JButton("Add to Order");
JLabel totalPrice = new JLabel("Total Price: $ ");
JLabel totalPriceVal = new JLabel("_______________");
JButton clearOrder = new JButton("Clear Order");
JRadioButton pickUp = new JRadioButton("Pick Up");
JRadioButton delivery = new JRadioButton("Delivery");
ButtonGroup pickupDelivery = new ButtonGroup();
pickupDelivery.add(pickUp);
pickupDelivery.add(delivery);
JButton completeOrder = new JButton("Complete Order");
Container menuSelection = new JPanel(new GridLayout(4,0));
menuSelection.add(r1);
r1.add(mains);
r1.add(noodles);
r1.add(sauces);
r1.add(extras);
menuSelection.add(r2);
r2.add(selectionPrice);
r2.add(selectionPriceVal);
r2.add(addToOrder);
menuSelection.add(r3);
r3.add(totalPrice);
r3.add(totalPriceVal);
r3.add(clearOrder);
menuSelection.add(r4);
r4.add(pickUp);
r4.add(delivery);
r4.add(completeOrder);
w.getContentPane().add(BorderLayout.CENTER, menuSelection);
w.setVisible(true);
}
}
GridLayout does not support that. All rectangles have the same size.
Take a look at the GridBagLayout, which supports dynamic resizing and much more.
I have set of code that seems somewhat messy. I was wondering how to tidy it up
JPanel inventory = new JPanel();
JPanel options = new JPanel();
JPanel planet = new JPanel();
JPanel mainPanel = new JPanel();
JFrame mainFrame = new JFrame("Inventory");
inventTitle = new JLabel("Inventory");
inventMoney = new JLabel(" - " + money);
optTitle = new JLabel("Options");
opt1Label = new JLabel("Mine Ice -1 P, +100 M");
opt2Label = new JLabel("Heat Planet -500 M, +10T");
opt3Label = new JLabel("BLANK");
opt4Label = new JLabel("BLANK");
opt5Label = new JLabel("BLANK");
opt6Label = new JLabel("BLANK");
opt7Label = new JLabel("BLANK");
opt8Label = new JLabel("BLANK");
opt9Label = new JLabel("BLANK");
JButton opt1 = new JButton("1");
JButton opt2 = new JButton("2");
JButton opt3 = new JButton("3");
JButton opt4 = new JButton("4");
JButton opt5 = new JButton("5");
JButton opt6 = new JButton("6");
JButton opt7 = new JButton("7");
JButton opt8 = new JButton("8");
JButton opt9 = new JButton("9");
mainPanel.setLayout(null);
mainPanel.add(inventory);
mainPanel.add(options);
mainPanel.add(planet);
mainPanel.setOpaque(true);
mainPanel.setBackground(Color.WHITE);
inventory.setLayout(new BoxLayout(inventory, 1));
inventory.add(inventTitle);
inventory.setOpaque(true);
inventory.setBackground(Color.RED);
inventory.setBounds(0, 0, 360, 400);
inventory.add(inventMoney);
I saw somewhere a way of setting it like a method.
You can use a for loop instead of writing the same statements multiple times.
JLabel optLabel[] = new JLabel[9];
JButton opt[] = new JButton[9];
for (int i = 0; i < 9 ; i++) {
optLabel[i] = new JLabel ("BLANK");
opt[i] = new JButton (Integer.valueOf (i + 1).toString());
}
public class NewAccountApplet extends JApplet implements ActionListener{
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[6];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5 = new JPanel(new GridBagLayout()); //set jp5 as a new jpanel with gridbaglayout
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel(); //adds items[i] as JLabel
items[i].setText(itemText[i]); //sets text of items as itemText[]
jp5.add(items[i], firstCol); //adds items to firstcol of jp5
selectQty[i] = new JComboBox<Object>(); //JComboBox selectqty[i]
selectQty[i].setPreferredSize(new Dimension(300, 20)); //sets the size
jp5.add(selectQty[i], lastCol); //sadsdasd
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
I have some questions regarding adding a JComboBox into a loop to display on my JApplet.
the for loop on the bottom adds my JComboBox (selectQty) to the screen. But I get an error message on eclipse where i coded as: items[i].setText(itemText[i]);.
It shows up my JPanel jp4 correctly. but the JPanel jp5 is not showing up.. I wonder what is wrong...
So to summarize, the code compiles (with other codes that are not on here), but japplet only shows jp4 jpanel, and error occrs on line: items[i].setText(itemText[i]);.
itemText has 5 elements {"1", "2", "3", "4", "5"} but JLabel[] items = new JLabel[6] items has 6.
You appear to be re-creating jp5 but neither removing the old instance or adding the new instance...
// This suggests that jp5 has already been created
jp5.setVisible(true);
//...
// But you create a new instance here
jp5 = new JPanel(new GridBagLayout());
// Then add stuff to it...
Try using jp5.removeAll() instead of jp5 = new JPanel(new GridBagLayout());
The likely cause of your error is probably IndexOutOfBoundsException caused by the fact the itemText and items have different numbers of elements
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[6];
//...
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel(); //adds items[i] as JLabel
// Error here on the last element...
items[i].setText(itemText[i]); //sets text of items as itemText[]
Instead, consider using something like...
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[itemText.length];
And remember, magic numbers are a bad idea
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.*;
public class NewAccountApplet extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
String[] accountlist = {"Select Account Type.", "Customer", "Admin"};
JComboBox<Object> textAlignment = new JComboBox<Object>(accountlist);
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Name","Account ID","Password","E-Mail","Phone","Address","","","Account Type"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[9];
jtf = new JTextField[9];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
jp4 = new JPanel();
jp5 = new JPanel();
jp6 = new JPanel();
for(int i=0; (i<9); i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
String id = this.jtf[1].getText();
String pw = this.jtf[2].getText();
jtf[6].setText(id);
jtf[7].setText(pw);
jtf[6].setVisible(false);
jtf[7].setVisible(false);
jtf[8].setVisible(false);
jp2.add(textAlignment, lastCol);
decline.addActionListener(this);
accept.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String id = jtf[1].getText();
String pw = jtf[2].getText();
String checkID = jtf[6].getText();
String checkPW = jtf[7].getText();
String accountType = "";
String correctType = "Customer";
String chosenType = (String) textAlignment.getSelectedItem();
JPasswordField pField = new JPasswordField(10);
JPanel pPanel = new JPanel();
pPanel.add(new JLabel("Please Enter Password: "));
pPanel.add(pField);
if (e.getActionCommand().equals("Create") && (chosenType.equals("Customer"))){
JOptionPane.showMessageDialog(null, "Thank you for Joining!");
id = jtf[1].getText();
pw = jtf[2].getText();
titlePage.setText("Welcome to Final Sales!");
accept.setText("Login");
decline.setText("Cancel");
txt[6].setText("UserName");
txt[7].setText("Password");
jtf[0].setText("");
jtf[3].setText("");
jtf[4].setText("");
jtf[5].setText("");
txt[0].setVisible(false);
txt[1].setVisible(false);
txt[2].setVisible(false);
txt[3].setVisible(false);
txt[4].setVisible(false);
txt[5].setVisible(false);
textAlignment.setVisible(false);
txt[8].setVisible(false);
jtf[0].setVisible(false);
jtf[1].setVisible(false);
jtf[2].setVisible(false);
jtf[3].setVisible(false);
jtf[4].setVisible(false);
jtf[5].setVisible(false);
jtf[6].setVisible(true);
jtf[7].setVisible(true);
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Admin"))) {
JOptionPane.showMessageDialog(null, pPanel);
JOptionPane.showMessageDialog(null, "Wrong Admin Password");
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Select Account Type."))) {
JOptionPane.showMessageDialog(null, "You have selected wrong account type.");
}
if (e.getActionCommand().equals("Decline"))
System.exit(0);
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"White Snapback", "Silver Necklace", "Black T Shirt", "", "5"};
JLabel[] items = new JLabel[5];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5.setLayout(new GridBagLayout());
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel();
items[i].setText(itemText[i]);
jp5.add(items[i], firstCol);
selectQty[i] = new JComboBox<Object>();
selectQty[i].setPreferredSize(new Dimension(300, 20));
jp5.add(selectQty[i], lastCol);
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
if (e.getActionCommand().equals("Cancel")) {
System.exit(0);}
}
}
I have one tab that needs to update using one of two methods in it's class while the program is running, for that reason I'm adding components inside the methods, and I cannot get any of them to display. As far as I can tell it's because they are outside the constructor, I used to declare them all inside the methods but moved it to try and fix the problem. Any help would be greatly appreciated.
I apologise it's a bit messy, I've been trying to fix the problem, a bit blindly.
Also the code compiles fine, and println outputs in code display as expected.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package assgui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
/**
*
* #author Hugh
*/
public class ResultPanel extends JPanel {
static String[][] activityString = new String[31][2];
static String[][] foodString = new String[36][2];
String weighstr, foodstr, servstr, kjstr, actstr, hourstr, minstr, metstr;
JLabel uw = new JLabel ("User Weight: ");
JLabel weigh = new JLabel (weighstr);
JLabel kg = new JLabel(" kg");
JLabel sel1 = new JLabel("Food: ");
JLabel sel2 = new JLabel(foodstr);
JLabel sel3 = new JLabel(" - kj ");
JLabel sel4 = new JLabel(kjstr);
JLabel sel5 = new JLabel(" , Servings: ");
JLabel sel6 = new JLabel(servstr);
JLabel sel7 = new JLabel("Activity for comparison: ");
JLabel sel8 = new JLabel(actstr);
JLabel sel9 = new JLabel(" Time required to balance: ");
JLabel sel10 = new JLabel(hourstr);
JLabel sel11 = new JLabel(" hours");
JLabel sel12 = new JLabel(minstr);
JLabel sel13 = new JLabel(" minutes");
JLabel smlspace = new JLabel(" ");
JLabel medspace = new JLabel(" ");
JLabel lrgspace = new JLabel(" ");
JLabel auw = new JLabel("User Weight: ");
JLabel aweigh = new JLabel(weighstr);
JLabel akg = new JLabel(" kg");
JLabel asel1 = new JLabel("Activity: ");
JLabel asel2 = new JLabel(actstr);
JLabel asel3 = new JLabel(" - MET ");
JLabel asel4 = new JLabel(metstr);
JLabel asel5 = new JLabel(" , Duration: ");
JLabel asel6 = new JLabel(hourstr);
JLabel asel7 = new JLabel(" hour ");
JLabel asel8 = new JLabel(minstr);
JLabel asel9 = new JLabel(" minutes ");
JLabel asel10 = new JLabel("Food for comparison: ");
JLabel asel11 = new JLabel(foodstr);
JLabel asel12 = new JLabel(" Servings to balance: ");
JLabel asel13 = new JLabel(servstr);
JLabel asmlspace = new JLabel(" ");
JLabel amedspace = new JLabel(" ");
JLabel alrgspace = new JLabel(" ");
Public ResultPanel() {
setBackground(Color.GREEN);
setPreferredSize(new Dimension(650, 600));
{
public void activityPaint (String[][] actstring, String[][] foodstring, double weight, int activity, int hour, int min, int food, double servings) {
System.out.println("act1");
weighstr = Double.toString(weight);
actstr = activityString[activity][0];
hourstr = Integer.toString(hour);
minstr = Integer.toString(min);
metstr = activityString[activity][1];
foodstr = foodString[food][0];
servstr = Double.toString(servings);
add(lrgspace);
add(uw);
add(weigh);
add(kg);
add(medspace);
add(sel1);
add(sel2);
add(sel3);
add(sel4);
add(sel5);
add(sel6);
add(sel7);
add(sel8);
add(sel9);
add(sel10);
add(sel11);
add(sel12);
add(sel13);
}
public void foodPaint(String[][] foodstring, String[][] actstring, double weight, int food, int servings, int activity, int hour, int min) {
System.out.println("food1");
weighstr = Double.toString(weight);
foodstr = foodString[food][0];
servstr = Integer.toString(servings);
kjstr = foodString[food][1];
actstr = activityString[activity][0];
hourstr = Integer.toString(hour);
minstr = Integer.toString(min);
add(lrgspace);
add(uw);
add(weigh);
add(kg);
add(medspace);
add(sel1);
add(sel2);
add(sel3);
add(sel4);
add(sel5);
add(sel6);
add(sel7);
add(sel8);
add(sel9);
add(sel10);
add(sel11);
add(sel12);
add(sel13);
}
}
Does your main method (or whatever method) that creates this JPanel also call the activityPaint(...) and foodPaint(...) methods? If those methods are not called then they will never be added to the panel it seems. If you want everything to be added when you create the JPanel then you must have your constructor call activityPaint() and foodPaint().
If the values of your JLables can't be set until something else occurs (like user input), then you can add the components when the JPanel is created and then later call the setText(...) method. Just be sure if you do that to also set the size since changing the text will effect that. I prefer to use nameofjpanel.setSize(nameofjpanel.getPreferredSize()).
Hope this helps you and I didn't completely miss what you're going for here.