I'm hoping this is an easy question. I have a JComboBox with the choices of 0, 1, 2, 3,...10. Depending on what number is selected in the JComboBox, I want my GUI to add a JLabel and a JTextField. So if the number 3 is chosen, the GUI should add 3 JLabels and 3 JTextFields. and so forth.
I'm using an array of JLabels and JTextFields to accomplish this, but I am getting a null pointer exception at runtime, and no labels or fields are being added.
Code:
private void createComponents()
{
//Create Action Listeners
ActionListener comboListener = new ComboListener();
//Create Components of the GUI
parseButton = new JButton("Parse Files");
parseButton.addActionListener(comboListener);
numberLabel = new JLabel("Number of Files to Parse: ");
String[] comboStrings = { "","1", "2","3","4","5","6","7","8","9","10" };
inputBox = new JComboBox(comboStrings);
inputBox.setSelectedIndex(0);
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(2,10));
centerPanel = new JPanel();
centerPanel.add(numberLabel);
centerPanel.add(inputBox);
totalGUI = new JPanel();
totalGUI.setLayout(new BorderLayout());
totalGUI.add(parseButton, BorderLayout.SOUTH);
totalGUI.add(centerPanel, BorderLayout.CENTER);
add(totalGUI);
}
ActionListener Code:
public void actionPerformed(ActionEvent e)
{
JTextField[] fileField = new JTextField[inputBox.getSelectedIndex()];
JLabel[] fieldLabel = new JLabel[inputBox.getSelectedIndex()];
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i].setText("File "+i+":"); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fieldLabel[i]); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fileField[i]);
}
centerPanel.add(fieldPanel);
repaint();
revalidate();
}
Thanks to MadProgrammer's comment, this question has been answered.
Editing the loop to:
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i] = new JLabel();
fileField[i] = new JTextField();
fieldLabel[i].setText("File "+i+":");
fieldPanel.add(fieldLabel[i]);
fieldPanel.add(fileField[i]);
}
resolved the issue.
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 am trying to create GUI like given in first picture, but I am not able to do it.here is the image
I am getting only one combo1, combo2, combo3 and serialNoLabel instead of 5 [5 is the size of list]
ArrayList<String> list; // the size of the list is 5
JComboBox combo1[] = new JComboBox[list.size()];
JComboBox combo2[] = new JComboBox[list.size()];
JComboBox combo3[] = new JComboBox[list.size()];
JLabel SerialNoLabel[] = new JLabel[list.size()];
JPanel masterPanel[] = new JPanel[list.size()];
JDialog masterDialog = new JDialog();
masterDialog.setVisible(true);
masterDialog.setSize(800, 500);
masterDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
masterDialog.setVisible(true);
for(int j =0; j < list.size(); j++) {
masterPanel[j] = new JPanel();
SerialNoLabel[j] = new JLabel(list.get(j));
masterPanel[j].add(SerialNoLabel[j]);
combo1[j] = new JComboBox();
masterPanel[j].add(combo1[j]);
combo2[j] = new JComboBox();
masterPanel[j].add(combo2[j]);
combo3[j] = new JComboBox();
masterPanel[j].add(combo3[j]);
masterDialog.add(masterPanel[j]);
masterDialog.revalidate();
}
I believe it's a layout issue leading your masterPanels to be on top of each other.
So I would do something like this:
JPanel mainPanel = new JPanel();
FlowLayout experimentLayout = new FlowLayout();
mainPanel.setLayout(experimentLayout);
for(int j =0; j < list.size(); j++) {
masterPanel[j] = new JPanel();
SerialNoLabel[j] = new JLabel(list.get(j));
masterPanel[j].add(SerialNoLabel[j]);
combo1[j] = new JComboBox();
masterPanel[j].add(combo1[j]);
combo2[j] = new JComboBox();
masterPanel[j].add(combo2[j]);
combo3[j] = new JComboBox();
mainPanel.add(masterPanel[j]);
}
Of course you could other layouts as well. But I believe you want to go for a FlowLayout. See the documentation about FlowLayout here.
You can learn more about other layouts here
I need help changing the size of my TextField. I have a JScrollPane at the beginning of my panel (Which is big so I can read more data), then I have a JLabel for instructions and in the end I would like to add a JTextArea which I only need a row for entering a number. The problem is that the elements are quite big in the panel.
I attach the result:
Here is my code:
public static void delete()
{
int deletePosition;
String[] options = {"Confirm", "Cancel"};
JPanel panel = new JPanel();
JLabel label0 = new JLabel("Write the Position[#]:");
JLabel labelJump1 = new JLabel("");
JTextField txtDelete = new JTextField(1);
GridLayout gridLayout = new GridLayout(0,1);
panel.setLayout(gridLayout);
String fullText = "";
JTextArea textArea = new JTextArea(15,30);
textArea.setText(fullText);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane);
panel.add(label0);
panel.add(labelJump1);
panel.add(txtDelete);
try
{
if (theEntityCollection.checkEmpty())
JOptionPane.showMessageDialog(null, "The collection is EMPTY");
else
{
for(int i = 0 ; i < theEntityCollection.getArraySize() ; i++)
{
fullText += "Position [" + (i+1) + "]\n\n" + theEntityCollection.getEntity(i);
if (i != theEntityCollection.getArraySize() - 1)
fullText += "_____________________\n\n";
textArea.setText(fullText);
}
deletePosition = JOptionPane.showOptionDialog(null, panel, "ENTITY COLLECTION", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options , options[0]);
}
}
catch(Exception e)
{
System.out.println("FAILED");
}
fullText = "";
}
I must say that I'm new with the Java GUI.
I'll appreciate a lot if you could help me!
GridLayout is doing exactly what it was designed to do. It provides each component with exactly the same amount of space evenly distributed based on the available space. You'll probably need to use a more flexible layout manager, for example...
Start by chaning...
GridLayout gridLayout = new GridLayout(0,1);
panel.setLayout(gridLayout);
to something like...
GridBagLayout gridLayout = new GridBagLayout();
panel.setLayout(gridLayout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
And then change...
panel.add(scrollPane);
panel.add(label0);
panel.add(labelJump1);
panel.add(txtDelete);
to something more like...
panel.add(scrollPane, gbc);
panel.add(label0, gbc);
panel.add(labelJump1, gbc);
panel.add(txtDelete, gbc);
Take a look at Laying Out Components Within a Container and How to Use GridBagLayout for more details
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);}
}
}