java - 格式化 JLabel/JTextField 文本?

标签 java swing format jlabel jtextfield

所以我正在尝试制作一个非常基本的应用程序,当您点击按钮时,它会进行计数(每秒将数字添加到 0),然后将其显示在标签和文本字段中。由于我使用的是 double ,因此文本输出如下所示,例如:2.34555555555555。我希望它在点后仅显示 2 个数字。我怎样才能做到这一点?

这是我的代码,正如我所说,只是一个按钮、标签和文本字段以及一个小计时器:

public class Frame1 {

    private JFrame frame;
    private JTextField txtbox1;
    double fiz = 1500;
    double mpfiz = fiz/60/60;
    int secondsPassed = 0;
    double penz = 0;
    Timer timer = new Timer();

    TimerTask task = new TimerTask() {
        public void run() {
            secondsPassed++;
            penz += mpfiz;
            lbpenz.setText("Ennyi: "+ penz);
            txtbox1.setText("Ennyi: " + penz);
        }};
        private JLabel lbpenz;


        public void start() {
            timer.scheduleAtFixedRate(task, 1000, 1000);
        }

        public static void main(String[] args) {
            Frame1 peldany = new Frame1();
            peldany.start();

            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        Frame1 window = new Frame1();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the application.
         */
        public Frame1() {
            initialize();
        }

        /**
         * Initialize the contents of the frame.
         */
        private void initialize() {

            JButton btnStart = new JButton("Start!");
            btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    start();
                }
            });
        }
}

提前致谢。

最佳答案

尝试以下代码

public void run() {
    DecimalFormat df = new DecimalFormat(".##");

    secondsPassed++;
    penz += mpfiz;
    lbpenz.setText("Ennyi: "+ df.format(penz));
    txtbox1.setText("Ennyi: " + df.format(penz));
}};

关于java - 格式化 JLabel/JTextField 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027377/

相关文章:

python - Python 中的对齐列

java - 在java中为国际象棋游戏设计对象

java - Java SE 是一个框架吗?

java - JDBC + Swing : Not able to get table contents

java.awt.Rectangle#intersects(Rectangle r) 丑陋的实现?

mysql - MySQL中的字符串格式化

文本字段中的日期格式

java - 如何调用包含数组的方法

java - 是否支持 log4j.properties 文件包含?

java - JEdi​​torPane.setText 显示页面底部