首页 > 解决方案 > 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 个”之类的东西,只是为了减少数字。它只适用于数字,但是当我添加文本时,我收到一大堆错误。有什么方法可以解决,还是我必须使用单独的标签?

标签: javauser-interface

解决方案


您可以使用实例成员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


推荐阅读