java - JAVA GUI 标签输出错误
问题描述
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Stock {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Stock window = new Stock();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Stock() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblBrickStock = new JLabel("10");
lblBrickStock.setBounds(48, 62, 46, 14);
frame.getContentPane().add(lblBrickStock);
JButton btnNewButton = new JButton("Bricks");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int bricks = Integer.parseInt(lblBrickStock.getText());
bricks--;
if (bricks <= 10) {
lblBrickStock.setText(String.valueOf(bricks));
}
}
});
btnNewButton.setBounds(38, 28, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
我创建了这个库存程序,它是我正在创建的未来程序的原型。该程序所做的是,当您按下按钮时,标签中的数字会减少。我不能做的是,在标签中我希望它说“剩余 10 个”之类的东西,只是为了减少数字。它只适用于数字,但是当我添加文本时,我收到一大堆错误。有什么方法可以解决,还是我必须使用单独的标签?
解决方案
您可以使用实例成员counter
来跟踪数字,而不是从标签文本中获取当前值
public class Stock{
private int counter = 10;
...
}
你的动作监听器可能是这样的:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
counter--;
if (counter <= 10) {
lblBrickStock.setText(counter + " remaining");
}
}
});
这样,您不必将其解析lblBrickStock.getText
为数值,并且如果这不再是数值,也不必冒险获得解析异常。
这是一个小片段,展示了如何在匿名内部类(动作监听器)中使用变量
public class TestFrame extends JFrame{
private int counter = 10;
public TestFrame(){
this.setTitle("Labo - TestFrame");
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().add(new JButton(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(counter--);
}
}));
this.setVisible(true);
this.pack();
}
}
我点击了 3 次:
10
9
8
推荐阅读
- ios - 在 UITableView 滚动上更新 UITableViewCell
- powershell - 如何在 PowerShell 7 中使用 AzureRm 模块?
- android - 还有另一种方法可以添加片段吗?
- c++ - 从 Visual Studio 代码中的二进制文件读取数据时出错
- password-hash - 将另一个气流连接传递给气流 SSH 操作员时如何从日志和呈现的模板中隐藏密码
- jquery - 在 Angular 8 中包含 jQuery
- html - ReactStrap:如果我使用 Row 和 Col,组件会相互堆叠
- curl - 检索 tiktok 视频的到期日期
- django - Django:页面没有正确重定向错误
- macos - 无法在 macOS Catalina 10.15.1 上对 gdb 进行代码设计:无法识别的 blob 类型