Home > Software engineering >  I need to make a button which text will change depending of an integer
I need to make a button which text will change depending of an integer

Time:12-16

I need the text of the button to be 16 at first. As the button is clicked, it needs that 16 to half, and half again and again when it is clicked and when it gets to 1, it needs to stay to 1.

int n=16;
        JButton button4 = new JButton(String.valueOf(n));
        frame.add(button4);
        button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                button4.setText(String.valueOf(n/2));
            }
        });

So far I tried this, but it just gets to 8, and nothing more. I added the frame, and that stuff I just need this button figured out

CodePudding user response:

The code below will continually divide n in half until it reaches 1 and then remain there.

        int n=16;
        JButton button4 = new JButton(String.valueOf(n));
        frame.add(button4);
        button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                button4.setText(String.valueOf(n));
                if( n > 1)
                    n = n / 2;
            }
        });

Ensure that you define n outside of the method in the class header.

CodePudding user response:

The main issue is that you do not modify n. So you just keep setting the text to 16 / 2 = 8

You could modify n (ex: n /= 2) or you could read the button's text, convert to int, halve it, set the button's text to that. No need for n.

button4.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            JButton b = (JButton)e.getSource();
            int n = Integer.parseInt(b.getText());
            if (n > 1) {
                b.setText(String.valueOf(n / 2));
            }
        }
        catch (Exception ex) {}
    }
});

This code can be reused for any button.

  • Related