Java JButton getText
My previous post I described how to get and set JButton icons.Today am going to demonstrate how to get JButton Text.
JButton getText Example
[
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.ImageIcon; import javax.swing.JLabel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.LookAndFeel; import javax.swing.UIManager; public class JavaJButton { public static void main(String args[]) { try { UIManager.setLookAndFeel ("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"); } catch(Exception e) { } JFrame frame=new JFrame("Jbutton Example"); JButton button=new JButton("Save"); JLabel field=new JLabel(); field.setBounds(50,50, 150,20); frame.add(field); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String text=button.getText(); field.setText("Button Name is="+text); } }); button.setBounds(100,100,95,30); frame.add(button); frame.setSize(400,400); frame.setLocationRelativeTo(null); frame.setLayout(null); frame.setVisible(true); } }
]
JButton getText Code Explanation:
[ button.addActionListener(new ActionListener())]-used to add action to the button when clicked.
[ frame.setVisible(true)]-makes the frame visible.
[ frame.add(button)]-adds button to the frame.
[String text=button.getText();
field.setText("Button Name is="+text);]-gets String in the button and sets the text in a JLabel.