JAVA如何制作GUI
JAVA制作GUI的方法
JAVA提供了多种方式创建图形用户界面(GUI),以下是常用的工具包和框架:
使用Swing
Swing是JAVA标准库的一部分,适合开发桌面应用程序。
创建简单窗口
import javax.swing.*;
public class SimpleGUI {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JButton button = new JButton("点击");
frame.add(button);
frame.setVisible(true);
}
}
布局管理
Swing支持多种布局管理器,如BorderLayout、FlowLayout、GridLayout。
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JButton("北"), BorderLayout.NORTH);
panel.add(new JButton("中"), BorderLayout.CENTER);
frame.add(panel);
使用JavaFX
JavaFX是Swing的现代替代方案,支持更丰富的UI效果。

基本窗口创建
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXDemo extends Application {
@Override
public void start(Stage stage) {
Button btn = new Button("点击");
StackPane root = new StackPane(btn);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("JavaFX示例");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
FXML与CSS样式
JavaFX支持通过FXML分离UI设计与逻辑,并支持CSS样式。
<!-- example.fxml -->
<StackPane xmlns="http://javafx.com/javafx">
<Button text="FXML按钮" />
</StackPane>
使用第三方库
如Apache Pivot、SWT(Eclipse开发工具常用),适用于特定需求。

SWT示例
import org.eclipse.swt.widgets.*;
public class SWTDemo {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("SWT示例");
Button button = new Button(shell, SWT.PUSH);
button.setText("点击");
button.setBounds(50, 50, 80, 30);
shell.setSize(200, 150);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
图形绘制
通过Graphics2D在组件上绘制自定义图形。
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawRect(50, 50, 100, 100);
}
};
事件处理
为按钮添加点击事件。
button.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "按钮被点击");
});
以上方法覆盖了从基础到进阶的GUI开发需求,可根据项目复杂度选择合适的工具。




