Basic GUI program layout positioning - java

I have been trying to figure out how to properly layout my program for quite a while now. I basically have 5 JLabels, 5 JTextFields, and 6 JButtons, I need to align it as shown below.
I tried using a GridLayout but it make the JTextFields really thick, I tried different combinations of flow layout with mixed results. I was wondering if someone can guide me as to how I can get the below result?
Thanks in advance.
Here is my code as it stands now:
public class MyClass extends JFrame{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JTextField item4;
private JTextField item5;
JLabel label1 = new JLabel("Enter number of items in this order:");
JLabel label2 = new JLabel("Enter CD ID for Item #1:");
JLabel label3 = new JLabel("Enter quantity for Item #1:");
JLabel label4 = new JLabel("Item #1 info:");
JLabel label5 = new JLabel("Order subtotal for 0 item(s):");
private JButton button1 = new JButton("Process Item #1");
private JButton button2 = new JButton("Confirm Item #1");
private JButton button3 = new JButton("View Order");
private JButton button4 = new JButton("Finish Order");
private JButton button5 = new JButton("New Order");
private JButton button6 = new JButton("Exit");
private Scanner x;
private int exitFlag = 0;
public String[] idArray = new String[10];
public String[] recordArray = new String[10];
public String[] priceArray = new String[10];
public int myNum=1;
private JPanel jp = new JPanel();
public void openFile(){
try{
x = new Scanner(new File("inventory.txt"));
x.useDelimiter(",|" + System.getProperty("line.separator"));
}
catch(Exception e){
System.out.println("Could not find file");
}
}
public void readFile(){
int i=0;
while(x.hasNext()){
idArray[i] = x.next();
recordArray[i] = x.next();
priceArray[i] = x.next();
i++;
}
}
public int itemNum(int num){
return num+1;
}
public MyClass(){
super("Matt's World of Music");
jp.setLayout(new FlowLayout(FlowLayout.RIGHT));
Box vertBox = Box.createVerticalBox();
Box vertBox2 = Box.createVerticalBox();
Box itemBox2 = Box.createHorizontalBox();
item1 = new JTextField(40);
item2 = new JTextField(40);
item3 = new JTextField(40);
item4 = new JTextField(40);
item5 = new JTextField(40);
vertBox.add(label1);
vertBox.add(label2);
vertBox.add(label3);
vertBox.add(label4);
vertBox.add(label5);
jp.add(vertBox);
vertBox2.add(item1);
vertBox2.add(item2);
vertBox2.add(item3);
vertBox2.add(item4);
vertBox2.add(item5);
jp.add(vertBox2);
itemBox2.add(button1);
itemBox2.add(button2);
itemBox2.add(button3);
itemBox2.add(button4);
itemBox2.add(button5);
itemBox2.add(button6);
jp.add(itemBox2);
add(jp);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
item4.setEditable(false);
item5.setEditable(false);
//Process Item
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MyClass obj = new MyClass();
button1.setEnabled(false);
button2.setEnabled(true);
item1.setEditable(false);
obj.openFile();
obj.readFile();
//start loop
for(int i=0; i < idArray.length; i++){
if(item2.getText().equals(obj.idArray[i])==true){
//set item4 text field to price id and other details
item4.setText(obj.idArray[i] + " " + obj.recordArray[i] + " $" + obj.priceArray[i].replaceAll("\\s",""));
}
}
}
});
//Confirm Item
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(myNum==Integer.parseInt(item1.getText())){
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
button2.setEnabled(false);
button1.setText("Process Item");
button2.setText("Confirm Item");
button1.setEnabled(false);
button3.setEnabled(true);
button4.setEnabled(true);
item2.setText("");
item3.setText("");
label2.setText("");
label3.setText("");
item2.setEditable(false);
item3.setEditable(false);
}else{
//Execute when button is pressed
button1.setEnabled(true);
button2.setEnabled(false);
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
item2.setText("");
item3.setText("");
label2.setText("Enter CD ID for Item #" + (myNum+1) + ":");
label3.setText("Enter quantity for Item #" + (myNum+1) + ":");
label4.setText("Item #" + (myNum+1) + " info:");
myNum++;
button1.setText("Process item #" + (myNum));
button2.setText("Confirm item #" + (myNum));
}
}
});
//View Order
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("View Order");
}
});
//Finish Order
button4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("Finish Order");
}
});
//New Order
button5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("New Order");
}
});
//Quit
button6.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//exit program
}
});
}
}

Using a simple GridBagLayout makes it look like in your screenshot:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyClass extends JFrame {
private final JTextField item1;
private final JTextField item2;
private final JTextField item3;
private final JTextField item4;
private final JTextField item5;
JLabel label1 = new JLabel("Enter number of items in this order:");
JLabel label2 = new JLabel("Enter CD ID for Item #1:");
JLabel label3 = new JLabel("Enter quantity for Item #1:");
JLabel label4 = new JLabel("Item #1 info:");
JLabel label5 = new JLabel("Order subtotal for 0 item(s):");
private final JButton button1 = new JButton("Process Item #1");
private final JButton button2 = new JButton("Confirm Item #1");
private final JButton button3 = new JButton("View Order");
private final JButton button4 = new JButton("Finish Order");
private final JButton button5 = new JButton("New Order");
private final JButton button6 = new JButton("Exit");
private Scanner x;
private final int exitFlag = 0;
public String[] idArray = new String[10];
public String[] recordArray = new String[10];
public String[] priceArray = new String[10];
public int myNum = 1;
private final JPanel jp;
public void openFile() {
try {
x = new Scanner(new File("inventory.txt"));
x.useDelimiter(",|" + System.getProperty("line.separator"));
} catch (Exception e) {
System.out.println("Could not find file");
}
}
public void readFile() {
int i = 0;
while (x.hasNext()) {
idArray[i] = x.next();
recordArray[i] = x.next();
priceArray[i] = x.next();
i++;
}
}
public int itemNum(int num) {
return num + 1;
}
public MyClass() {
super("Matt's World of Music");
jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.BASELINE_TRAILING;
// Box vertBox = Box.createVerticalBox();
// Box vertBox2 = Box.createVerticalBox();
// Box itemBox2 = Box.createHorizontalBox();
item1 = new JTextField(40);
item2 = new JTextField(40);
item3 = new JTextField(40);
item4 = new JTextField(40);
item5 = new JTextField(40);
c.gridx = 0;
c.gridy = 0;
jp.add(label1, c);
c.gridy++;
jp.add(label2, c);
c.gridy++;
jp.add(label3, c);
c.gridy++;
jp.add(label4, c);
c.gridy++;
jp.add(label5, c);
c.gridx = 1;
c.gridy = 0;
jp.add(item1, c);
c.gridy++;
jp.add(item2, c);
c.gridy++;
jp.add(item3, c);
c.gridy++;
jp.add(item4, c);
c.gridy++;
jp.add(item5, c);
JPanel btnPan = new JPanel(new FlowLayout(FlowLayout.CENTER));
btnPan.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
btnPan.add(button1);
btnPan.add(button2);
btnPan.add(button3);
btnPan.add(button4);
btnPan.add(button5);
btnPan.add(button6);
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
jp.add(btnPan, c);
add(jp);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
item4.setEditable(false);
item5.setEditable(false);
// Process Item
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MyClass obj = new MyClass();
button1.setEnabled(false);
button2.setEnabled(true);
item1.setEditable(false);
obj.openFile();
obj.readFile();
// start loop
for (int i = 0; i < idArray.length; i++) {
if (item2.getText().equals(obj.idArray[i]) == true) {
// set item4 text field to price id and other details
item4.setText(obj.idArray[i] + " " + obj.recordArray[i] + " $"
+ obj.priceArray[i].replaceAll("\\s", ""));
}
}
}
});
// Confirm Item
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (myNum == Integer.parseInt(item1.getText())) {
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
button2.setEnabled(false);
button1.setText("Process Item");
button2.setText("Confirm Item");
button1.setEnabled(false);
button3.setEnabled(true);
button4.setEnabled(true);
item2.setText("");
item3.setText("");
label2.setText("");
label3.setText("");
item2.setEditable(false);
item3.setEditable(false);
} else {
// Execute when button is pressed
button1.setEnabled(true);
button2.setEnabled(false);
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
item2.setText("");
item3.setText("");
label2.setText("Enter CD ID for Item #" + (myNum + 1) + ":");
label3.setText("Enter quantity for Item #" + (myNum + 1) + ":");
label4.setText("Item #" + (myNum + 1) + " info:");
myNum++;
button1.setText("Process item #" + (myNum));
button2.setText("Confirm item #" + (myNum));
}
}
});
// View Order
button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("View Order");
}
});
// Finish Order
button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("Finish Order");
}
});
// New Order
button5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("New Order");
}
});
// Quit
button6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// exit program
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyClass c = new MyClass();
c.pack();
c.setVisible(true);
}
});
}
}

I would design it this way:
the main panel would have a BorderLayout as the layout manager and contain 2 panels: one in the center and one on the south
the panel in the center could have a GridBagLayout and contain the labels and the text fields
the panel on the south could have a FlowLayout or a BoxLayout and include the buttons

As a single layout, you might look to use GroupLayout or GridBagLayout. I would probably do it as a nested layout.
A BorderLayout for the outer container.
A GridLayout of text fields in LINE_END.
A GridLayout of labels in the CENTER.
A FlowLayout for the buttons at PAGE_END.
If any of the text fields are larger than needed, wrap them in a new JPanel(new FlowLayout()) - the panel will fill the parent location, while allowing the text filed to shrink to whatever size it needs to be.
Of course that is ignoring the plethora of excellent 3rd party layouts such as FormLayout, MigLayout..

Related

JOptionpane.showMessageDialog not working inside of if-statement (event handler Program)

Context
I'm trying to build a percentage calculator using JFrame and event handling by having blank text fields and "enter" buttons and displaying the answer depending on which button they click (two different calculations for each button).
Problem
Thing is, when I put the JOptionPane.showMessageDialog line inside of the if/else if statement (all in the actionPerformed method), the program runs, but clicking the buttons does nothing. But if I put it outside of the statements, it says the answer variable is undeclared.
I realize a percentage calculator can be done in a million other, simpler ways, but this is simply what I had in mind and wanted to see if I could do it (I'm a complete beginner).
Code
public class PercentageCalc extends JFrame{
private JTextField item2, item4, item5, item7;
private JButton button, button2;
public PercentageCalc(){
super("Percentage Calculator");
setLayout(new FlowLayout());
JLabel item1 = new JLabel("What is");
add(item1);
JTextField item2 = new JTextField(3);
add(item2);
JLabel item3 = new JLabel("% of");
add(item3);
JTextField item4 = new JTextField(2);
add(item4);
button = new JButton("Enter");
add(button);
JLabel spacer = new JLabel(" ");
add(spacer);
JTextField item5 = new JTextField(3);
add(item5);
JLabel item6 = new JLabel("is what % of");
add(item6);
JTextField item7 = new JTextField(3);
add(item7);
button2 = new JButton("Enter");
add(button2);
thehandler handler = new thehandler();
button.addActionListener(handler);
button2.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String strx;
String stry;
double x, y, answer;
if(e.getSource()==button){
strx = item2.getText();
stry = item4.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
}
else if(e.getSource()==button2){
strx = item5.getText();
stry = item7.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = x/y*100;
JOptionPane.showMessageDialog(null, answer);
}
}
You have member-variable and local variable with the same name. Please read ere and here about it.
Here is the corrected variant of you program
import java.awt.FlowLayout;
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.JOptionPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class PrecentageCalc extends JFrame {
private JTextField item2, item4, item5, item7;
private JButton button, button2;
public PrecentageCalc() {
super("Percentage Calculator");
setLayout(new FlowLayout());
JLabel item1 = new JLabel("What is");
add(item1);
item2 = new JTextField(3);
add(item2);
JLabel item3 = new JLabel("% of");
add(item3);
item4 = new JTextField(2);
add(item4);
button = new JButton("Enter");
add(button);
JLabel spacer = new JLabel(" ");
add(spacer);
item5 = new JTextField(3);
add(item5);
JLabel item6 = new JLabel("is what % of");
add(item6);
item7 = new JTextField(3);
add(item7);
button2 = new JButton("Enter");
add(button2);
thehandler handler = new thehandler();
button.addActionListener(handler);
button2.addActionListener(handler);
}
private class thehandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String strx;
String stry;
double x, y, answer;
if (e.getSource() == button) {
strx = item2.getText();
stry = item4.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
} else if (e.getSource() == button2) {
strx = item5.getText();
stry = item7.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = x / y * 100;
JOptionPane.showMessageDialog(null, answer);
}
}
}
public static void main(String[] args) {
JFrame frm = new PrecentageCalc();
frm.pack();
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
Use separate ActionListeners for your buttons. Both use the same calculation method with different parameters:
public PercentageCalc() {
// Part of your code
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
handleInput(item2.getText(), item4.getText());
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
handleInput(item5.getText(), item7.getText());
}
});
}
private void handleInput(final String strx, final String stry) {
final double x = Double.parseDouble(strx);
final double y = Double.parseDouble(stry);
final double answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
}

Java swing GUI error

my GUI program is about writing a psychology quiz for my class. It uses swing but I am getting two errors on terminal and I'm not sure what the problem is. Can I know what my error is?
MyGuiProject.java:78: error: ';' expected
int JLabel scoreK = new JLabel("Your score is " + score + ".");
^
MyGuiProject.java:78: error: <identifier> expected
int JLabel scoreK = new JLabel("Your score is " + score + ".");
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGuiProject
extends JFrame implements ActionListener
{
//instance variables
//JFrame
private JFrame frame1 = new JFrame("Psychology Quiz");
private JFrame frame2 = new JFrame("Solutions");
//JPanel (p1 = panel 1)
private JPanel p1 = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
//Fonts (f1 = font 1)
private Font f1 = new Font("Times New Roman", Font.BOLD, 30);
private Font f2 = new Font("Arial", Font.ITALIC, 30);
//Description (d1 = description)
private JLabel d1 = new JLabel("Psychology - Classical Conditioning");
//questions (q1 = question 1)
private JLabel q1 = new JLabel("Any behavior or action is...");
private JLabel q2 = new JLabel(
"All mental process associated with thinking, knowing, and remembering is...");
private JLabel q3 = new JLabel("American psychologist and founder of behaviorism is...");
//answers (a1 = answer 1)
private JButton a1 = new JButton("response");
private JButton a2 = new JButton("reaction");
private JButton a3 = new JButton("stimulus");
private JButton b1 = new JButton("recognition");
private JButton b2 = new JButton("cognition");
private JButton b3 = new JButton("classical conditioning");
private JButton c1 = new JButton("John B. Watson");
private JButton c2 = new JButton("Mr. Morgan");
private JButton c3 = new JButton("Mr. Ansari");
//Images
private ImageIcon image1 = new ImageIcon("ang.jpg");
private ImageIcon image2 = new ImageIcon("psych.jpg");
//JMenu
private JMenuBar ppap = new JMenuBar();
private JMenu menu1 = new JMenu("Questions");
private JMenuItem item1 = new JMenuItem("1");
private JMenuItem item2 = new JMenuItem("2");
private JMenuItem item3 = new JMenuItem("3");
//Solutions (s1 = solution 1)
private JLabel s1 = new JLabel(
"Answers: 1) response || 2) cognition || 3) John B. Watson (unfortunately)");
//Another program for adding points and label for adding points
int score = 0;
int JLabel scoreK = new JLabel("Your score is " + score + ".");
ScoreKeeper ang1 = new ScoreKeeper();
public void angWindow()
{
//setting frame
frame1.setBounds(0, 0, 300, 400);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//addActionListener for JButton and JMenuItem
a1.addActionListener(this);
a2.addActionListener(this);
a3.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
//setting font
d1.setFont(f1);
scoreK.setFont(f2);
//JPanel for questions
p1.add(a1);
p1.add(a2);
p1.add(a3);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p3.add(c1);
p3.add(c2);
p3.add(c3);
//JMenu on JMenuBar
ppap.add(menu1);
//setting frame again
frame1.setJMenuBar(ppap);
frame1.add(q1, BorderLayout.SOUTH);
frame1.add(p1, BorderLayout.NORTH);
frame1.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("response"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q1);
frame1.remove(p1);
frame1.add(p2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("reaction"))
{
frame1.remove(p1);
frame1.remove(q1);
frame1.add(p2, BorderLayout.NORTH);
frame1.add(q2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("stimulus"))
{
frame1.remove(p1);
frame1.remove(q1);
frame1.add(p2, BorderLayout.NORTH);
frame1.add(q2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("recognition"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q2);
frame1.remove(p2);
frame1.add(p3, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("cognition"))
{
frame1.add(q3, BorderLayout.NORTH);
frame1.remove(q2);
frame1.add(p3, BorderLayout.SOUTH);
frame1.validate();
frame1.repaint();
}
if(command.equals("classical conditioning"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q2);
frame1.remove(p2);
frame1.add(p3, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("John B. Watson"))
{
frame1.remove(q3);
frame1.remove(p3);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
frame2.setVisible(true);
}
if(command.equals("..."))
{
frame1.remove(p3);
frame1.remove(q3);
frame1.validate();
frame1.repaint();
score = ang1.trackScore(score);
frame2.setVisible(true);
}
if(command.equals("..."))
{
frame1.remove(p3);
frame1.remove(q3);
frame1.validate();
frame1.repaint();
score = ang1.trackScore(score);
frame2.setVisible(true);
}
frame1.remove(scoreK);
scoreK.setText("Your score is " + score + ".");
frame1.add(scoreK, BorderLayout.CENTER);
}
public static void main(String[] args)
{
MyGuiProject angBaby = new MyGuiProject();
angBaby.setWindow();
}
}
public class ScoreKeeper
{
public int trackScore(int score)
{
score = score + 2;
return score;
}
}
Is this an int or a JLabel ?
int JLabel scoreK = new JLabel("Your score is " + score + ".");
try
JLabel scoreK = new JLabel("Your score is " + score + ".");

How to declare variable to hold value of JTextField?

I'm doing coding for Food Ordering GUI. I would like to ask few questions. I would like to ask that how should I declare variable to hold value for tfPrice1, tfPrice2, tfPrice3? What should I do to make the "Place Order" button so that when it is pressed it will sum up the values contained in the JTextFields? Below is my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FoodOrder1 extends JFrame
{
JButton riceBtn,noodleBtn,soupBtn;
JTextField display,total,tfPrice1,tfPrice2,tfPrice3;
JPanel mp,p1,p2,p3,p4,p5,p6,p7,p8;
JLabel dsp,ttl,rLbl,nLbl,sLbl,prc1,prc2,prc3;
int rice=3 , noodle=3 , soup=4;
int Total , price1=Integer.parseInt(tfPrice1), price2=Integer.parseInt(tfPrice2) , price3=Integer.parseInt(tfPrice3);
public FoodOrder1()
{
Container pane = getContentPane();
mp = new JPanel();
mp.setLayout(new GridLayout(14,1));
pane.add(mp);
p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
rLbl = new JLabel("Rice");
rLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
riceBtn = new JButton("Fried Rice " + "RM3");
p1.add(riceBtn);
riceBtn.addActionListener(new MyAction());
p1.add(rLbl);
p1.add(riceBtn);
p2 = new JPanel();
p2.setLayout(new GridLayout(1,2));
nLbl = new JLabel("Noodle");
nLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
noodleBtn = new JButton("Tomato Noodle " + "RM3");
noodleBtn.addActionListener(new MyAction());
p2.add(nLbl);
p2.add(noodleBtn);
p3 = new JPanel();
p3.setLayout(new GridLayout(1,2));
sLbl = new JLabel("Soup");
sLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
soupBtn = new JButton("Tomyam Soup " + "RM4");
soupBtn.addActionListener(new MyAction());
p3.add(sLbl);
p3.add(soupBtn);
p4 = new JPanel();
p4.setLayout(new GridLayout(1,2));
prc1 = new JLabel("Price of Fried Rice");
prc1.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice1 = new JTextField(10);
p4.add(prc1);
p4.add(tfPrice1);
tfPrice1.setEditable(false);
p5 = new JPanel();
p5.setLayout(new GridLayout(1,2));
prc2 = new JLabel("Price of Tomato Noodle");
prc2.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice2 = new JTextField(10);
p5.add(prc2);
p5.add(tfPrice2);
tfPrice2.setEditable(false);
p6 = new JPanel();
p6.setLayout(new GridLayout(1,2));
prc3 = new JLabel("Price of Tomyam Soup");
prc3.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice3 = new JTextField(10);
p6.add(prc3);
p6.add(tfPrice3);
tfPrice3.setEditable(false);
p7 = new JPanel();
p7.setLayout(new FlowLayout());
poBtn = new JButton("Place Order");
poBtn.setFont(new Font("Myraid Pro",Font.PLAIN,14));
poBtn.addActionListener(new MyAction2());
rstBtn = new JButton("Reset");
rstBtn.setFont(new Font("Myraid Pro",Font.PLAIN,14));
rstBtn.addActionListener(new MyAction3());
p7.add(poBtn);
p7.add(rstBtn);
p8 = new JPanel();
p8.setLayout(new GridLayout(1,2));
ttl = new JLabel("Total (RM)");
ttl.setFont(new Font("Myraid Pro",Font.BOLD,14));
total = new JTextField(10);
p8.add(ttl);
p8.add(total);
total.setEditable(false);
mp.add(p1);
mp.add(p2);
mp.add(p3);
mp.add(p4);
mp.add(p5);
mp.add(p6);
mp.add(p7);
mp.add(p8);
}
public class MyAction implements ActionListener
{
int counter=0;
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == riceBtn)
{
counter++;
tfPrice1.setText("RM" + String.valueOf(counter*rice));
}
if (e.getSource() == noodleBtn)
{
counter++;
tfPrice2.setText("RM" + String.valueOf(counter*noodle));
}
if (e.getSource() == soupBtn)
{
counter++;
tfPrice3.setText("RM" + String.valueOf(counter*soup));
}
}
}
public class MyAction2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
price1.setText(String.valueOf(tfPrice1));
price2.setText(String.valueOf(tfPrice2));
price3.setText(String.valueOf(tfPrice3));
Total = price1+price2+price3;
total.setText(String.valueOf(Total));
}
}
public class MyAction3 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == rstBtn)
{
tfPrice1.setText("");
tfPrice2.setText("");
tfPrice3.setText("");
total.setText("");
}
}
}
public static void main(String [] args)
{
FoodOrder1 f = new FoodOrder1();
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1000,800);
}
}
You don't need a variable to hold the value. Just extract the text from the text boxes whenever you need the value.
double totalPrice = 0.0;
totalPrice += Double.parseDouble(tfPrice1.getText());
totalPrice += Double.parseDouble(tfPrice2.getText());
totalPrice += Double.parseDouble(tfPrice3.getText());
total.setText(String.valueOf(totalPrice));
here is code to hold textfield value to some string
String data = txtdata.getText();
Take data entered to txtdata jTextField into data which is of string datatype

Message to JList [duplicate]

This question already has an answer here:
Gui JList ActionListener
(1 answer)
Closed 9 years ago.
hey all goodevening i have a problem about my second button named "Submit" because i cant transfer all information i entered to my null JList in the frame here is my code so far my problem is if i clicked submit my all information will appear in my Message area in frame it needs to be list. thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class vin extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
JList list = new JList();
JPanel panel = new JPanel();
JLabel brief;
public vin()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
list = new JList();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
vin w = new vin();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}
I modified your code so that your list is backed by a Vector which you update when you press the Submit button.
public class Frame extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
Vector vector = new Vector();
JList list = new JList(vector);
JPanel panel = new JPanel();
JLabel brief;
public Frame()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
vector.add(t1.getText() + "-" + t2.getText() + "-" + t3.getText() + "-" + t4.getText());
list.setListData(vector);
list.revalidate();
list.repaint();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
Frame w = new Frame();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}

Can anyone tell me why my change QTY button isnt changing the QTY?

Can anyone tell me why my change QTY button isnt changing the QTY?
The buttonlistener2 is supposed to change the number of items in arrayCount[x]
to the number in the count JTextfield, but its not, could use a new set of eyes.
thanks all
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ProduceInventory extends JFrame
{
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<Integer> arrayCount = new ArrayList<Integer>();
// declares panels and items
private final int WINDOW_WIDTH = 450;
private final int WINDOW_HEIGHT = 350;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JTextField name;
private JTextField count;
private JTextArea output;
private JButton add;
private JButton changeQTY;
private JButton delete;
private JButton clear;
private JButton report;
private JButton save;
private JButton load;
public ProduceInventory()
{
//creates Jframe
setTitle("Produce Inventory");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1(); //build panels
panel2();
panel3();
add(panel1, BorderLayout.NORTH); //add panels
add(panel2, BorderLayout.SOUTH);
add(panel3, BorderLayout.CENTER);
setVisible(true);
}
private void panel1() //builds panel 1
{
messageLabel1 = new JLabel("Name");
messageLabel2 = new JLabel("Count");
name = new JTextField(20);
count = new JTextField(5);
panel1 = new JPanel();
panel1.add(messageLabel1);
panel1.add(name);
panel1.add(messageLabel2);
panel1.add(count);
}
private void panel2() //builds panel 2
{
add = new JButton("Add");
changeQTY = new JButton("CHANGE QTY");
delete = new JButton("Delete");
clear = new JButton("Clear");
report = new JButton("Report");
save = new JButton("Save File");
load = new JButton("Load File");
add.addActionListener(new ButtonListener());
changeQTY.addActionListener(new ButtonListener2());
panel2 = new JPanel();
panel2.setLayout(new GridLayout(2,4));
panel2.add(add);
panel2.add(changeQTY);
panel2.add(delete);
panel2.add(clear);
panel2.add(report);
panel2.add(save);
panel2.add(load);
}
private void panel3() //builds panel 3
{
output = new JTextArea(10,30);
panel3 = new JPanel();
panel3.add(output);
}
private class ButtonListener implements ActionListener //add listener
{
String nameIn;
String countIn;
int number;
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
nameIn = name.getText();
arrayName.add(name.getText());
countIn = count.getText();
number = Integer.parseInt(countIn);
arrayCount.add(number);
output.setText(name.getText() + " " + count.getText() + " Item Added");
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
private class ButtonListener2 implements ActionListener //add listener
{
public void actionPerformed(ActionEvent e)
{
String nameIn;
String countIn;
int number;
String actionCommand = e.getActionCommand();
if (actionCommand.equals("CHANGE QTY"))
{
nameIn = name.getText();
countIn = count.getText();
number = Integer.parseInt(countIn);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
if(arrayName.get(x) == nameIn)
{
arrayCount.set(x, number);
}
}
output.setText("Qty is updated to: " + number);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ProduceInventory(); //runs program
}
}
In the action listener, on the line
if(arrayName.get(x) == nameIn)
you are checking if the two variables refer to the same object. Instead of that you have to check if the objects they refer to are equal:
if(nameIn.equals(arrayName.get(x)))

Categories

Resources