I want this code work with update JProgressBar and JTextArea while scanner is working, but I don't know how implement Threading. Is it possible?
This is my code:
UPDATED: It's a working version now, with "Stop" function. I added a "breakPoint" variable to break out from the for loop.
package main;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
public class PortScanner extends javax.swing.JFrame {
private doSomeStuff taskPortScanner;
private boolean breakPoint;
public PortScanner() {
initComponents();
}
private void portScan() {
int currentPort = 1;
try {
String hostname = hostNameTextField.getText();
int timeOut = (Integer) timeOutSpinner.getValue();
int minPort = Integer.parseInt(portMinTextField.getText());
int maxPort = Integer.parseInt(portMaxTextField.getText());
//set min and max value of progress bar
jProgressBar1.setMinimum(minPort);
jProgressBar1.setMaximum(maxPort);
//print out the address
InetAddress theAddress = InetAddress.getByName(hostname);
resultTextArea.append("IP adress: " + theAddress + "\n\n");
//check if port is open
for (currentPort = minPort; currentPort <= maxPort; currentPort++) {
//stop for loop
if (breakPoint == true) {
System.out.println("Portscanning stopped.");
break;
}
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostname, currentPort), timeOut);
//update textarea
resultTextArea.append("Service running on port " + currentPort + "\n");
socket.close();
} catch (Exception ex) {
System.out.println(currentPort);
}
//update progressbar
jProgressBar1.setValue(currentPort);
jProgressBar1.repaint();
}
} catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Unknown hostname: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Invalid format. " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
private class doSomeStuff extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() throws Exception {
portScan();
return null;
}
#Override
public void done() {
//if thread is done enable start and clear buttons
clearButton.setEnabled(true);
startButton.setEnabled(true);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
hostNameTextField = new javax.swing.JTextField();
portMinTextField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
resultTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
clearButton = new javax.swing.JButton();
portMaxTextField = new javax.swing.JTextField();
jProgressBar1 = new javax.swing.JProgressBar();
timeOutSpinner = new javax.swing.JSpinner();
jLabel4 = new javax.swing.JLabel();
stopButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Simple port scanner");
setResizable(false);
jLabel1.setText("Hostname");
jLabel2.setText("Timeout");
jLabel3.setText("Port range");
hostNameTextField.setToolTipText("Type a hostname like www.google.com");
portMinTextField.setText("1");
resultTextArea.setColumns(20);
resultTextArea.setRows(5);
jScrollPane1.setViewportView(resultTextArea);
startButton.setText("Scan");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
clearButton.setText("Clear");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
portMaxTextField.setText("1000");
jProgressBar1.setStringPainted(true);
timeOutSpinner.setModel(new javax.swing.SpinnerNumberModel(15, 0, 999999, 1));
jLabel4.setText("-");
stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(hostNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(timeOutSpinner)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addGap(12, 12, 12)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(startButton)
.addGap(18, 18, 18)
.addComponent(stopButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(clearButton)
.addGap(32, 32, 32))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(hostNameTextField, 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(jLabel2)
.addComponent(timeOutSpinner, 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(jLabel3)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton)
.addComponent(clearButton)
.addComponent(stopButton))
.addContainerGap())
);
pack();
}// </editor-fold>
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = false;
taskPortScanner = new doSomeStuff();
taskPortScanner.execute();
startButton.setEnabled(false);
clearButton.setEnabled(false);
System.out.println("Starting portscanner...");
}
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
resultTextArea.setText(null);
jProgressBar1.setValue(0);
System.out.println("Clearing results...");
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = true;
startButton.setEnabled(true);
clearButton.setEnabled(true);
}
/**
* #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(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortScanner.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 PortScanner().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton clearButton;
private javax.swing.JTextField hostNameTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField portMaxTextField;
private javax.swing.JTextField portMinTextField;
private javax.swing.JTextArea resultTextArea;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
private javax.swing.JSpinner timeOutSpinner;
// End of variables declaration
}
You need to look at moving the long running scan task out of the Event dispatching thread to keep the UI responsive. Look at using a Swing Worker to achieve this.
http://en.wikipedia.org/wiki/SwingWorker#The_event_dispatching_thread_problem
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
Related
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
}
i wanted to choose a file from harddisk which contain a matrix.....and i want to save it in an 2d array..but whenever i choose the file,my app hangs and i cant abble to press any other buttons
Here is my sample:
public class Flood extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public static int[][] multi;
public Flood() {
initComponents();
browseB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
switch (fc.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION:
File file = fc.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Flood.class.getName()).log(Level.SEVERE, null, ex);
}
int row = 0;
int col = 0;
while (input.hasNextLine()) {
++row;
Scanner colReader = new Scanner(input.nextLine());
while (colReader.hasNextInt()) {
++col;
}
}
multi = new int[row][col];
input.close();
{
try {
input = new Scanner(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Flood.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (input.hasNextInt()) {
multi[i][j] = input.nextInt();
}
}
}
break;
}
}
});
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
for(int i=0;i<multi.length;i++)
{
for(int j=0;j<multi[0].length;j++)
{
System.out.println(""+multi[i][j]);
}
}
}
});
}
/**
* 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();
browseTF = new javax.swing.JTextField();
browseB = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
browseB.setText("Browse");
browseB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseBActionPerformed(evt);
}
});
jLabel1.setText("number of 0 :-");
jLabel2.setText("0");
jLabel3.setText("number of 1 :-");
jLabel4.setText("0");
jButton1.setText("go");
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(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(browseTF, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseB))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.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)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(159, 159, 159)
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(browseTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(browseB))
.addGap(7, 7, 7)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(176, Short.MAX_VALUE))
);
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(24, 24, 24)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
layout.setVerticalGroup(
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(18, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void browseBActionPerformed(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(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Flood.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 Flood().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton browseB;
private javax.swing.JTextField browseTF;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
Thanks in Advance
You have an infinite loop here:
while (colReader.hasNextInt()) {
++col;
}
You are not advancing the colReader Scanner at all, so it is forever looking at the first int value on the line.
You can fix it by moving past each int value as you encounter it:
while (colReader.hasNextInt()) {
colReader.nextInt();
++col;
}
In the future, you can solve a problem like this on your own by using a debugger to check where your program is stuck, or, if you’re running on the command line, by forcing Java to print a stack trace for each active thread using Ctrl-Break on Windows or Ctrl-\ (SIGQUIT) on Linux and OS X.
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();
}
}
}
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()
}
}
});
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.