简体   繁体   中英

how do I get of the particular Jbutton clicked?

I have a list of titles for which I am making Jbuttons. I want that when I click a particular button I get that text.I searched on net and tried some things but they are giving random title out of the list and not the one on which I click. Please let me know where I am making mistake. Any kind of help will be highly appreciated. Thanks,

           for(String title:listOfTitles){
           button1.setText(title);
           button1.setBounds(20,50,100,25);
           button1.setBorderPainted(true);
           button1.setFocusPainted(true);
           button1.setContentAreaFilled(false);
           button1.setOpaque(false);
           button1.setBackground(Color.lightGray);
           button1.setBounds(5,i,100,100);
           button1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField3.setText(((button1) evt.getSource()).getText());
            }

         });
         jPanel3.add(button1);
         jPanel3.revalidate();
         jPanel3.repaint();
         i = i+15;
     }

In general, you do not want to add a MouseListener to JButtons. If you've gone through the button tutorials, surely you've seen that you should use ActionListeners instead. If you do this, call getActionCommand() on the ActionEvent object passed into the listener's actionPerformed(...) method and you'll get the String you want.

ie,

myButton.addActionListener(new ActionListener() {
   actionPerformed(ActionEvent evt) {
      System.out.println("Button's actionCommand: " + evt.getActionCommand());
   }
});

Legal Disclaimer: This code has not been compiled nor tested and is not meant to be a copy and paste solution, but rather to give you an idea of how ActionListeners work, so you can adapt the concept to your program.

Also, please check out the Swing JButton tutorial for all the rest of the details that you'll need to know.

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