java如何窗口
Java 窗口创建方法
在 Java 中创建窗口通常使用 JFrame 类,它是 Swing 库的一部分,用于构建图形用户界面(GUI)应用程序。
使用 JFrame 创建基本窗口
import javax.swing.JFrame;
public class MainWindow {
public static void main(String[] args) {
JFrame frame = new JFrame("窗口标题");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
设置窗口属性
窗口大小可以通过 setSize(int width, int height) 方法设置。setDefaultCloseOperation(int operation) 方法定义窗口关闭时的行为,常用参数为 JFrame.EXIT_ON_CLOSE。
窗口位置可以使用 setLocation(int x, int y) 方法设置,或使用 setLocationRelativeTo(Component c) 方法使窗口居中显示。

添加组件到窗口
可以向窗口添加按钮、文本框等组件:
import javax.swing.JButton;
import javax.swing.JFrame;
public class WindowWithButton {
public static void main(String[] args) {
JFrame frame = new JFrame("带按钮的窗口");
frame.setSize(400, 300);
JButton button = new JButton("点击我");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
使用布局管理器
Java Swing 提供多种布局管理器来控制组件在窗口中的排列方式:

import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class LayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("布局示例");
frame.setLayout(new FlowLayout());
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
事件处理
为窗口组件添加事件监听器以实现交互功能:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventExample {
public static void main(String[] args) {
JFrame frame = new JFrame("事件示例");
JButton button = new JButton("点击显示消息");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "按钮被点击了!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
使用 JavaFX 创建窗口
对于更现代的 GUI 开发,可以使用 JavaFX:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Button btn = new Button("点击我");
btn.setOnAction(event -> System.out.println("Hello World!"));
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("JavaFX 窗口");
primaryStage.setScene(scene);
primaryStage.show();
}
}
这些方法提供了在 Java 中创建窗口的基本途径,可根据具体需求选择 Swing 或 JavaFX 进行开发。






