简体   繁体   中英

Java - Change label text when button is clicked

i have a problem i can't solve.

I want this:

When i open the gui, i will show a random number and a button that says "change number".

Then, when the button is clicked, i want that the previous random number change into another random number and so on.

This is my code:

public class RandomDisplayPanel extends JPanel {




    public RandomDisplayPanel() {

    JPanel panel = new JPanel();
    add(panel);
    JPanel inside = new JPanel();
    panel.setBackground(Color.yellow);


    JButton sendButton = new JButton("Send");

    Random generator = new Random();
    int num;
    num = generator.nextInt(100) +1;
    JLabel numero = new JLabel("" + num);


    inside.add(numero);
    inside.add(sendButton);
    panel.add(inside);


    sendButton.addActionListener(new RandomDisplayPanel.RandomListener());
}

private class RandomListener implements ActionListener {


        @Override
        public void actionPerformed(ActionEvent e) {

            Random generator = new Random();

            int num;
            num = generator.nextInt(100) +1;
        }

    }
}

How can i do that? thank you in advance :)

You can pass the (JLabel) number to the listener as follow:

sendButton.addActionListener(new RandomDisplayPanel.RandomListener(number));

private class RandomListener implements ActionListener {
    private JLabel target;
    public RandomListener(JLabel target) {
        this.target = target;    
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        Random generator = new Random();

        int num;
        num = generator.nextInt(100) +1;
        this.target.setText(String.valueOf(num));
    }
}

Hope this helps!

Add numero.setText(num + ""); inside your listener.

EDIT : Declare the JLabel numero as a class variable and it will work.

You need to effectively call numero.setText(num) inside of your ActionPreformed method. I would recommend maybe adding a checking statement similar to this..

if(e.getSource() == sendButton) {
    numero.setText(num);
}

There is another problem I see, being that you might not be able to know the values of numero or sendButton. Offhand you could make them public variables in your main class, or you could pass them as parameters.

To get a random number you can use Math.random(); and multiply it with 10 and add 1 for example. (Then it is between 1 and 10) To set the button text then use

Button myButton=(Button)this.findViewById(R.id.yourButtonsID);
    myButton.setText(yourRandomNumber);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM