how to get the text from a text field to a variable? - java

i want to get the value from the txt field val1 and val2 and store it in the variables n1 and n2. then n1 and n2 will be parsed to get the value for the calculator. here is the code:
public class CalcUI extends javax.swing.JFrame {
String n1 = val1.getText();
String n2 = val2.getText();
double num1 = Double.parseDouble(n1);
double num2 = Double.parseDouble(n2);
/**
* Creates new form CalcUI
*/
public CalcUI() {
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() {
val1 = new javax.swing.JTextField();
val2 = new javax.swing.JTextField();
plus = new javax.swing.JButton();
multiply = new javax.swing.JButton();
clr = new javax.swing.JButton();
exit = new javax.swing.JButton();
minus = new javax.swing.JButton();
divide = new javax.swing.JButton();
ans = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
plus.setText("+");
plus.setMaximumSize(new java.awt.Dimension(41, 41));
plus.setMinimumSize(new java.awt.Dimension(41, 41));
plus.setPreferredSize(new java.awt.Dimension(41, 41));
plus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
plusActionPerformed(evt);
}
});
multiply.setText("*");
multiply.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
multiplyActionPerformed(evt);
}
});
clr.setText("Clear");
clr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clrActionPerformed(evt);
}
});
exit.setText("Exit");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
minus.setText("-");
minus.setMaximumSize(new java.awt.Dimension(41, 41));
minus.setMinimumSize(new java.awt.Dimension(41, 41));
minus.setPreferredSize(new java.awt.Dimension(41, 41));
minus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
minusActionPerformed(evt);
}
});
divide.setText("/");
divide.setMaximumSize(new java.awt.Dimension(41, 41));
divide.setMinimumSize(new java.awt.Dimension(41, 41));
divide.setPreferredSize(new java.awt.Dimension(41, 41));
divide.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divideActionPerformed(evt);
}
});
ans.setBorder(javax.swing.BorderFactory.createEtchedBorder());
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(val1)
.addComponent(val2)
.addGroup(layout.createSequentialGroup()
.addComponent(clr)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(exit)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(134, 134, 134)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(multiply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(plus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(minus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(divide, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(143, 143, 143))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(ans, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(val1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(val2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ans, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(clr)
.addComponent(exit))
.addContainerGap())
);
pack();
}// </editor-fold>
private void plusActionPerformed(java.awt.event.ActionEvent evt) {
double add = num1 + num2;
ans.setText(Double.toString(add));
// TODO add your handling code here:
}
private void minusActionPerformed(java.awt.event.ActionEvent evt) {
double min = num1 - num2;
ans.setText(Double.toString(min));
// TODO add your handling code here:
}
private void divideActionPerformed(java.awt.event.ActionEvent evt) {
double div = num1 / num2;
ans.setText(Double.toString(div));
// TODO add your handling code here:
}
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
// TODO add your handling code here:
}
private void clrActionPerformed(java.awt.event.ActionEvent evt) {
val1.setText("");
val2.setText("");
ans.setText("");
// TODO add your handling code here:
}
private void multiplyActionPerformed(java.awt.event.ActionEvent evt) {
double mult = num1 * num2;
ans.setText(Double.toString(mult));
// 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(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CalcUI.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 CalcUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel ans;
private javax.swing.JButton clr;
private javax.swing.JButton divide;
private javax.swing.JButton exit;
private javax.swing.JButton minus;
private javax.swing.JButton multiply;
private javax.swing.JButton plus;
private javax.swing.JTextField val1;
private javax.swing.JTextField val2;
// End of variables declaration
}
the problem is that in the declaration
String n1 = val1.getText();
String n2 = val2.getText();
i get an error whioch says illegal forward reference. how do i fix this?
this was fixed.
now when i use the following code:
public class CalcUI extends javax.swing.JFrame {
Double num1 ;
Double num2 ;
/**
* Creates new form CalcUI
*/
public CalcUI(){
val1 = new javax.swing.JTextField();
val2 = new javax.swing.JTextField();
num1 = Double.parseDouble(val1.getText());
num2 = Double.parseDouble(val2.getText());
initComponents();
}
i get a build error which says:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at CalcUI.<init>(CalcUI.java:24)
at CalcUI$7.run(CalcUI.java:227)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
how do i fix this? what is wrong with the code?

I imagine your JTextField components will not have been initialised by the time you are calling:
String n1 = val1.getText();
String n2 = val2.getText();

If you use this code you will see what your input is.
private void yourActionButtonActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null,yourTextField.getText());
}
So, this should store your data to n1.
private void yourActionButtonActionPerformed(java.awt.event.ActionEvent evt) {
String n1;
n1 = yourTextField.getText();
}

You're missing the "equals" button that will do the computation. Add a listener to that button, and in the listener's actionPerformed() you getText() and then compute the calculation. Also, I guess there's no need to have n1 and n2 as class-level variables.

Related

When I input a number into jTextField1, the case does not get acted upon

eg. I input 1 into combobox and 50 into jTextField1 and the correct answer won't come out. It is going to be code that runs an application to convert chosen temperature ie. celcius, fairenheit or kelvin into the desired choice. For now I'm just trying out with this format of the choices between 1 and 4. I will change it later. Jbutton1 is the button to convert and when clicked should enact all the code within it. but for some reason it does not want to enact on the case that I defined earlier on. It should take the inputted temperature and add 273 to it.
public class Conversion extends javax.swing.JFrame {
int calculation = 0;
String temphold;
double input_temp;
/**
* Creates new form Conversion
*/
public Conversion() {
initComponents();
}
public void cases() {
switch (calculation) {
case 1:
input_temp = input_temp + 273.5;
break;
}
}
/**
* 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() {
jTextField1 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("jTextField1");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4" }));
jButton1.setText("jButton1");
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()
.addGap(126, 126, 126)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(207, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(113, 113, 113))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(67, 67, 67))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(50, 50, 50))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
temphold = (String) jComboBox1.getSelectedItem();
String hold = jTextField1.getText();
input_temp = Double.parseDouble(hold);
if (temphold == "1") {
calculation = 1;
System.out.println("monkey");
System.out.println(input_temp);
}
}
/**
* #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(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Conversion.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 Conversion().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

RMI ClassCastException to remote interface

Hi i am having a problem with RMI.
I have this error when i run it.
java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to rmi.converter
This is the interface
converter.java
import java.rmi.RemoteException;
public interface converter {
double CelciusKelvin (double a) throws RemoteException;
double CelciusFahrenheit (double a) throws RemoteException;
double FahrenheitKelvin (double a) throws RemoteException;
double FahrenheitCelcius (double a) throws RemoteException;
double KelvinCelcius (double a) throws RemoteException;
double KelvinFahrenheit (double a) throws RemoteException;
double AtmosPascal (double a) throws RemoteException;
double AtmosPSI (double a) throws RemoteException;
double PascalAtmos (double a) throws RemoteException;
double PascalPSI (double a) throws RemoteException;
double PSIAtmos (double a) throws RemoteException;
double PSIPascal (double a) throws RemoteException;
}
This is the remote method
converterImp.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class converterImp extends UnicastRemoteObject implements converter {
public converterImp() throws RemoteException
{
}
double convert;
#Override
public double CelciusKelvin(double a) throws RemoteException {
convert = a+273.15;
return convert;
}
#Override
public double CelciusFahrenheit(double a) throws RemoteException {
convert = (a*1.8)+32;
return convert;
}
#Override
public double FahrenheitKelvin(double a) throws RemoteException {
convert = (a+459.67)*5/9;
return convert;
}
#Override
public double FahrenheitCelcius(double a) throws RemoteException {
convert=(a-32)/(9/5);
return convert;
}
#Override
public double KelvinCelcius(double a) throws RemoteException {
convert = a - 273.15;
return convert;
}
#Override
public double KelvinFahrenheit(double a) throws RemoteException {
convert=(a-273.15)* 1.8 + 32.00;
return convert;
}
#Override
public double AtmosPascal(double a) throws RemoteException {
convert = a*101325;
return convert;
}
#Override
public double AtmosPSI(double a) throws RemoteException {
convert = a*14.6959488;
return convert;
}
#Override
public double PascalAtmos(double a) throws RemoteException {
convert = a/101325;
return convert;
}
#Override
public double PascalPSI(double a) throws RemoteException {
convert=a*0.000145037;
return convert;
}
#Override
public double PSIAtmos(double a) throws RemoteException {
convert = a*0.0680459639;
return convert;
}
#Override
public double PSIPascal(double a) throws RemoteException {
convert =a*6894.75729;
return convert;
}
}
This is my GUI Client.
package projectrmiclient;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmi.converter;
public class ProjectRMIClient extends javax.swing.JFrame {
public ProjectRMIClient() {
initComponents();
}
String num = "";
String str = "";
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
jButton21 = new javax.swing.JButton();
jButton22 = new javax.swing.JButton();
jButton23 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextPane1.setEditable(false);
jScrollPane1.setViewportView(jTextPane1);
jButton1.setText("1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("3");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("4");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("5");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("6");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton7.setText("7");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setText("8");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton9.setText("9");
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton10.setText("0");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
jButton11.setText("Cancel");
jButton11.setToolTipText("");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jLabel1.setText("Temperature");
jButton12.setText("C~F");
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
jButton13.setText("F~C");
jButton14.setText("K~C");
jButton15.setText("C~K");
jButton16.setText("F~K");
jButton17.setText("K~F");
jButton18.setText("A~PSI");
jButton19.setText("PSI~A");
jButton20.setText("Pas~A");
jButton21.setText("A~Pas");
jButton22.setText("PSI-Pas");
jButton22.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton22ActionPerformed(evt);
}
});
jButton23.setText("Pas~A");
jLabel2.setText("Pressure");
jLabel3.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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton11)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(36, 36, 36)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton23, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton14, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel2))
.addContainerGap(20, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3)
.addComponent(jButton2)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(jButton5)
.addComponent(jButton6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7)
.addComponent(jButton8)
.addComponent(jButton9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton11)
.addComponent(jButton10))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton15)
.addComponent(jButton12))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton16)
.addComponent(jButton13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton17)
.addComponent(jButton14))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton18)
.addComponent(jButton21))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton22)
.addComponent(jButton19))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton20)
.addComponent(jButton23))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {
jTextPane1.setText("");
}
private void jButton22ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// fire to localhost port 1099
Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", 1099);
// search for myMessage service
converter impl = (converter) myRegistry.lookup("PTConverter");
if(!jTextPane1.getText().isEmpty())
{
double input = Double.parseDouble(jTextPane1.getText());
// call server's method
double result=impl.CelciusFahrenheit(input);
String answer = result + "Fahrenheit";
jLabel4.setText(answer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #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(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProjectRMIClient.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 ProjectRMIClient().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton20;
private javax.swing.JButton jButton21;
private javax.swing.JButton jButton22;
private javax.swing.JButton jButton23;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
I developed the GUI using GUI Builder on netbeans.
The problem is when i pressed jButton12. it will show the error as stated.
You appear to have created a copy of your remote interface in a different package for the client. You can't do that. The remote interface has to be the same on both sides: The Same, and that does not include changing its package, or indeed any anything else.

getText from GUI textfield error in java

I am doing a project where I have to convert a fraction into its lowest terms. I am experiencing errors with .getText from a JTextField. I printed their input and the input is being received as the properties rather than as a string. I am having problems with this code:
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
this give the variable a value of
javax.swing.JTextField[,12,93,166x36,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#c112a58,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
I was wondering if any problems could be caused by me using a GUI form or a key released listener.
Here is the full code separated into two classes:
package reducefraction;
public class ReduceFraction {
public static void main(String[] args) {
NewJFrame form = new NewJFrame();
form.setVisible(true);
form.setLocationRelativeTo(null);
}
}
Here is the second class
package reducefraction;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
userDenominatorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userDenominatorInputKeyReleased(evt);
}
});
userNumeratorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userNumeratorInputKeyReleased(evt);
}
});
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
userDenominatorInput = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
numeratorOutput = new javax.swing.JTextField();
denominatorOutput = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
userNumeratorInput = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Reduce Fractions");
jLabel2.setText("This program will reduce a fraction to its lowest terms");
userDenominatorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userDenominatorInput.setForeground(new java.awt.Color(255, 102, 51));
numeratorOutput.setEditable(false);
numeratorOutput.setColumns(10);
numeratorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
numeratorOutput.setForeground(new java.awt.Color(255, 102, 51));
denominatorOutput.setEditable(false);
denominatorOutput.setColumns(10);
denominatorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
denominatorOutput.setForeground(new java.awt.Color(255, 102, 51));
jLabel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
jLabel3.setText("=");
userNumeratorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userNumeratorInput.setForeground(new java.awt.Color(255, 102, 51));
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(155, 155, 155)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jLabel2)))
.addGap(0, 82, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(userNumeratorInput))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator2)
.addComponent(denominatorOutput, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(numeratorOutput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(userNumeratorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(denominatorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(numeratorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)))
.addGap(22, 22, 22))
);
pack();
}// </editor-fold>
**public void userDenominatorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
public void userNumeratorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
public void calculate(double userNumerator, double userDenominator) {
System.out.println(userNumeratorInput);
double a = userDenominator;
double b = userNumerator % userDenominator;
double c;
do {
c = a % b;
a = b;
b = c;
} while (a != 0);
int greatestCommonDenominator = (int) c;
double numeratorAnswer = userNumerator / greatestCommonDenominator;
double denominatorAnswer = userDenominator / greatestCommonDenominator;
numeratorOutput.setText(Double.toString(numeratorAnswer));
denominatorOutput.setText(Double.toString(denominatorAnswer));
}**
/**
* #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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField denominatorOutput;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField numeratorOutput;
public javax.swing.JTextField userDenominatorInput;
private javax.swing.JTextField userNumeratorInput;
// End of variables declaration
}
The "probable" cause is the use of KeyListener on the text fields.
The main problem is you are not taking into account what should occur if one of the fields is empty, "" is not a valid number.
Don't use KeyListeners on text fields, if you want to perform real time updates on fields, you should be using a DocumentListener instead. KeyListener won't be notified if the the user pastes content into the field...
You should also consider using a JSpinner or a JFormattedField or even a DocumentFilter to restrict what the user can actually type into the fields
Something like...
if (!userDenominatorInput.getText().isEmpty() && !userNumeratorInput.getText().isEmpty()) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
Should help...
MadProgrammer gave me the answer I needed that was causing the output of properties rather than a string. This Problem is solved by doing the .getText method as described here:
Don't use System.out.println(userNumeratorInput), it's calling userNumeratorInput.toString()which prints the properties of the text field, use ystem.out.println(userNumeratorInput.getText()) to print the text content of the field – MadProgrammer
Here is the correct code from my form class
package reducefraction;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class NewJFrame extends javax.swing.JFrame {
double userDenominator, userNumerator;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
// userDenominatorInput.addActionListener(new MyTextActionListener());
userDenominatorInput.getDocument().addDocumentListener(new MyDocumentListener());
userDenominatorInput.getDocument().putProperty("name", "Text Field");
/* userDenominatorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userDenominatorInputKeyReleased(evt);
}
});
*/
// userNumeratorInput.addActionListener(new MyTextActionListener());
userNumeratorInput.getDocument().addDocumentListener(new MyDocumentListener());
userNumeratorInput.getDocument().putProperty("name", "Text Field");
/*
userNumeratorInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
userNumeratorInputKeyReleased(evt);
}
});
*/
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
userDenominatorInput = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
numeratorOutput = new javax.swing.JTextField();
denominatorOutput = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
userNumeratorInput = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Reduce Fractions");
jLabel2.setText("This program will reduce a fraction to its lowest terms");
userDenominatorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userDenominatorInput.setForeground(new java.awt.Color(255, 102, 51));
numeratorOutput.setEditable(false);
numeratorOutput.setColumns(10);
numeratorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
numeratorOutput.setForeground(new java.awt.Color(255, 102, 51));
denominatorOutput.setEditable(false);
denominatorOutput.setColumns(10);
denominatorOutput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
denominatorOutput.setForeground(new java.awt.Color(255, 102, 51));
jLabel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
jLabel3.setText("=");
userNumeratorInput.setFont(new java.awt.Font("Gabriola", 1, 24)); // NOI18N
userNumeratorInput.setForeground(new java.awt.Color(255, 102, 51));
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(155, 155, 155)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jLabel2)))
.addGap(0, 82, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(userNumeratorInput))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator2)
.addComponent(denominatorOutput, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(numeratorOutput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(userNumeratorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(userDenominatorInput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(denominatorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(numeratorOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)))
.addGap(22, 22, 22))
);
pack();
}// </editor-fold>
/* public void userDenominatorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
*/
/* public void userNumeratorInputKeyReleased(java.awt.event.KeyEvent evt) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
*/
public void update() {
if (!userDenominatorInput.getText().isEmpty() && !userNumeratorInput.getText().isEmpty()) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
}
public void calculate(double userNumerator, double userDenominator) {
if (Double.toString(userNumerator).contains(".")) {
int decimalLocationuserNumerator = Double.toString(userNumerator).lastIndexOf(".");
String decimalsuserNumerator = Double.toString(userNumerator).substring(decimalLocationuserNumerator + 1, Double.toString(userNumerator).length());
int magnitudeUserNumerator = decimalsuserNumerator.length();
userNumerator = userNumerator * Math.pow(10, magnitudeUserNumerator);
userDenominator = userDenominator * Math.pow(10, magnitudeUserNumerator);
}
if (Double.toString(userDenominator).contains(".")) {
int decimalLocationUserDenominator = Double.toString(userDenominator).lastIndexOf(".");
String decimalsUserDenominator = Double.toString(userDenominator).substring(decimalLocationUserDenominator + 1, Double.toString(userDenominator).length());
int magnitudeUserDenominator = decimalsUserDenominator.length();
userDenominator = userDenominator * Math.pow(10, magnitudeUserDenominator);
userNumerator = userNumerator * Math.pow(10, magnitudeUserDenominator);
}
double a = userNumerator;
double b = userDenominator;
double c = a % b;
while (c > 1) {
c = a % b;
a = b;
b = c;
}
int greatestCommonDenominator = (int) a;
int numeratorAnswer = (int) userNumerator / greatestCommonDenominator;
int denominatorAnswer = (int) userDenominator / greatestCommonDenominator;
numeratorOutput.setText(Integer.toString(numeratorAnswer));
denominatorOutput.setText(Integer.toString(denominatorAnswer));
}
/**
* #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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField denominatorOutput;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField numeratorOutput;
public javax.swing.JTextField userDenominatorInput;
private javax.swing.JTextField userNumeratorInput;
// End of variables declaration
private class MyDocumentListener implements DocumentListener {
public MyDocumentListener() {
}
#Override
public void insertUpdate(DocumentEvent de) {
update();
}
#Override
public void removeUpdate(DocumentEvent de) {
update();
}
#Override
public void changedUpdate(DocumentEvent de) {
update();
}
}
}

How do I Calculate the Average using the CalculateButton with following code for a KDRCalculator Program

In the following code I don't know how to find the average using the Calculate Button. I have managed to read the text in through Text fields for the values but i don't know how to make the program calculate the average and print it in the textfield once the Calculate Button has been clicked.
import java.util.Scanner;
public class KdrCalGui extends javax.swing.JFrame {
/**
* Creates new form KdrCalGui
*/
public KdrCalGui() {
initComponents();
double kills;
double deaths;
double subtotal;
double roundnumber;
}
/**
* 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() {
KillsValue = new javax.swing.JTextField();
KillsLabel = new javax.swing.JLabel();
DeathsValue = new javax.swing.JLabel();
DeathsLabel = new javax.swing.JTextField();
CalculateButton = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
Display = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
KillsValue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
KillsValueActionPerformed(evt);
}
});
KillsLabel.setText("Kills");
DeathsValue.setText("Deaths");
DeathsLabel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeathsLabelActionPerformed(evt);
}
});
CalculateButton.setText("Calculate");
CalculateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CalculateButtonActionPerformed(evt);
}
});
jLabel3.setText("Your KDR");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(CalculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeathsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeathsValue)
.addComponent(KillsValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KillsLabel))
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(Display, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(31, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {DeathsLabel, KillsValue});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(KillsLabel)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(KillsValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(DeathsValue)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DeathsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Display)))
.addGap(36, 36, 36)
.addComponent(CalculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(50, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void DeathsLabelActionPerformed(java.awt.event.ActionEvent evt) {
DeathsLabel.setText(DeathsLabel.getText());
double deaths;
Scanner sc= new Scanner(System.in);
deaths=sc.nextInt();
}
private void KillsValueActionPerformed(java.awt.event.ActionEvent evt) {
KillsLabel.setText(KillsLabel.getText());
double kills;
Scanner sc=new Scanner(System.in);
kills=sc.nextInt();
}
THIS IS THE CALCULATE BUTTON.
private void CalculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.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 KdrCalGui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton CalculateButton;
private javax.swing.JTextField DeathsLabel;
private javax.swing.JLabel DeathsValue;
private javax.swing.JTextField Display;
private javax.swing.JLabel KillsLabel;
private javax.swing.JTextField KillsValue;
private javax.swing.JLabel jLabel3;
// End of variables declaration
}
CalculateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == CalculateButton) {
// not sure what exactly you're trying to average
// but if it's the kills and deaths value, then...
int k = Integer.parseInt(KillsValue.getText());
int d = Integer.parseInt(DeathsValue.getText());
Display.setText((k+d)/2);
// think about adding exception handling in case they enter a noninteger
// also you switched the names of the TextField and Label in the initComponents()
}
}
});

Netbeans calculator error

I made a calculator in netbeans so far i added the plus and minus button to work. but lets say i do 5+5 it gives me 10 and if i add 5 more it give 15. so that parts correct. but if i do 9-5 it gives me -4, and if i subtrac 2 from the -4 i get positive 6. please help, im fairly new to java.
public class Calculator extends javax.swing.JFrame {
/**
* Creates new form Calculator
*/
public Calculator() {
initComponents();
}
double fNums = 0.0;
double sNums = 0.0;
boolean add = false;
boolean sub = false;
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
display = new javax.swing.JTextField();
seven = new javax.swing.JButton();
eight = new javax.swing.JButton();
nine = new javax.swing.JButton();
plus = new javax.swing.JButton();
four = new javax.swing.JButton();
five = new javax.swing.JButton();
six = new javax.swing.JButton();
minus = new javax.swing.JButton();
one = new javax.swing.JButton();
two = new javax.swing.JButton();
three = new javax.swing.JButton();
multiply = new javax.swing.JButton();
zero = new javax.swing.JButton();
decimal = new javax.swing.JButton();
divide = new javax.swing.JButton();
enter = new javax.swing.JButton();
clear = new javax.swing.JButton();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu4 = new javax.swing.JMenu();
Home = new javax.swing.JMenuItem();
jMenu5 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
display.setEditable(false);
seven.setText("7");
seven.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sevenActionPerformed(evt);
}
});
eight.setText("8");
eight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eightActionPerformed(evt);
}
});
nine.setText("9");
nine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nineActionPerformed(evt);
}
});
plus.setText("+");
plus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
plusActionPerformed(evt);
}
});
four.setText("4");
four.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fourActionPerformed(evt);
}
});
five.setText("5");
five.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fiveActionPerformed(evt);
}
});
six.setText("6");
six.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sixActionPerformed(evt);
}
});
minus.setText("-");
minus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
minusActionPerformed(evt);
}
});
one.setText("1");
one.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
oneActionPerformed(evt);
}
});
two.setText("2");
two.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
twoActionPerformed(evt);
}
});
three.setText("3");
three.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
threeActionPerformed(evt);
}
});
multiply.setText("*");
multiply.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
multiplyActionPerformed(evt);
}
});
zero.setText("0");
zero.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zeroActionPerformed(evt);
}
});
decimal.setText(".");
decimal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
decimalActionPerformed(evt);
}
});
divide.setText("/");
divide.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divideActionPerformed(evt);
}
});
enter.setText("Enter");
enter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enterActionPerformed(evt);
}
});
clear.setText("C");
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(clear, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(enter, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(one, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(two, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(three, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(four, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(five, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(six, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(display)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(seven, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(eight, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nine, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(zero, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(decimal, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(display, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(seven, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(eight, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nine, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(four, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(five, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(six, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(one, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(two, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(three, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(zero, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(decimal, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(clear, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(enter, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(54, Short.MAX_VALUE))
);
jMenu4.setText("File");
Home.setText("Home");
Home.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HomeActionPerformed(evt);
}
});
jMenu4.add(Home);
jMenuBar2.add(jMenu4);
jMenu5.setText("Edit");
jMenuBar2.add(jMenu5);
setJMenuBar(jMenuBar2);
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()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void HomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Menu m = new Menu();
m.setVisible(true);
}
private void sixActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + six.getText());
}
private void divideActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + divide.getText());
}
private void sevenActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + seven.getText());
}
private void eightActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + eight.getText());
}
private void nineActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + nine.getText());
}
private void plusActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
fNums = fNums + Double.parseDouble(display.getText());
display.setText("");
add = true;
}
private void fourActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + four.getText());
}
private void fiveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + five.getText());
}
private void minusActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
fNums = fNums - Double.parseDouble(display.getText());
display.setText("");
sub = true;
}
private void oneActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + one.getText());
}
private void twoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + two.getText());
}
private void threeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + three.getText());
}
private void multiplyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + multiply.getText());
}
private void zeroActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + zero.getText());
}
private void decimalActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText(display.getText() + decimal.getText());
}
private void enterActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your enter code here:
if(add = true){
sNums = fNums + Double.parseDouble(display.getText());
display.setText(String.valueOf(sNums));
fNums = 0;
add = false;
} else {
if(sub = true){
sNums = fNums + Double.parseDouble(display.getText());
display.setText(String.valueOf(sNums));
fNums = 0;
sub = false;
}
}
}
private void clearActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
display.setText("");
fNums = 0;
sNums = 0;
}
/**
* #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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculator.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().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Home;
private javax.swing.JButton clear;
private javax.swing.JButton decimal;
private javax.swing.JTextField display;
private javax.swing.JButton divide;
private javax.swing.JButton eight;
private javax.swing.JButton enter;
private javax.swing.JButton five;
private javax.swing.JButton four;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenu jMenu5;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton minus;
private javax.swing.JButton multiply;
private javax.swing.JButton nine;
private javax.swing.JButton one;
private javax.swing.JButton plus;
private javax.swing.JButton seven;
private javax.swing.JButton six;
private javax.swing.JButton three;
private javax.swing.JButton two;
private javax.swing.JButton zero;
// End of variables declaration
}
First: You are missing the == in enterActionPerformed. Use two = signs.
Second: If I understood correctly, everytime there's a '-', the number gets negated. Which is happening after the first number is written.
9-5 gives you 4 because you are negating the first number and adding it to the second:
(-9)+5 =-4
The error is in the following code, when you press the '-' button, you are doing 0-valueEntered.
private void minusActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
fNums = fNums - Double.parseDouble(display.getText());
display.setText("");
sub = true;
}
if(add == true){
sNums = fNums + Double.parseDouble(display.getText());
display.setText(String.valueOf(sNums));
fNums = 0;
add = false;
} else {
`
`if(sub == true){
sNums = fNums + Double.parseDouble(display.getText());
display.setText(String.valueOf(sNums));
fNums = 0;
sub = false;
}
}
You can check out my MathExpressionEvaluator repository from Github, as it can easily evaluate simple math expressions.
You can pass it a string expression from your calculator and display the answer that you get from it easily.
Change the Minus listener to
private void minusActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
fNums = Double.parseDouble(display.getText()); <----------
display.setText("");
sub = true;
}
and enter action performed as
private void enterActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your enter code here:
if(add == true){
sNums = fNums + Double.parseDouble(display.getText());
display.setText(String.valueOf(sNums));
fNums = 0;
add = false;
} else {
if(sub == true){
sNums = fNums - Double.parseDouble(display.getText()); <----------
display.setText(String.valueOf(sNums));
fNums = 0;
sub = false;
}
}
}
And Check

Categories