调用setText时Jlabel未更新



在构建一个简单的货币转换器应用程序时,setText不会在JLabel中设置值。(我在windows中使用eclipseide(。我调用了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, 300, 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, 100, 135, 50);
frame.add(button2);

display2=new JLabel();
display2.setBounds(50, 170, 300, 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布局。请参阅布局管理器可视化指南,了解有关摆动布局管理器的概述。使用布局管理器将为您确定组件的大小和布局。因此,您不必手动设置每个组件的大小和边界。

  • 您可以为每个JButton实现一个匿名的ActionListener,而不是在actionPerformed()中检查操作的来源。这样,组件和操作之间就有了清晰的映射。例如

    button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    int noInDisplay = Integer.parseInt(display.getText()) * 70;
    display2.setText("" + noInDisplay);
    }
    });
    
  • 下一步应该考虑某种输入验证。

最新更新