Search code examples
javaswingjbutton

How to activate a Jbutton by clicking another Jbutton


There are 7 buttons in my project. 6 of them are categories and RandomSoru button is the one which randomly chooses one of the categories. I want to access the chosen category. "r" is the random generator.

RandomSoru.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        TriviaLinked tl = new TriviaLinked();


        tl.insertAtBack(tl.CogHmap);
        tl.insertAtBack(tl.TarihHmap);
        tl.insertAtBack(tl.SporHmap);
        tl.insertAtBack(tl.BilimHmap);
        tl.insertAtBack(tl.FilmHmap);
        tl.insertAtBack(tl.SanatHmap);

        TriviaNode current = tl.root;

        int n = r.nextInt(tl.sizeCounter());

        for (int i = 0; i < n; i++) {
            current = current.next;
        }
        if(current.hmap==tl.CogHmap)
            JOptionPane.showMessageDialog(null,"Your Category is Cografya");

        else if(current.hmap==tl.SporHmap)
            JOptionPane.showMessageDialog(null,"Your Category is Spor");
            ....

Here is the Spor button

Spor.addActionListener(new ActionListener() {


    public void actionPerformed(ActionEvent e) {
    ......

My expectation was like

 else if(current.hmap==tl.SporHmap)
        JOptionPane.showMessageDialog(null,"Your Category is Spor");
        Spor();
else if(current.hmap.....

Solution

  • One way is to add the 6 buttons to an ArrayList.

    Then in the ActionListener of the random button you could do something like:

    1. Use the Collections.shuffle(...) method to randomize the buttons in the List.

    2. Then you get the first button from the List.

    3. Finally you invoke the doClick() method on the button.