getLabel() and setLabel().
In Core Java, specifically in the context of GUI programming using Swing, the methods used to get and set the text label displayed by a Button
object are:
- To get the text label:
getText()
: This method retrieves the current text displayed on the button.
- To set the text label:
setText(String text)
: This method sets the text to be displayed on the button. You pass the desired text as an argument to this method.
Here’s a simple example:
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonExample {public static void main(String[] args) {
JFrame frame = new JFrame(“Button Example”);
JButton button = new JButton(“Click Me”);
// Get the current text label
String currentText = button.getText();
System.out.println(“Current text label: “ + currentText);
// Set a new text label
button.setText(“Press Me”);
// Display the updated text label
System.out.println(“Updated text label: “ + button.getText());
frame.getContentPane().add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this example, getText()
is used to get the initial text label, and setText("Press Me")
is used to set a new text label for the button.