can i change toggle button's state to another (play state to pause),by clicking another button(stop)

You can. As JamesCherrill said, you'll need to add a functionality to each of your GUI components, so that it would handle the "events" generated by the user.

Here's a small example. We have a button named "Click me", which can be pressed. Near him there's a label named "Clicks: " and a number. That number indicates the number of times the user clicked that button.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Sb extends JFrame{
    private static final long serialVersionUID = 1L;
    private JButton nrClicks = new JButton("Click me!");
    private JLabel clicks_lbl = new JLabel("Clicks: 0");
    private int clicks = 0;

    public Sb(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        nrClicks.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                clicks_lbl.setText("Clicks: "+Integer.toString(++clicks));
            }
        });
        JPanel main = new JPanel(new GridLayout(1, 2));
        main.add(nrClicks);
        main.add(clicks_lbl);
        add(main);
    }

    public static void main(String args[]){
        Sb sb = new Sb();
        sb.pack();
        sb.setVisible(true);
    }
}

As you can see, I've added an annonymouss inner class of type ActionListener which adds a handle functionality for that button, when an event occurs (which in our case is consisted by the user clicking the button).
You can also have a separate class in which you define your event handling things, but it should always implement a listener class (which "listens" for events). There are a lot of listener classes, you should check the API for more info about them.
For buttons, here's an useful link: Click Here

Edited 3 Years Ago by Lucaci Andrew

can i change toggle button's state to another (play state to pause),by clicking another button(stop)

  • JToggleButton.setSelected(true / false) (inherits from JCheckBox / JRadioButton, has two states)

  • use ItemListener (returns SELECTED / DESELECTED, then easy to test), otherwise you have to test for isSelected()

Edited 3 Years Ago by mKorbel

This article has been dead for over six months. Start a new discussion instead.