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();
}
}
}
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 learning java and i am pretty new for it. I am trying to create a static profile window using swing. Also, the avatar picture should change depending on user and user information should be read from a text file. This code doesnt give a error but its because of avatarPath. I think the program thinks its non-static.
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author B_Ali
*/
public class ProfilePanel extends javax.swing.JFrame {
public static String avatarPath;
public static int x;
public static class UsersInfo{
public int userID;
public String userName;
public String userSurname;
public String userGender;
UsersInfo(String name, String surname, String gender){
userID = x;
userName = name;
userSurname = surname;
userGender = gender;
}
}
static UsersInfo permitedUser[];
public static void InfoReader()throws IOException{
#SuppressWarnings("UnusedAssignment")
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader("C:\\Users\\B_Ali\\Documents\\NetBeansProjects\\JavaApplication20\\UserInformation.txt"));
String s, s2 = new String();
while((s = in.readLine())!= null)
s2 += s + "\n";
#SuppressWarnings("UnusedAssignment")
String[] s1 = new String[100];
s1 = s2.split("\\s+");
in.close();
permitedUser[0] = new UsersInfo( s1[0] , s1[1], s1[2] );
permitedUser[1] = new UsersInfo ( s1[3], s1[4], s1[5] );
permitedUser[2] = new UsersInfo ( s1[6], s1[7], s1[8] );
} catch (FileNotFoundException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
public static void ProfilePanel() {
initComponents();
}
public static String AvatarPic(){
if( x == 0 ){
avatarPath = "\"/Users/hei_cosplay_darker_than_black_by_seras0victoria.jpg\"";
}
else if( x == 1 ){
avatarPath = "\"/Users/lyralei_the_windrunner_by_trungth-d5zhmc1.jpg\"";
}
else if( x == 2 ){
avatarPath = "\"/Users/shingeki_no_kyojin_by_asuka10-d6k762k.jpg\"";
}
return avatarPath;}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Avatar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(ProfilePanel.AvatarPic())));
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jScrollPane2.setName(""); // NOI18N
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
try {
ProfilePanel.InfoReader(); // TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText("Name: " +permitedUser[x].userName+ "\r\nSurname :"+permitedUser[x].userSurname+"\r\nGender :"+permitedUser[x].userGender);
jTextArea1.setDragEnabled(true);
jTextArea1.setMaximumSize(new java.awt.Dimension(2147483647, 120));
jTextArea1.setMinimumSize(new java.awt.Dimension(92, 120));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 120));
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
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(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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
*/
Scanner in = new Scanner(System.in);
x = in.nextInt();
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(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.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 ProfilePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
public javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
Edit: I changed code a bit and it gives error.
Edit2: what I am trying to do is creating users and their profiles. Profile will contain avatar image and 3 variable which are name, surname and gender. I want to display them with respect to users.
I am living problems with this codes;
static void AvatarPic(){
if( x == 0 ){
avatarPath = "\"/Users/hei_cosplay_darker_than_black_by_seras0victoria.jpg\"";
}
else if( x == 1 ){
avatarPath = "\"/Users/lyralei_the_windrunner_by_trungth-d5zhmc1.jpg\"";
}
else if( x == 2 ){
avatarPath = "\"/Users/shingeki_no_kyojin_by_asuka10-d6k762k.jpg\"";
}
}
and
ProfilePanel.AvatarPic();
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource(ProfilePanel.avatarPath)));
There are many problems in your code.
The initComponents() is not a static function .I guess in your static conversion you just replaced every function with public static .And the below is a constructor [I'm sure because it is a Netbeans generated one] and you have modified it also.No need to do that
public static void ProfilePanel() {
initComponents();
}
You can change it back to the way it was
public ProfilePanel() {
initComponents();
}
You'll get a java.lang.NullPointerException at
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(ProfilePanel.AvatarPic())));
because if you are using getResource you just have to specify the filename relative to the package.If you'll be loading from other location,then you have to change it like
jLabel1.setIcon(new javax.swing.ImageIcon(ProfilePanel.AvatarPic()));//file location
Also you have to give the absolute path
avatarPath = "D://hei_cosplay_darker_than_black_by_seras0victoria.jpg";
You'll again get a java.lang.NullPointerException at
permitedUser[0] = new UsersInfo(s1[0], s1[1], s1[2]);
because you haven't initialized the permitedUser anywhere.So you have to do it like
static UsersInfo permitedUser[]=new UsersInfo[3];
After making those changes and if you run it with 0 then BK201[Code Name Hei] will be on your screen
And Your Edited FullCode[Make change to ImageLocations]
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author B_Ali
*/
public class ProfilePanel extends javax.swing.JFrame {
public static String avatarPath;
public static int x;
public static class UsersInfo {
public int userID;
public String userName;
public String userSurname;
public String userGender;
UsersInfo(String name, String surname, String gender) {
userID = x;
userName = name;
userSurname = surname;
userGender = gender;
}
}
static UsersInfo permitedUser[] = new UsersInfo[3];//change 3
public static void InfoReader() throws IOException {
#SuppressWarnings("UnusedAssignment")
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader("C:\\Users\\B_Ali\\Documents\\NetBeansProjects\\JavaApplication20\\UserInformation.txt"));
String s, s2 = new String();
while ((s = in.readLine()) != null) {
s2 += s + "\n";
}
#SuppressWarnings("UnusedAssignment")
String[] s1 = new String[100];
s1 = s2.split("\\s+");
in.close();
permitedUser[0] = new UsersInfo(s1[0], s1[1], s1[2]);
permitedUser[1] = new UsersInfo(s1[3], s1[4], s1[5]);
permitedUser[2] = new UsersInfo(s1[6], s1[7], s1[8]);
} catch (FileNotFoundException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
//Change 1
public ProfilePanel() {
initComponents();
}
public static String AvatarPic() {
//change 2
if (x == 0) {
avatarPath = "D://hei_cosplay_darker_than_black_by_seras0victoria.jpg";
} else if (x == 1) {
avatarPath = "D://lyralei_the_windrunner_by_trungth-d5zhmc1.jpg";
} else if (x == 2) {
avatarPath = "D://shingeki_no_kyojin_by_asuka10-d6k762k.jpg";
}
return avatarPath;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Avatar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
//Change 2
jLabel1.setIcon(new javax.swing.ImageIcon(ProfilePanel.AvatarPic()));
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jScrollPane2.setName(""); // NOI18N
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
try {
ProfilePanel.InfoReader(); // TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText("Name: " + permitedUser[x].userName + "\r\nSurname :" + permitedUser[x].userSurname + "\r\nGender :" + permitedUser[x].userGender);
jTextArea1.setDragEnabled(true);
jTextArea1.setMaximumSize(new java.awt.Dimension(2147483647, 120));
jTextArea1.setMinimumSize(new java.awt.Dimension(92, 120));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 120));
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
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(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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
*/
Scanner in = new Scanner(System.in);
x = in.nextInt();
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(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.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 ProfilePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
public javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
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.