Search code examples
javaswingformatjlabeljtextfield

Formatting JLabel/JTextField text?


So I'm trying to make a very basic app that counts(adds a number to 0 every second) when you hit a button then displays it in a label and a text field. Since I'm using doubles the text output looks like this, for example: 2.34555555555555. I want it to display only 2 number after the dot. How could I do that?

Here's my code, as I said just a button, label and textfield alongside with a small timer thingy:

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();
                }
            });
        }
}

Thanks in advance.


Solution

  • Try the following code

    public void run() {
        DecimalFormat df = new DecimalFormat(".##");
    
        secondsPassed++;
        penz += mpfiz;
        lbpenz.setText("Ennyi: "+ df.format(penz));
        txtbox1.setText("Ennyi: " + df.format(penz));
    }};