我正在做一个项目,我必须将一个分数转换为最低分。我遇到来自JTextField的.getText错误。我打印了他们的输入,输入作为属性而不是字符串接收。我遇到了这段代码的问题:
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
这给变量一个值
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]
我想知道使用GUI表单或密钥释放的监听器是否可能导致任何问题。
以下是分为两类的完整代码:
package reducefraction;
public class ReduceFraction {
public static void main(String[] args) {
NewJFrame form = new NewJFrame();
form.setVisible(true);
form.setLocationRelativeTo(null);
}
}
这是第二类
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
}
答案 0 :(得分:2)
&#34;可能&#34;原因是在文本字段中使用KeyListener
。
主要问题是你没有考虑如果其中一个字段为空,应该发生什么,&#34;&#34;不是有效的数字。
不要在文本字段上使用KeyListener
,如果要对字段执行实时更新,则应使用DocumentListener
。如果用户将内容粘贴到字段中,则KeyListener
不会收到通知...
您还应该考虑使用JSpinner
或JFormattedField
甚至DocumentFilter
来限制用户可以在字段中输入的内容
像...一样的东西。
if (!userDenominatorInput.getText().isEmpty() && !userNumeratorInput.getText().isEmpty()) {
double userDenominator = Double.parseDouble(userDenominatorInput.getText());
double userNumerator = Double.parseDouble(userNumeratorInput.getText());
calculate(userNumerator, userDenominator);
}
应该有所帮助......
答案 1 :(得分:0)
MadProgrammer给了我需要的答案,它导致属性的输出而不是字符串。通过执行此处描述的.getText方法来解决此问题:
不要使用System.out.println(userNumeratorInput),它调用userNumeratorInput.toString()打印文本字段的属性,使用ystem.out.println(userNumeratorInput。 getText())打印字段的文本内容 - MadProgrammer
以下是我的表单类
中的正确代码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();
}
}
}