想在点击按钮后更换文字
时间: 2024-03-22 12:36:57 浏览: 14
要在点击按钮后更换文字,可以在按钮上添加ActionListener,然后在ActionListener中更改JLabel的文本。具体步骤如下:
1. 创建一个JLabel并将其添加到JPanel中。
```
JLabel myLabel = new JLabel("Enter two operands,result and click on 'Check'");
JPanel myPanel = new JPanel();
myPanel.add(myLabel);
```
2. 创建一个JButton并为其添加ActionListener。
```
JButton myButton = new JButton("Check");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myLabel.setText("Correct! Have another go?");
}
});
```
在ActionListener中,我们调用myLabel.setText()方法来更改JLabel的文本。
3. 将JButton添加到JPanel中。
```
myPanel.add(myButton);
```
完整的示例代码如下:
```
JLabel myLabel = new JLabel("Enter two operands,result and click on 'Check'");
JPanel myPanel = new JPanel();
myPanel.add(myLabel);
JButton myButton = new JButton("Check");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myLabel.setText("Correct! Have another go?");
}
});
myPanel.add(myButton);
```
请注意,这里我将JLabel的文本设置为"Enter two operands,result and click on 'Check'",将JButton的文本设置为"Check"。当用户点击按钮时,JLabel的文本将更改为"Correct! Have another go?"。你可以将这些文本替换为你想要的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)