我想在标签中使用当前可用的值并使用数字添加(计算) 并显示在文本字段上但有错误
private void ch13ActionPerformed(java.awt.event.ActionEvent evt)
r1=Integer.parseInt(tLabel.getText()); //r2 and r1 are integers
// error .. It says "Void type not allowed here"
r2 = Integer.parseInt(tLabel.setText(String.valueOf("3")));
result=r1+r2;
creaditTxt.setText(result+"");
}
然后我该如何解决这个问题?
答案 0 :(得分:0)
setText()
返回void
。所以通过这样做
r2 = Integer.parseInt(tLabel.setText(String.valueOf("3")));
你说r2
=无效。那是不可能的。
您可能希望改为使用2个文本字段,并使用标签显示结果
public class AddFrame extends JFrame {
private JLabel result = new JLabel();
private JTextField number1 = new JTextField(10);
private JTextField number2 = new JTextField(10);
private JButton addBut = new JButton("Add");
public AddFrame(){
setLayout(new GridLayout(4, 1));
add(result);
add(number1);
add(number2);
add(addBut);
addBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int num1 = Integer.parseInt(number1.getText());
int num2 = Integer.parseInt(number2.gettext());
int total = num1 + num2;
result.setText(String.valueOf(total));
}
});
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
AddFrame frame = new AddFrame();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}