Java弹窗可以使用Java的Swing库来实现。以下是一个简单的Java弹窗代码示例:
import javax.swing.*;
public class PopupWindow {
public static void main(String[] args) {
// 创建一个新的JFrame对象作为主窗口
JFrame frame = new JFrame("Popup Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// 创建一个按钮,点击时弹出一个对话框
JButton button = new JButton("Click me!");
button.addActionListener(e -> {
// 创建一个新的JDialog对象作为弹窗
JDialog dialog = new JDialog(frame, "Popup", true);
dialog.setSize(200, 150);
dialog.setLocationRelativeTo(frame); // 将弹窗居中显示
dialog.setVisible(true); // 显示弹窗
});
// 将按钮添加到主窗口中
frame.getContentPane().add(button);
frame.setVisible(true); // 显示主窗口
}
}
这段代码首先创建了一个JFrame
对象作为主窗口,并设置了窗口的大小和关闭操作。然后创建了一个JButton
对象作为按钮,并为其添加了一个点击事件监听器。当用户点击按钮时,会弹出一个JDialog
对象作为弹窗,并设置弹窗的大小、位置和可见性。最后将按钮添加到主窗口中,并显示主窗口。