Related
I want to get the value from my Jframe textfield to another class.
Why does it not work in my example?
I've created a getter in the main JFrame class that returns me txtIP1, this is a Textfield inside my frame.
In the method bepaalklasse inside the secondary class i'm trying to get the content of my textfield txtIP1 and parse it to an integer so i can use it for the method.
Secondary Class
private int iKlasse_;
private String sKlasse_;
private JFrame JFrame;
public void setiKlasse_(int iKlasse_) {
this.iKlasse_ = iKlasse_;
}
public void BepaalKlasse() {
iKlasse_ = Integer.parseInt(JFrame.getTxtIP1().getText());
System.out.println("iKlasse_" + iKlasse_);
try {
if (JFrame.getTxtIP1().getText().isEmpty()) {
throw new IOException();
}
if ((iKlasse_ >= 0) && ((iKlasse_) <= 127)) {
sKlasse_ = "A Klasse";
} else if ((iKlasse_ > 127) && ((iKlasse_ <= 191))) {
sKlasse_ = "B Klasse";
} else if ((iKlasse_ > 191) && ((iKlasse_ <= 223))) {
sKlasse_ = "C Klasse";
} else if ((iKlasse_ > 223)) {
sKlasse_ = "N/B";
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Gelieve een cijfer in te voeren in het eerste vak", "Leeg IP veld!", JOptionPane.ERROR_MESSAGE);
}
}
public String getsKlasse_() {
return sKlasse_;
}
}
Main Class
private clsInput oInput = new clsInput();
static private clsKlasse oKlasse = new clsKlasse();
private String sKlasse;
protected int iGeselecteerd;
public JFrame() {
initComponents();
iniCombobox();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
txtaDisplay = new javax.swing.JTextArea();
btnKies = new javax.swing.JButton();
btnPrinten = new javax.swing.JButton();
txtIP1 = new javax.swing.JTextField();
txtIP2 = new javax.swing.JTextField();
txtIP3 = new javax.swing.JTextField();
txtIP4 = new javax.swing.JTextField();
cmbSubnetten = new javax.swing.JComboBox<>();
jLabel1 = new javax.swing.JLabel();
lblKlasse = new javax.swing.JLabel();
btnBerekenen = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txtaDisplay.setColumns(20);
txtaDisplay.setRows(5);
jScrollPane1.setViewportView(txtaDisplay);
btnKies.setText("Kies");
btnKies.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnKiesActionPerformed(evt);
}
});
btnPrinten.setText("Export");
jLabel1.setText("Klasse:");
btnBerekenen.setText("bereken");
btnBerekenen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBerekenenActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(txtIP1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIP2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIP3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIP4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(cmbSubnetten, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnKies, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblKlasse, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBerekenen))
.addComponent(btnPrinten))
.addContainerGap(35, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtIP1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIP2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIP3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIP4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnBerekenen, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbSubnetten, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnKies, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(lblKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnPrinten)
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnKiesActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DoorzendenCmb();
oInput.Subnetten();
}
private void btnBerekenenActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
InstellenKlasse();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnBerekenen;
private javax.swing.JButton btnKies;
private javax.swing.JButton btnPrinten;
private javax.swing.JComboBox<String> cmbSubnetten;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblKlasse;
public javax.swing.JTextField txtIP1;
private javax.swing.JTextField txtIP2;
private javax.swing.JTextField txtIP3;
private javax.swing.JTextField txtIP4;
private javax.swing.JTextArea txtaDisplay;
// End of variables declaration
public JTextField getTxtIP1() {
return txtIP1;
}
public JTextField getTxtIP2() {
return txtIP2;
}
public JTextField getTxtIP3() {
return txtIP3;
}
public JTextField getTxtIP4() {
return txtIP4;
}
private void iniCombobox() { //ini van Combobox (1-10)
for (int i = 0; i < 10; i++) {
cmbSubnetten.addItem(String.valueOf(i));
}
}
private void DoorzendenCmb() {
iGeselecteerd = Integer.parseInt(cmbSubnetten.getSelectedItem().toString());
oInput.setiGeselecteerd(iGeselecteerd);
}
private void InstellenKlasse(){
sKlasse = oKlasse.getsKlasse_();
lblKlasse.setText(sKlasse);
}
}
I have following Simple Utility Calculator
Now i want to apply some Junit Testing here.
I don't know how to perform a Junit testing on Gui.
So kindly help me out.
Code is:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package calculator;
import java.io.*;
import java.text.DecimalFormat;
/**
*
* #author owner
*/
public class Calculator_Utility extends javax.swing.JFrame {
/**
* Creates new form Calculator_Utility
*/
public Calculator_Utility() {
initComponents();UsePowerKw.setText("4.0");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void setComponentsName(){
AddButton.setName("Add");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
CostPerKW = new javax.swing.JLabel();
SelectAppliance = new javax.swing.JLabel();
PowerUsage = new javax.swing.JLabel();
NumberHoursUse = new javax.swing.JLabel();
TotalCostApp = new javax.swing.JLabel();
AddButton = new javax.swing.JButton();
CostPerKwTextField = new javax.swing.JTextField();
UsePowerKw = new javax.swing.JTextField();
HourUse = new javax.swing.JTextField();
CostApp = new javax.swing.JTextField();
AllTotal = new javax.swing.JLabel();
AllTotalApp = new javax.swing.JTextField();
SelectApp = new javax.swing.JComboBox<>();
Showfield = new javax.swing.JTextField();
GallonWater = new javax.swing.JLabel();
GallonWat = new javax.swing.JTextField();
Export = new javax.swing.JButton();
CostGallon = new javax.swing.JLabel();
CostGall = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
CostPerKW.setText("Cost Per KW Hour:");
SelectAppliance.setText("Select Appliance:");
PowerUsage.setText("Power Usage In KW Hours:");
NumberHoursUse.setText("Number of Hours use per day:");
TotalCostApp.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
TotalCostApp.setText("Total Cost For Appliance");
AddButton.setText("ADD");
AddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddButtonActionPerformed(evt);
}
});
CostPerKwTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CostPerKwTextFieldActionPerformed(evt);
}
});
UsePowerKw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UsePowerKwActionPerformed(evt);
}
});
AllTotal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
AllTotal.setText("Total of All Appliances");
SelectApp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Refrigerator", "Washer", "Dryer", "Freezer", "Air Conditioner" }));
SelectApp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SelectAppActionPerformed(evt);
}
});
GallonWater.setText("Gallon of Water:");
Export.setText("Export");
Export.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExportActionPerformed(evt);
}
});
CostGallon.setText("Cost Per Gallon:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(NumberHoursUse)
.addComponent(SelectAppliance)
.addComponent(PowerUsage)
.addComponent(CostPerKW))
.addComponent(CostGallon, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(GallonWater, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(4, 4, 4))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(AllTotal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(Export)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(TotalCostApp)
.addGap(4, 4, 4)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(AddButton)
.addGap(24, 24, 24))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AllTotalApp, CostApp, CostGall, CostPerKwTextField, GallonWat, HourUse, SelectApp, UsePowerKw});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostPerKW)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SelectAppliance)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PowerUsage)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(NumberHoursUse)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(GallonWater)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostGallon)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(TotalCostApp))
.addComponent(AddButton))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotal))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Export))
.addContainerGap())
);
pack();
}// </editor-fold>
//Declare Variables and intialize the variables
private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {
double answer;
double total = 0;
String s = SelectApp.getSelectedItem().toString();
//Check if user select "Washer" from drop down box, calculate usage with Gallon
if (s=="Washer") {
//DecimalFormat df= new DecimalFormat("#.##");
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
number4 = (int)((Double.parseDouble(GallonWat.getText())));
answer = number1*number2*number3;
total =+ answer;
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
}
//if user select any appliances other than washer calculate usage
else
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
answer = number1*number2*number3;
total =+ answer;
//Calculated amount is put into field
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
// TODO add your handling code here:
}
//Action listener/Events for JCombo. Pre-defined Power Usage for Each Appliacnes
private void SelectAppActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String s=SelectApp.getSelectedItem().toString();
double r=4;
double w=7;
double x=12;
double y=16;
double z=24;
if (s=="Refrigerator"){
UsePowerKw.setText(String.valueOf(r));
}
else if (s=="Washer") {UsePowerKw.setText(String.valueOf(w));}
else if (s=="Dryer") {UsePowerKw.setText(String.valueOf(x));}
else if (s=="Freezer") {UsePowerKw.setText(String.valueOf(y));}
else UsePowerKw.setText(String.valueOf(z));
}
private void UsePowerKwActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//If jComboBox1 = "Refrigerator" then set jTextField4 = 22
}
//Action Listener/Event creates Data.txt with output
private void ExportActionPerformed(java.awt.event.ActionEvent evt) {
File file = new File("Data.txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = Showfield.getText();
//"The quick brown fox" +
//System.getProperty("line.separator") +
//"jumps over the lazy dog.";
writer.write(contents);
} catch (IOException e) {
e.printStackTrace();
}
}
private void CostPerKwTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculator_Utility().setVisible(true);
}
});
}
public double number1, number2, number3, number4;
// Variables declaration - do not modify
private javax.swing.JButton AddButton;
private javax.swing.JLabel AllTotal;
private javax.swing.JTextField AllTotalApp;
private javax.swing.JTextField CostApp;
private javax.swing.JTextField CostGall;
private javax.swing.JLabel CostGallon;
private javax.swing.JLabel CostPerKW;
private javax.swing.JTextField CostPerKwTextField;
private javax.swing.JButton Export;
private javax.swing.JTextField GallonWat;
private javax.swing.JLabel GallonWater;
private javax.swing.JTextField HourUse;
private javax.swing.JLabel NumberHoursUse;
private javax.swing.JLabel PowerUsage;
private javax.swing.JComboBox<String> SelectApp;
private javax.swing.JLabel SelectAppliance;
private javax.swing.JTextField Showfield;
private javax.swing.JLabel TotalCostApp;
private javax.swing.JTextField UsePowerKw;
// End of variables declaration
}
Any testCase you can apply like proper working , (actual== expected Result) etc.
You can't test the GUI with JUnit. You can only test the methods.
For example you have a JButton with an actionListener witch calls the method calculate(1, 1):
JButton showDialogButton = new JButton("Text Button");
showDialogButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
calculate(1, 1);
}
});
private int calculate(int n1, int n2){
return n1 + n2;
}
Now, You cant test the JButton but you can test the method "calculate". We know that calculate(1, 1) will return us 2 so we test it:
assertEquals(2, calculate(1, 1));
This means, that you cannot "press the button with JUnit" but you can test the action the button does.
as part of my java learning I made a jForm using netbeans which contains three jTextFields for the user to enter some numbers and then the sum of those numbres is displayed in another jTextField. This is, of course, extremely easy, but I want to be able to do this without any buttons. I don't know how to "update" the sum everytime any of the 3 textfields is modified. Can anyone help me?
Here's my code (the form was done with netbeans in the design mode):
package sumfields;
public class Frame extends javax.swing.JFrame {
public Frame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
n1 = new javax.swing.JTextField();
n2 = new javax.swing.JTextField();
n3 = new javax.swing.JTextField();
sum = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("n1");
jLabel2.setText("n2");
jLabel3.setText("n3");
jLabel5.setText("result");
jButton1.setText("Opperate");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(jLabel5))
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int r=Integer.parseInt(n1.getText())+Integer.parseInt(n2.getText())+Integer.parseInt(n3.getText());
sum.setText(""+r);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField n1;
private javax.swing.JTextField n2;
private javax.swing.JTextField n3;
private javax.swing.JTextField sum;
// End of variables declaration
}
As #Reimeus suggested, you need to add Document Listener to each of your text fields. Since you're performing the addition in your jButton1ActionPerformed() method, I made the notification of the listeners call this method whenever there's a change to your text fields.
Note: Based on the comments, I've updated my code to include only one DocumentListener and also added a DocumentFilter to accept only numeric input. I also removed the button that was present in the original code to perform the summation
Here's your updated code:
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class Frame extends javax.swing.JFrame {
public Frame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
n1 = new javax.swing.JTextField();
n2 = new javax.swing.JTextField();
n3 = new javax.swing.JTextField();
sum = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
DocumentListener documentListener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
performSummation(null);
}
#Override
public void insertUpdate(DocumentEvent e) {
performSummation(null);
}
#Override
public void changedUpdate(DocumentEvent e) {
}
};
DocumentFilter numericFilter = new DocumentFilter(){
#Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
fb.insertString(offset, string.replaceAll("[^\\d]", ""), attr);
}
#Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
fb.replace(offset, length, text.replaceAll("[^\\d]", ""), attrs);
}
};
((AbstractDocument) n1.getDocument()).setDocumentFilter(numericFilter);
((AbstractDocument) n2.getDocument()).setDocumentFilter(numericFilter);
((AbstractDocument) n3.getDocument()).setDocumentFilter(numericFilter);
n1.getDocument().addDocumentListener(documentListener);
n2.getDocument().addDocumentListener(documentListener);
n3.getDocument().addDocumentListener(documentListener);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("n1");
jLabel2.setText("n2");
jLabel3.setText("n3");
jLabel5.setText("result");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void performSummation(java.awt.event.ActionEvent evt) {
int total = 0;
if(n1.getText().trim().length() > 0){
try{
total += Integer.parseInt(n1.getText());
}catch(NumberFormatException nbx){
}
}
if(n2.getText().trim().length() > 0){
try{
total += Integer.parseInt(n2.getText());
}catch(NumberFormatException nbx){
}
}
if(n3.getText().trim().length() > 0){
try{
total += Integer.parseInt(n3.getText());
}catch(NumberFormatException nbx){
}
}
sum.setText(""+total);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField n1;
private javax.swing.JTextField n2;
private javax.swing.JTextField n3;
private javax.swing.JTextField sum;
// End of variables declaration
}
A couple of pointers:
Never trust the input that comes from the user. There's a possibility that the user might enter an incorrect value (say something that is not an Integer). As such it is always a good idea to validate your input and check whether the input can be actually parsed. Keeping this in mind, I'ved updated your jButton1ActionPerformed() method
The other alternative is to use a Formatted Text Fields
What you are looking for is a DocumentListener.
Register a listener with each of your JTextFields n1, n2 and n3 and call your method jButton1ActionPerformed to update the result field.
This alternative approach uses a PropertyChangeListener and a FocusListener to update() a sum of values using JFormattedTextField.
You can use a focus listener or you can use a action listener to the input JTextField
Please bear with any mistakes that I make as I am still very new to Java. I am working on an assignment and I'm stuck. I need to create a java based GUI that can be used as a retail calculator. I have all the labels and fields done, and some of the ActionListener's as well, but I'm struggling with the final piece of the assignment.
I need to store the data that is entered into a table for future viewing. I have tried a JTable, and I can't seem to get it right. My code is below. Any help or suggestions would be greatly appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package my.numberaddition;
/**
*
* #author Andrew
*/
public class NumberAdditionUI extends javax.swing.JFrame {
/**
* Creates new form NumberAdditionUI
*/
public NumberAdditionUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
originalPrice = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
discountPercentage = new javax.swing.JTextField();
salePrice = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel5 = new javax.swing.JLabel();
itemName = new javax.swing.JTextField();
departmentName = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
scrollPane1 = new java.awt.ScrollPane();
jLabel7 = new javax.swing.JLabel();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton3.setText("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel1.setText("Original Price:");
originalPrice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
originalPriceActionPerformed(evt);
}
});
jLabel2.setText("Discount Percentage:");
discountPercentage.setToolTipText("");
discountPercentage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
discountPercentageActionPerformed(evt);
}
});
jLabel3.setText("Sale Price:");
jButton1.setText("Calculate");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Next Item");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel4.setText("Retail Calculator");
jLabel5.setText("Item Name:");
departmentName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Department", "Kitchen & Bath", "Mens Clothing", "Women's Clothing", "Electronics", "Hardware" }));
departmentName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
departmentNameActionPerformed(evt);
}
});
jLabel6.setText("Department:");
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel7.setText("Previously Calculated Items");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton3)
.addGap(19, 19, 19))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jButton2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(itemName, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(salePrice, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(discountPercentage, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(originalPrice, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(departmentName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel4)))
.addGroup(layout.createSequentialGroup()
.addGap(140, 140, 140)
.addComponent(jLabel7)))
.addGap(0, 114, Short.MAX_VALUE))
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(departmentName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel5))
.addComponent(itemName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(originalPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(discountPercentage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(9, 9, 9)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(salePrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addGap(33, 33, 33)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(scrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addContainerGap())
);
pack();
}// </editor-fold>
private void originalPriceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
originalPrice.setText("");
discountPercentage.setText("");
salePrice.setText("");
itemName.setText("");
departmentName.setSelectedIndex(0);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(originalPrice.getText());
num2 = (Float.parseFloat(discountPercentage.getText()))/100;
// Now we can perform the addition.
result = num1-(num1*num2);
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
salePrice.setText(String.valueOf(result));
}
private void departmentNameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void discountPercentageActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NumberAdditionUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox departmentName;
private javax.swing.JTextField discountPercentage;
private javax.swing.JTextField itemName;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField originalPrice;
private javax.swing.JTextField salePrice;
private java.awt.ScrollPane scrollPane1;
// End of variables declaration
}
The best way to deal with tables is to create a TableModel class that extends AbstractTableModel.
All data manipulation should be done in the table model object. When data is changed you should call some of the fireTable* methods.
So, from my previous question I decided to go ahead and use the list as recommended (Thank you for that).
I've got a single class now that uses a list. This list is updated through the button. When a user presses on the button, values within the textfield are parsed to double and saved into the list. I am trying to create a method to be placed into the button that will print out the list.
import java.util.ArrayList;
public class foodDept extends javax.swing.JFrame {
ArrayList<MyShoppingCart> list = new ArrayList<MyShoppingCart>();
public foodDept() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
appleLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
cartArea = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
appleField = new javax.swing.JTextField();
bananaField = new javax.swing.JTextField();
addTocart = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
appleLabel.setText("Apple ($1.99):");
cartArea.setColumns(20);
cartArea.setRows(5);
jScrollPane1.setViewportView(cartArea);
cartArea.setEditable(false);
jLabel1.setText("Banana ($0.99):");
addTocart.setText("Add to Cart");
addTocart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTocartActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(appleLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(appleField)
.addGap(44, 44, 44))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addTocart)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(bananaField, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(appleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(appleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bananaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
.addComponent(addTocart))
.addComponent(jScrollPane1))
.addContainerGap())
);
pack();
}// </editor-fold>
**// HEEEEEEERRRRRRRRRRRREEEEEEEEEEEEEEEEEEEEEE
void printList() {
cartArea.setText("");
for (int i = 0; i < list.length; i++){
cartArea.append(list[i].toString());
}//******** ^ THIS IS THE METHOD IM TALKING ABOUT (printList)^*******
}**
**private void addTocartActionPerformed(java.awt.event.ActionEvent evt) {
double a = Double.parseDouble(appleField.getText());
list.add(new MyShoppingCart(a));
double b = Double.parseDouble(bananaField.getText());
list.add(new MyShoppingCart(b));
appleField.setText("");
bananaField.setText("");
printList();
} //where the values are parsed**
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new foodDept().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton addTocart;
private javax.swing.JTextField appleField;
private javax.swing.JLabel appleLabel;
private javax.swing.JTextField bananaField;
private javax.swing.JTextArea cartArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
You try to use List as an Array, but it's wrong.
Use next:
for (int i = 0; i < list.size(); i++){
cartArea.append(list.get(i).toString());
}
list.size() like a array.length
and list.get(i) as array[i]
Read tutorial for List.