1

I want to perform the action done when a button is pressed without clicking the button. Asking simply, can I perform two action listeners when a single button is clicked?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
shahsadpp
  • 21
  • 1
  • 2
  • *"can I perform two action listeners when a single button is clicked?"* Sure, start by abstracting everything done in each listener to a method. Then, for your 'two at once', have a listener that calls both methods. OTOH, this question reeks of an XY problem. See [What is the XY problem?](http://meta.stackexchange.com/q/66377) – Andrew Thompson Mar 17 '15 at 09:37
  • Although very similar, I'd argue against this being a dupe. Programmatically clicking a button (via `doClick()`) also invokes Swing-isms such as painting and calling the button's model to be armed/pressed. This is not necessarily what the OP wants. The OP asked about performing the action only. Further, the answer provided by Rolch is both valid and also not included in the dupe question. – splungebob Mar 17 '15 at 15:16
  • thank u guys..i solved the problem using doclick() – shahsadpp Mar 23 '15 at 16:51

1 Answers1

2

You can solve the problem by calling a method when the button is clicked. See this example: Although the button isn't pressed, I can perform the same action.

public class ButtonTest extends javax.swing.JFrame {
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;    

    /**
     * Creates new form ButtonTest
     */
    public ButtonTest() {
        initComponents();

        changeLabelText();
    }

    private void changeLabelText() {
        if(jLabel1.getText().equals("1"))
            jLabel1.setText("2");
        else
            jLabel1.setText("1");
    }

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("1");
        jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);

        jButton1.setText("Click");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeLabelText();
            }
        });
        getContentPane().add(jButton1, java.awt.BorderLayout.PAGE_END);

        pack();
    }                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ButtonTest().setVisible(true);
            }
        });
    }                           
}
Rolch2015
  • 1,354
  • 1
  • 14
  • 20