问题描述
虽然构建一个简单的货币转换器应用程序 setText 并没有在 JLabel 中设置值。(我在 Windows 中使用 eclipse ide)。我已经调用了 Action Listener 来设置按钮,并且还在 parseInt 的帮助下将 getText 转换为 int .
我的代码如下。
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class CurrencyConverter implements ActionListener {
JButton button1,button2;
JLabel display2,display3;
JTextField display;
public CurrencyConverter() {
var frame=new JFrame();
frame.setLayout(null);
frame.setBounds(300,300,400,300);
frame.getContentPane().setBackground(Color.BLACK);
display=new JTextField();
display.setBounds(50,30,50);
display.setBackground(Color.yellow);
display.setForeground(Color.black);
frame.add(display);
button1=new JButton("TO INR");
button1.setBounds(50,100,135,50);
frame.add(button1);
button2=new JButton("TO USD");
button2.setBounds(215,50);
frame.add(button2);
display2=new JLabel();
display2.setBounds(50,170,50);
display2.setBackground(Color.GREEN);
display2.setForeground(Color.BLACK);
display2.setopaque(true);
frame.add(display2);
frame.setVisible(true);
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new CurrencyConverter();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button1) {
int noIndisplay=Integer.parseInt(display.getText())*70;
display2.setText(""+noIndisplay);
}
else if(e.getSource()==button2) {
int noIndisplay=Integer.parseInt(display.getText())/70;
display2.setText(""+noIndisplay);
}
}
}
解决方法
您在 JLabel
上看不到任何可见更新的主要问题是从未在按钮上添加 ActionListener
,因此从未调用 actionPerformed()
。
要解决此问题,您应该在 CurrencyConverter()
构造函数中添加这两行,以在按钮上添加 ActionListener
:
button1.addActionListener(this);
button2.addActionListener(this);
代码中的一些旁注:
-
swing 中一般不推荐使用
null
布局。查看 Visual Guide to Layout Managers 以了解有关 Swing 布局管理器的概述。使用布局管理器将为您完成组件的大小和布局工作。所以你不必自己手动设置每个组件的大小和边界。 -
您可以为每个
actionPerformed()
实现匿名ActionListener
,而不是在JButton
中检查操作的来源。这样,您在组件和操作之间就有了清晰的映射。例如button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int noInDisplay = Integer.parseInt(display.getText()) * 70; display2.setText("" + noInDisplay); } });
-
下一步应该考虑某种输入验证。