swing 实现点击按钮刷新页面 获取最新数据
时间: 2023-12-08 13:07:01 浏览: 44
你可以在按钮的 ActionListener 中实现刷新页面的操作。具体实现步骤如下:
1. 在按钮的 ActionListener 中获取最新数据。
2. 将最新数据更新到页面中。
3. 调用页面的 repaint() 方法,刷新页面。
下面是一个简单的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RefreshPageDemo extends JFrame {
private JLabel dataLabel;
public RefreshPageDemo() {
initUI();
}
private void initUI() {
setTitle("Refresh Page Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
// 创建按钮
JButton refreshButton = new JButton("Refresh");
// 创建数据标签
dataLabel = new JLabel("Initial data");
// 将按钮和数据标签添加到界面中
JPanel panel = new JPanel();
panel.add(refreshButton);
panel.add(dataLabel);
add(panel);
// 为按钮添加 ActionListener
refreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 在这里获取最新数据,并更新到 dataLabel 中
String newData = "New data";
dataLabel.setText(newData);
// 刷新页面
repaint();
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
RefreshPageDemo demo = new RefreshPageDemo();
demo.setVisible(true);
}
});
}
}
```
在这个示例代码中,我们创建了一个 RefreshPageDemo 类,继承自 JFrame。在 initUI() 方法中,我们创建了一个按钮和一个数据标签,并将它们添加到界面中。我们为按钮添加了一个 ActionListener,当用户点击按钮时,会触发 actionPerformed() 方法。在 actionPerformed() 方法中,我们获取最新数据,并更新到 dataLabel 中,然后调用 repaint() 方法刷新页面。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)