📜  java gui - Java (1)

📅  最后修改于: 2023-12-03 15:15:56.108000             🧑  作者: Mango

Java GUI

Introduction

Java GUI (Graphical User Interface) refers to the mechanism of creating interactive applications that incorporate graphical elements such as windows, buttons, input fields, menus, and icons. Java provides several APIs (Application Programming Interfaces) to create GUI applications, including the Abstract Window Toolkit (AWT), Swing, and JavaFX.

AWT (Abstract Window Toolkit)

AWT is the oldest GUI package provided by Java, and it is part of the core Java API. AWT provides several components such as the Button, Label, Checkbox, and others, that can be used to construct graphical user interfaces. AWT uses the native platform components for rendering, which makes it less portable across different platforms.

Here is an example of creating a simple window using AWT:

import java.awt.Frame;

public class MyWindow extends Frame {
   public static void main(String[] args) {
      Frame f = new Frame("My Window");
      f.setSize(300, 200);
      f.setVisible(true);
   }
}
Swing

Swing is another GUI package provided by Java, and it is an enhanced version of AWT. Swing provides a set of lightweight components that are implemented in Java, which makes it more portable than AWT. Swing also provides several new components such as JTable, JTree, and others.

Here is an example of creating a simple window using Swing:

import javax.swing.JFrame;

public class MyWindow extends JFrame {
   public static void main(String[] args) {
      JFrame f = new JFrame("My Window");
      f.setSize(300, 200);
      f.setVisible(true);
   }
}
JavaFX

JavaFX is the latest GUI package provided by Java, and it is intended to replace Swing in the future. JavaFX provides a set of components that are implemented in Java and Graphics Processing Units (GPUs), which makes it more responsive and easier to customize. JavaFX is also designed to work seamlessly with other Java technologies such as Java EE and Java SE.

Here is an example of creating a simple window using JavaFX:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class MyWindow extends Application {
   public static void main(String[] args) {
      launch(args);
   }

   @Override
   public void start(Stage primaryStage) {
      primaryStage.setTitle("My Window");
      StackPane root = new StackPane();
      Scene scene = new Scene(root, 300, 200);
      primaryStage.setScene(scene);
      primaryStage.show();
   }
}
Conclusion

Java provides several APIs to create GUI applications, including the Abstract Window Toolkit (AWT), Swing, and JavaFX. Each API has its own set of components and features, and it's up to the developer to choose the one that best suits their needs. Choosing the right API can lead to faster development, better performance, and more portable applications.