Having prob with my "Display Data Button" - java

Try running my program. Press Add Subject (fill the data). Then Display. Then Add another subject. Then Display.
On the Display Tab, it shows 2 subjects and 1 empty subject.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
#SuppressWarnings ({"unchecked" , "rawtypes"})
public class StudentGradeCalc extends JFrame implements ActionListener {
//String setName [];
int x = 0;
int count = 0;
int w = 0;
int [] addSize = {50,10,20,30,40,100};
private JPanel panelInfo = new JPanel(new GridLayout(7,0) );
private JLabel sy = new JLabel ("School Year : ");
private JLabel sem = new JLabel ("Sem/Term: ");
private JLabel Name = new JLabel ("Name : ");
private JLabel Course = new JLabel ("Course : ");
private JLabel Year = new JLabel ("Year : ");
private JLabel college = new JLabel ("College : ");
private JLabel id = new JLabel ("I.D Number : ");
private JTextField syear = new JTextField ("");
private JTextField semnum = new JTextField("");
private JTextField name = new JTextField ("");
private JTextField course = new JTextField ("");
private JTextField year = new JTextField ("");
private JTextField scs = new JTextField("");
private JTextField idnum = new JTextField("");
private JPanel fakebuttons = new JPanel (new GridLayout (4,0,10,10));
private JButton addSubject = new JButton("Add Subject..");
private JButton deleteSubject = new JButton("Delete Subject..");
private JButton editSubject = new JButton("Edit Subject..");
private JButton totalLoad = new JButton("Total Load : ");
private JButton GPA = new JButton ("GPA : ");
private JTextField units_textfield = new JTextField(3);
private JTextField gpa_textfield = new JTextField (7);
private JButton displayInfo = new JButton("Display Data");
private JPanel addPanel = new JPanel(new GridLayout(3,2,20,10));
private JLabel subjectName = new JLabel("Subject: ");
private JTextField subject [] ;
private JLabel gradeLabel = new JLabel("Grade : ");
private JLabel unitsLabel = new JLabel ("Units : ");
private JButton addButton = new JButton ("Add");
String grade [] = {"1.00","1.25","1.50","1.75","2.00","2.25","2.50","2.75","3.00","5.0", "DRP", "INC", "WDRW"};
private JComboBox comboGrade [];
String unit [] = {"1","2","3","4","5","6"};
private JComboBox comboUnit[];
private JButton done = new JButton ("Done");
private JButton d_subj,d_unit,d_grade;
// private JTextField displaySubject = new JTextField();
// private JTextField displayUnit = new JTextField ();
//private JTextField displayGrade = new JTextField();
private JTextField displaySubject[];
private JTextField displayUnit[];
private JTextField displayGrade [];
private JLabel t_units = new JLabel ("Total Load : ");
private JTextField totalUnits = new JTextField ();
private JLabel gpa = new JLabel ("GPA : ");
private JTextField gpaTxt = new JTextField ();
private JLabel err = new JLabel ("No Entry Found");
private JLabel display1 = new JLabel ();
private JLabel display2 = new JLabel ();
private JLabel displayID = new JLabel ();
final String getName [] = new String [10];
final int getUnit [] = new int [10];
final String getGrade [] = new String [10];
public StudentGradeCalc()
{
Border border = BorderFactory.createLineBorder(null);
setLayout(null);
panelInfo.setBounds(5,5,280,150);
//panelInfo.setBorder(border);
panelInfo.add(Name);
panelInfo.add(name);
panelInfo.add(Course);
panelInfo.add(course);
panelInfo.add(Year);
panelInfo.add(year);
panelInfo.add(sy);
panelInfo.add(syear);
panelInfo.add(sem);
panelInfo.add(semnum);
panelInfo.add(college);
panelInfo.add(scs);
panelInfo.add(id);
panelInfo.add(idnum);
add(panelInfo);
fakebuttons.setBounds(5,160,280,160);
fakebuttons.add(addSubject);
fakebuttons.add(deleteSubject);
fakebuttons.add(editSubject);
fakebuttons.add(displayInfo);
add(fakebuttons);
//ADD SUBJECT BUTTON
addSubject.addActionListener(new ActionListener (){
public void actionPerformed (ActionEvent cags){
final JFrame addFrame = new JFrame ();
addFrame.setVisible(true);
addFrame.setSize (300,190);
addFrame.setResizable(false);
addFrame.setLocationRelativeTo(null);
addFrame.setTitle("Add Subject");
//addFrame.setLayout(new GridLayout (3,2,20,10));
addFrame.setLayout(null);
subject = new JTextField [] {
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
};
subjectName.setBounds (10,10,120,20);
subject[x].setBounds (75,10,170,20);
addFrame.add(subjectName);
addFrame.add(subject[x]);
gradeLabel.setBounds (10,40,100,20);
addFrame.add(gradeLabel);
comboGrade = new JComboBox [] {
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
};
comboGrade[x].setBounds(150,40,95,20);
addFrame.add(comboGrade[x]);
unitsLabel.setBounds (10, 70, 95, 20);
addFrame.add(unitsLabel);
comboUnit = new JComboBox [] {
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
};
comboUnit[x].setBounds(150,70,95,20);
addFrame.add(comboUnit[x]);
addButton.setBounds (120,120,60,30);
addFrame.add(addButton);
w++;
addButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent k){
//JOptionPane.showMessageDialog(null, "Subject "+subject[x].getText()+ " has been added", "Add Subject", JOptionPane.INFORMATION_MESSAGE);
getName [x] = subject[x].getText();
getGrade[x] = String.valueOf((String)comboGrade[x].getSelectedItem());
getUnit [x] = Integer.valueOf((String)comboUnit[x].getSelectedItem());
x++;
addFrame.dispose();
}
});
}
});
//DISPLAY DATA BUTTON
displayInfo.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent m){
final String name_course_year = "Name : "+name.getText()+ " Course : " +course.getText()+"- "+year.getText()+ " ID : "+idnum.getText() ;
final String ubos = "College : "+scs.getText()+ " SY : "+syear.getText()+ " Term : "+semnum.getText() ;
//String nametanga [] = {name.getText() , };
if (name.getText().equals("")|| course.getText().equals("")||year.getText ().equals("") || idnum.getText().equals("")||syear.getText ().equals("") || scs.getText().equals("")|| semnum.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Complete the Information!", "ERROR", JOptionPane.WARNING_MESSAGE);
}
else
{
final JFrame display = new JFrame ();
display.setVisible(true);
//display.setSize (400,200);
//display.setSize (400,down+130);
display.setResizable(false);
display.setLocationRelativeTo(null);
display.setTitle("Student Info");
display.setLayout(null);
display1.setBounds (5,5,390,20);
display2.setBounds (5,25,390,20);
display1.setText(name_course_year);
display2.setText(ubos);
display.add(display1);
display.add(display2);
d_subj = new JButton ("Subject");
d_unit = new JButton ("Unit");
d_grade = new JButton ("Grade");
d_subj.setBounds(10,50,180,20);
d_unit.setBounds (200,50,90,20);
d_grade.setBounds(300,50,90,20);
display.add(d_subj);
display.add(d_unit);
display.add(d_grade);
displaySubject = new JTextField [] {
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
};
displayUnit = new JTextField [] {
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),
};
displayGrade = new JTextField [] {
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),
};
int y = 30;
int down = 80;
int z = 0;
for (int i = 0; i < x; i++)
{
displaySubject[i].setBounds(10,down,180,y);
displayUnit[i].setBounds(200,down,90,y);
displayGrade[i].setBounds(300,down,90,y);
displaySubject[i].setText(getName[i]);
displayUnit[i].setText(""+getUnit[i]);
displayGrade[i].setText(getGrade[i]);
display.add(displaySubject[i]);
display.add(displayUnit[i]);
display.add(displayGrade[i]);
displaySubject[i].setEditable(false);
displayUnit[i].setEditable(false);
displayGrade[i].setEditable(false);
down+=y+10;
//i++;
// z++;
}
display.setSize (400,down+130);
t_units.setBounds (100,down,70,25);
totalUnits.setBounds(180,down,50,25);
gpa.setBounds(260,down,50,25);
gpaTxt.setBounds(310,down,80,25);
display.add(t_units);
display.add(totalUnits);
display.add(gpa);
display.add(gpaTxt);
gpaTxt.setEditable(false);
totalUnits.setEditable(false);
done.setBounds (170,down+50,70,30);
display.add(done);
done.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent done){
display.dispose();
}
});
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize (300,355);
setResizable(false);
setLocationRelativeTo(null);
setTitle("Student Grade Calculator");
}
public void actionPerformed (ActionEvent vahn)
{
System.exit(1);
}
public static void main(String[] args) {
new StudentGradeCalc();
}
}
I do not know where to find the reason why my program makes this error.

I found your problem it's here addButton.addActionListener(). You always add a new ActionListener to your button instance, because of that, every time you push addSubject button you also add a new Listener to addButton. Don't do that in the future, add your Listeners to Components, in method of component construction.

Related

Radio Button does not appear in JFrame

My JRadioButton does not appear in the JFrame.
It should appear below the Method of payment. If the user picks the creditRadioButton, the creditCardLabel and the creditTextField appears.
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class FinishTransaction extends JFrame implements ActionListener{
JLabel totalLabel;
JLabel nameLabel;
JLabel addressLabel;
JLabel contactLabel;
JLabel custPaymentLabel;
JLabel changeLabel;
JLabel methodLabel;
JLabel creditCardLabel;
JTextField totalTextField;
JTextField nameTextField;
JTextField addressTextField;
JTextField contactTextField;
JTextField custPaymentTextField;
JTextField changeTextField;
JTextField creditCardTextField;
final ButtonGroup bGroup = new ButtonGroup();
final JRadioButton[] buttons = new JRadioButton[2];
JButton checkoutButton;
static FinishTransaction fin = new FinishTransaction();
public FinishTransaction(){
super("Finish Transaction-Print Receipt");
setLayout(null);
totalLabel = new JLabel("Total Payment: ");
nameLabel = new JLabel("Name: ");
addressLabel = new JLabel("Address: ");
contactLabel = new JLabel("Contact: ");
custPaymentLabel = new JLabel("Payment: ");
changeLabel = new JLabel("Change: ");
totalTextField = new JTextField("");
nameTextField = new JTextField("");
addressTextField = new JTextField("");
contactTextField = new JTextField("");
custPaymentTextField = new JTextField("");
changeTextField = new JTextField("");
methodLabel = new JLabel("Method of payment: ");
creditCardLabel = new JLabel("Credit Card number: ");
creditCardTextField = new JTextField("");
checkoutButton = new JButton("Checkout");
buttons[0] = new JRadioButton("Cash");
buttons[1] = new JRadioButton("Credit Card");
totalTextField.setEditable(false);
changeTextField.setEditable(false);
creditCardLabel.setVisible(false);
creditCardTextField.setVisible(false);
nameLabel.setBounds(50,60,100,20); nameTextField.setBounds(130,60,200,20);
addressLabel.setBounds(50,80,100,20); addressTextField.setBounds(130,80,200,20);
contactLabel.setBounds(50,100,100,20); contactTextField.setBounds(130,100,200,20);
methodLabel.setBounds(50,130,200,20);
buttons[0].setBounds(50,150,100,20);
creditCardLabel.setBounds(90,170,150,20); creditCardTextField.setBounds(210,170,200,20);
buttons[1].setBounds(50,190,100,20);
totalLabel.setBounds(50,230,100,20); totalTextField.setBounds(140,230,200,20);
custPaymentLabel.setBounds(50,250,100,20); custPaymentTextField.setBounds(130,250,200,20);
changeLabel.setBounds(50,270,100,20); changeTextField.setBounds(130,270,200,20);
checkoutButton.setBounds(130,310,200,20);
add(nameLabel);
add(addressLabel);
add(contactLabel);
add(methodLabel);
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
add(creditCardLabel);
add(totalLabel);
add(custPaymentLabel);
add(changeLabel);
add(nameTextField);
add(addressTextField);
add(contactTextField);
add(creditCardTextField);
add(totalTextField);
add(custPaymentTextField);
add(changeTextField);
add(checkoutButton);
buttons[0].setSelected(true);
buttons[0].addActionListener(this);
buttons[1].addActionListener(this);
checkoutButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(checkoutButton.getName().equals(((Component)e.getSource()).getName())){
}
if(buttons[0].isSelected()){
creditCardLabel.setVisible(true);
creditCardTextField.setVisible(true);
}
}
public static void main(String args[]){
fin.setVisible(true);
fin.setResizable(false);
fin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fin.setSize(500,400);
}
}
The output:
You did not add buttons[0] and buttons[1] to the panel. Try to add them after this line add(methodLabel); and check the result.
add(buttons[0]);
add(buttons[1]);

Swing program exits immediately after starting

The program will launch but then immediately quit. Also, I'm not quite sure if adding multiple panels to a class that extends JFrame is allowed.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TravelExpensesCaskey extends JFrame
{
private double tripDays;
private double airfareCost;
private double carRentalFees;
private double numMiles;
private double parkingFees;
private double taxiCharges;
private double registrationFees;
private double lodgingCost;
private final double FOOD_$_PER_DAY = 37.00;
private final double PARKING_$_PER_DAY = 10.00;
private final double TAXI_$_PER_DAY = 20.00;
private final double LODGING_$_PER_DAY = 95.00;
private final double $_PER_MILE = 0.27;
private JPanel inputPanel;
private JPanel messageBar;
private JPanel panel;
private JPanel calculateBar;
private JButton calcButton;
private final int WINDOW_HEIGHT = 400;
private final int WINDOW_WIDTH = 200;
private JTextField field2;
private JTextField field3;
private JTextField field4;
private JTextField field5;
private JTextField field6;
private JTextField field7;
private JTextField field8;
private JTextField field9;
private double totalExpenditures;
private double totalAllowance;
private double totalBalance;
private double totalStipend;
public TravelExpensesCaskey()
{
setTitle("Travel Expenses");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label1 = new JLabel("Please input the following information about your trip. Enter 0 for any irrelavent values.");
messageBar = new JPanel();
messageBar.add(label1);
add(messageBar);
inputPanel.setLayout(new GridLayout(9,2));
inputPanel = buildPanel();
add(inputPanel);
calculateBar = buildCalculateBar();
add(calculateBar);
setVisible(true);
JOptionPane.showMessageDialog(null, "The total expenses incurred by the business person: " + totalExpenditures + "." +
"\nThe total allowance for the business person: " + totalAllowance + "." +
"\nThe total balance that must be paid for by the business person: " + totalBalance + "." +
"\nThe total stipend available to the business person: " + totalStipend + ".");
}
private JPanel buildPanel()
{
JLabel label2 = new JLabel("Number of Days: ");
JLabel label3 = new JLabel("Airfare Charges: :");
JLabel label4 = new JLabel("Car Rental Fees: ");
JLabel label5 = new JLabel("Number of Miles Driven: ");
JLabel label6 = new JLabel("Amount of Parking Fees: ");
JLabel label7 = new JLabel("Amount of Taxi Charges: ");
JLabel label8 = new JLabel("Conference/Seminar Registration Fees: ");
JLabel label9 = new JLabel("Lodging Charges per Night: ");
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
JPanel panel9 = new JPanel();
panel2.add(label2);
panel3.add(label3);
panel4.add(label4);
panel5.add(label5);
panel6.add(label6);
panel7.add(label7);
panel8.add(label8);
panel9.add(label9);
JTextField field2 = new JTextField(10);
JTextField field3 = new JTextField(10);
JTextField field4 = new JTextField(10);
JTextField field5 = new JTextField(10);
JTextField field6 = new JTextField(10);
JTextField field7 = new JTextField(10);
JTextField field8 = new JTextField(10);
JTextField field9 = new JTextField(10);
panel.add(panel2);
panel.add(field2);
panel.add(panel3);
panel.add(field3);
panel.add(panel4);
panel.add(field4);
panel.add(panel5);
panel.add(field5);
panel.add(panel6);
panel.add(field6);
panel.add(panel7);
panel.add(field7);
panel.add(panel8);
panel.add(field8);
panel.add(panel9);
panel.add(field9);
return panel;
}
private JPanel buildCalculateBar()
{
JPanel panel = new JPanel();
calcButton = new JButton("Calculate");
calcButton.addActionListener(new ButtonListener());
panel.add(calcButton);
return panel;
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String userText = "";
userText = field2.getText();
tripDays = Integer.parseInt(userText);
userText = field3.getText();
airfareCost = Integer.parseInt(userText);
userText = field4.getText();
carRentalFees = Integer.parseInt(userText);
userText = field5.getText();
numMiles = Integer.parseInt(userText);
userText = field6.getText();
parkingFees = Integer.parseInt(userText);
userText = field7.getText();
taxiCharges = Integer.parseInt(userText);
userText = field8.getText();
registrationFees = Integer.parseInt(userText);
userText = field9.getText();
lodgingCost = Integer.parseInt(userText);
calcCharges();
}
}
private void calcCharges()
{
totalExpenditures = (tripDays * lodgingCost) + parkingFees + airfareCost + carRentalFees + taxiCharges + registrationFees;
totalAllowance = (tripDays * FOOD_$_PER_DAY) + (tripDays + PARKING_$_PER_DAY) + (tripDays * TAXI_$_PER_DAY)
+ (tripDays * LODGING_$_PER_DAY) + (numMiles * $_PER_MILE);
if ((totalExpenditures - totalAllowance) < 0)
{
totalStipend = Math.abs(totalExpenditures - totalAllowance);
totalBalance = 0;
}
else if ((totalExpenditures - totalAllowance) > 0)
{
totalBalance = totalExpenditures - totalAllowance;
totalStipend = 0;
}
}
public static void main(String[] args)
{
new TravelExpensesCaskey();
}
}
Your program throw multiple NullPointerExceptions. You declare many objects as class fields and then never initialize them. You need to add at least:
inputPanel = new JPanel(); in constructor,
panel = new JPanel(); in buildPanel();
and in case of all yours JTextFields, change from:
JTextField field = new JTextField();
to:
field = new JTextField();
But it is only beginning because you GUI doesn't display most of components. You need to choose LayoutManager, and work with it. You add all your panels to center of your frames BorderLayout and I think they overlap . So for example, to see your JTextFields, JLabel and JButton, you can change add(component); in constructor for:
add(BorderLayout.NORTH, messageBar);
add(BorderLayout.CENTER, inputPanel);
add(BorderLayout.SOUTH,calculateBar);
also add:
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
in buildPanel() method, and it will look better.
Whats more, you need to move code for JOptionPane to the end of calcCharges() method, this way it will have access to processed date and it will display proper output. At beginning of a app, it displays only zeros.

Debugging code I have with 2 classes and a JFrame that holds 4 JPanels

I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
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.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}

JButton exits JPanel

I have multiple cancel, ok, and save buttons. When the user clicks one of these buttons, I need it to exit the JPanel, but not the whole program. I have tried multiple times and everything I do it exits the whole program. My code is below. I know there is a lot of stuff on my code and it can get confusing. Thanks in advance.
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
JLabel input = new JLabel();
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.add(input);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// Make all necessary buttons
JButton next = new JButton("Next");
JButton save = new JButton("Save");
JButton save2 = new JButton("Save");
JButton save3 = new JButton("Save");
JButton save4 = new JButton("Save");
JButton aok = new JButton("OK");
JButton bok = new JButton("OK");
JButton cok = new JButton("OK");
JButton acancel = new JButton("Cancel");
JButton bcancel = new JButton("Cancel");
JButton ccancel = new JButton("Cancel");
JButton dcancel = new JButton("Cancel");
JButton ecancel = new JButton("Cancel");
JButton fcancel = new JButton("Cancel");
JButton gcancel = new JButton("Cancel");
JButton hcancel = new JButton("Cancel");
//Make the drop down lists
String[] baudrates = {"57600", "115200", "128000", "256000"};
JComboBox baudlist = new JComboBox(baudrates);
String[] baudrates2 = {"57600", "115200", "128000", "256000"};
JComboBox baudlist2 = new JComboBox(baudrates2);
String[] bytesizes = {"7", "8"};
JComboBox bytelist = new JComboBox(bytesizes);
String[] bytesizes2 = {"7", "8"};
JComboBox bytelist2 = new JComboBox(bytesizes2);
String[] stopbit = {"1", "2"};
JComboBox stoplist = new JComboBox(stopbit);
String[] stopbit2 = {"1", "2"};
JComboBox stoplist2 = new JComboBox(stopbit2);
String[] flows = {"None", "Hardware","Xon", "Xoff"};
JComboBox flowlist = new JComboBox(flows);
String[] flows2 = {"None", "Hardware","Xon", "Xoff"};
JComboBox flowlist2 = new JComboBox(flows2);
String[] paritys = {"None", "Even", "Odd"};
JComboBox paritylist = new JComboBox(paritys);
String[] paritys2 = {"None", "Even", "Odd"};
JComboBox paritylist2 = new JComboBox(paritys2);
//Make all necessary labels
JLabel cardLabel = new JLabel("Card Number: ");
JLabel expLabel = new JLabel("Exp. Date (MM/YY): ");
JLabel cvvLabel = new JLabel("CVV: ");
JLabel ipLabel = new JLabel("IP Address: ");
JLabel connectLabel = new JLabel("Connect Time: ");
JLabel sendLabel = new JLabel("Send Time Out: ");
JLabel receiveLabel = new JLabel("Receive Time Out: ");
JLabel portLabel = new JLabel("Port: ");
JLabel baudrate = new JLabel("Baud Rate: ");
JLabel bytesize = new JLabel("Byte Size: ");
JLabel stopbits = new JLabel("Stop Bits: ");
JLabel flow = new JLabel("Flow Con..: ");
JLabel parity = new JLabel("Parity: ");
JLabel stoLabel = new JLabel("Send Time Out: ");
JLabel rtoLabel = new JLabel("Receive Time Out: ");
JLabel portLabel2 = new JLabel("Port: ");
JLabel baudrate2 = new JLabel("Baud Rate: ");
JLabel bytesize2 = new JLabel("Byte Size: ");
JLabel stopbits2 = new JLabel("Stop Bits: ");
JLabel flow2 = new JLabel("Flow Con..: ");
JLabel parity2 = new JLabel("Parity: ");
JLabel stoLabel2 = new JLabel("Send Time Out: ");
JLabel rtoLabel2 = new JLabel("Receive Time Out: ");
JLabel portLabel3 = new JLabel("Port: ");
JLabel vendor = new JLabel("Vendor ID: ");
JLabel product = new JLabel("Product ID: ");
JLabel stoLabel3 = new JLabel("Send Time Out: ");
JLabel rtoLabel3 = new JLabel("Receive Time Out: ");
JLabel amountLabel = new JLabel("Amount: ");
JLabel textLabel = new JLabel("Display Text: ");
//Make all necessary TextFields
JTextField card = new JTextField(10);
JTextField expDate = new JTextField(10);
JTextField cvv = new JTextField(10);
JTextField ip = new JTextField(10);
JTextField ct = new JTextField(10);
JTextField rto = new JTextField(10);
JTextField sto = new JTextField(10);
JTextField port = new JTextField(10);
JTextField sendto = new JTextField(10);
JTextField reto = new JTextField(10);
JTextField comport = new JTextField(10);
JTextField sendto2 = new JTextField(10);
JTextField reto2 = new JTextField(10);
JTextField comport2 = new JTextField(10);
JTextField vendorid = new JTextField(10);
JTextField productid = new JTextField(10);
JTextField sendtime = new JTextField(10);
JTextField receiveto = new JTextField(10);
JTextField amountbox = new JTextField(10);
JTextField textBox = new JTextField(10);
JTextArea logbox = new JTextArea();
//Add components to the panels
final JPanel ethernetSettings = new JPanel();
ethernetSettings.setLayout(new GridLayout(6, 2));
ethernetSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
ethernetSettings.add(ipLabel);
ethernetSettings.add(ip);
ethernetSettings.add(connectLabel);
ethernetSettings.add(ct);
ethernetSettings.add(receiveLabel);
ethernetSettings.add(rto);
ethernetSettings.add(sendLabel);
ethernetSettings.add(sto);
ethernetSettings.add(portLabel);
ethernetSettings.add(port);
ethernetSettings.add(save);
ethernetSettings.add(ecancel);
final JPanel usbHIDSettings = new JPanel();
usbHIDSettings.setLayout(new GridLayout(5, 2));
usbHIDSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
usbHIDSettings.add(vendor);
usbHIDSettings.add(vendorid);
usbHIDSettings.add(product);
usbHIDSettings.add(productid);
usbHIDSettings.add(stoLabel3);
usbHIDSettings.add(sendtime);
usbHIDSettings.add(rtoLabel3);
usbHIDSettings.add(receiveto);
usbHIDSettings.add(save4);
usbHIDSettings.add(hcancel);
final JPanel usbCDCSettings = new JPanel();
usbCDCSettings.setLayout(new GridLayout(9, 2));
usbCDCSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
usbCDCSettings.add(baudrate2);
usbCDCSettings.add(baudlist);
usbCDCSettings.add(bytesize2);
usbCDCSettings.add(bytelist);
usbCDCSettings.add(stopbits2);
usbCDCSettings.add(stoplist);
usbCDCSettings.add(flow2);
usbCDCSettings.add(flowlist);
usbCDCSettings.add(parity2);
usbCDCSettings.add(paritylist);
usbCDCSettings.add(stoLabel2);
usbCDCSettings.add(sendto2);
usbCDCSettings.add(rtoLabel2);
usbCDCSettings.add(reto2);
usbCDCSettings.add(portLabel3);
usbCDCSettings.add(comport2);
usbCDCSettings.add(save3);
usbCDCSettings.add(gcancel);
final JPanel rsSettings = new JPanel();
rsSettings.setLayout(new GridLayout(9, 2));
rsSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
rsSettings.add(baudrate);
rsSettings.add(baudlist2);
rsSettings.add(bytesize);
rsSettings.add(bytelist2);
rsSettings.add(stopbits);
rsSettings.add(stoplist2);
rsSettings.add(flow);
rsSettings.add(flowlist2);
rsSettings.add(parity);
rsSettings.add(paritylist2);
rsSettings.add(stoLabel);
rsSettings.add(sendto);
rsSettings.add(rtoLabel);
rsSettings.add(reto);
rsSettings.add(portLabel2);
rsSettings.add(comport);
rsSettings.add(save2);
rsSettings.add(fcancel);
JRadioButton ethernet = new JRadioButton("Ethernet");
ethernet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog esettings = new JDialog(frame);
esettings.setTitle("Ethernet Settings");
esettings.add(ethernetSettings);
esettings.setSize(400, 400);
esettings.pack();
esettings.setVisible(true);
}
});
JRadioButton rs = new JRadioButton("RS232");
rs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog rsettings = new JDialog(frame);
rsettings.setTitle("RS232 Settings");
rsettings.add(rsSettings);
rsettings.pack();
rsettings.setVisible(true);
}
});
JRadioButton usbcdc = new JRadioButton("USB_CDC");
usbcdc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog usbc = new JDialog(frame);
usbc.setTitle("USB_CDC Settings");
usbc.add(usbCDCSettings);
usbc.setSize(400, 400);
usbc.pack();
usbc.setVisible(true);
}
});
JRadioButton usbhid = new JRadioButton("USB_HID");
usbhid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog usbh = new JDialog(frame);
usbh.setTitle("USB_HID Settings");
usbh.add(usbHIDSettings);
usbh.setSize(400, 400);
usbh.pack();
usbh.setVisible(true);
}
});
final JPanel PortSettings = new JPanel();
PortSettings.setLayout(new GridLayout(3, 4));
PortSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
PortSettings.add(ethernet);
PortSettings.add(rs);
PortSettings.add(usbcdc);
PortSettings.add(usbhid);
PortSettings.add(next);
PortSettings.add(bcancel);
final JPanel accountPanel = new JPanel();
accountPanel.setLayout(new GridLayout(4, 2));
accountPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
accountPanel.add(cardLabel);
accountPanel.add(card);
accountPanel.add(expLabel);
accountPanel.add(expDate);
accountPanel.add(cvvLabel);
accountPanel.add(cvv);
accountPanel.add(bok);
accountPanel.add(ccancel);
JRadioButton apprve = new JRadioButton("Approve");
JRadioButton decline = new JRadioButton("Decline");
final JPanel apprvordecl = new JPanel();
apprvordecl.setLayout(new GridLayout(3, 2));
apprvordecl.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
apprvordecl.add(apprve);
apprvordecl.add(decline);
apprvordecl.add(textLabel);
apprvordecl.add(textBox);
apprvordecl.add(aok);
apprvordecl.add(acancel);
final JPanel amountPanel = new JPanel();
amountPanel.setLayout(new GridLayout(2, 2));
amountPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
amountPanel.add(amountLabel);
amountPanel.add(amountbox);
amountPanel.add(cok);
amountPanel.add(dcancel);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
portsettings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog port = new JDialog(frame);
port.setTitle("Port Settings");
port.setSize(400, 400);
port.add(PortSettings);
port.pack();
port.setVisible(true);
}
});
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
account.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog accountDialog = new JDialog(frame);
accountDialog.setTitle("Account");
accountDialog.setSize(400, 400);
accountDialog.add(accountPanel);
accountDialog.pack();
accountDialog.setVisible(true);
}
});
JButton amount = new JButton("Amount");
amount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog amount2 = new JDialog(frame);
amount2.setTitle("Amount");
amount2.setSize(400, 400);
amount2.add(amountPanel);
amount2.pack();
amount2.setVisible(true);
}
});
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
approvordecl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog apprv = new JDialog(frame);
apprv.setTitle("Approve / Decline");
apprv.setSize(400, 400);
apprv.add(apprvordecl);
apprv.pack();
apprv.setVisible(true);
}
});
JButton test = new JButton("Test Button #1");
JButton testing = new JButton("Test Button #2");
JRadioButton button = new JRadioButton("Radio Button");
JRadioButton button2 = new JRadioButton("Radio Button");
JCheckBox checkbox = new JCheckBox("Check Box");
JCheckBox checkbox2 = new JCheckBox("Check Box");
ButtonGroup group = new ButtonGroup();
group.add(usbhid);
group.add(usbcdc);
group.add(ethernet);
group.add(rs);
ButtonGroup approvegroup = new ButtonGroup();
approvegroup.add(apprve);
approvegroup.add(decline);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.add(online);
llpPanel.add(offline);
llpPanel.add(status);
llpPanel.add(reboot);
llpPanel.add(account);
llpPanel.add(amount);
llpPanel.add(reset);
llpPanel.add(approvordecl);
llpPanel.add(logbox);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
I have tried multiple times and everything I do it exits the whole program.
I don't see you code for closing the dialog so I can't guess what you might be doing wrong.
In your ActionListener you would invoke the dispose method on the dialog. The code would be something like:
JButton button = (JButton)event.getSource();
Window dialog = SwingUtilities.windowForComponent( button );
dialog.dispose();
A different approach might be to use a JOptionPane, then you don't need to code your own ActionListeners. You can easily add a panel to an option pane. The code below shows two approaches:
import java.awt.*;
import javax.swing.*;
public class OptionPanePanel
{
private static void createAndShowUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
// Build a custom panel
JPanel panel = new JPanel( new GridLayout(2, 2) );
panel.add( new JLabel("First Name") );
JTextField firstName = new JTextField(10);
// firstName.addAncestorListener( new RequestFocusListener(false) );
panel.add( firstName );
panel.add( new JLabel("Last Name") );
JTextField lastName = new JTextField(10);
panel.add( lastName );
int result = JOptionPane.showConfirmDialog(
null, // use your JFrame here
panel,
"Enter Name",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if(result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
// Let Option Pane build the panel for you
Object[] msg = {"First Name:", firstName, "Last Name:", lastName};
result = JOptionPane.showConfirmDialog(
frame,
msg,
"Enter Name...",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
One problem with this approach is that focus will be on the OK button instead of the text field. To get around this you can use the RequestFocusListener found in Dialog Focus.

Can't figure out how to output result to JLabel instead of System.out.println

I'm stuck again trying to figure out how to out the button clicked to label1.
When I click button01 I get A printed out. I need it to print to the label1 though and say Folder A when A is pressed and B when B is pressed and so on. Any nudge in the right direction?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JFileCabinet extends JFrame {
private JButton button01 = new JButton("A");
private JButton button02 = new JButton("B");
private JButton button03 = new JButton("C");
private JButton button04 = new JButton("D");
private JButton button05 = new JButton("E");
private JButton button06 = new JButton("F");
private JButton button07 = new JButton("G");
private JButton button08 = new JButton("H");
private JButton button09 = new JButton("I");
private JButton button10 = new JButton("J");
private JButton button11 = new JButton("K");
private JButton button12 = new JButton("L");
private JButton button13 = new JButton("M");
private JButton button14 = new JButton("N");
private JButton button15 = new JButton("O");
private JButton button16 = new JButton("P");
private JButton button17 = new JButton("Q");
private JButton button18 = new JButton("R");
private JButton button19 = new JButton("S");
private JButton button20 = new JButton("T");
private JButton button21 = new JButton("U");
private JButton button22 = new JButton("V");
private JButton button23 = new JButton("W");
private JButton button24 = new JButton("X");
private JButton button25 = new JButton("Y");
private JButton button26 = new JButton("Z");
private JButton button27 = new JButton(" ");
private JButton button28 = new JButton(" ");
private JButton button29 = new JButton(" ");
private JButton button30 = new JButton(" ");
private static JLabel label1 = new JLabel("Folder ");
private JPanel panel01 = new JPanel(new GridLayout(1, 6));
private JPanel panel02 = new JPanel(new GridLayout(1, 6));
private JPanel panel03 = new JPanel(new GridLayout(1, 6));
private JPanel panel04 = new JPanel(new GridLayout(1, 6));
private JPanel panel05 = new JPanel(new GridLayout(1, 2));
private GridLayout layout = new GridLayout(5, 1, 5, 5);
public JFileCabinet() {
setLayout(layout);
add(panel01);
add(panel02);
add(panel03);
add(panel04);
add(panel05);
button01.addActionListener(new ButtonListener());
panel01.add(button01);
panel01.add(button02);
panel01.add(button03);
panel01.add(button04);
panel01.add(button05);
panel01.add(button06);
panel02.add(button07);
panel02.add(button08);
panel02.add(button09);
panel02.add(button10);
panel02.add(button11);
panel02.add(button12);
panel03.add(button13);
panel03.add(button14);
panel03.add(button15);
panel03.add(button16);
panel03.add(button17);
panel03.add(button18);
panel04.add(button19);
panel04.add(button20);
panel04.add(button21);
panel04.add(button22);
panel04.add(button23);
panel04.add(button24);
panel05.add(button25);
panel05.add(button26);
panel05.add(button27).setVisible(false);
panel05.add(button28).setVisible(false);
//panel05.add(button29).setVisible(false);
panel05.add(label1);
panel05.add(button30).setVisible(false);
setSize(400, 350);
setVisible(true);
}
public static void main(String[] args) {
JFileCabinet frame = new JFileCabinet();
}
String selection;
class ButtonListener implements ActionListener {
private String e;
public void actionPerformed(ActionEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
String clicked = null;
if (e.getActionCommand().equals("A")) { //clicked.equals("A");
System.out.println("A");
}
}
}
}
label1.setText("Folder " + e.getActionCommand());
The nudge - and not the full blown answer is this:
Go and read the public API for JLabel
Identify the method that sets the text on JLabel
Instead of checking for an A string value, just set the value of folder to the value of e.getActionCommand().

Categories