JavaのSwingをネイティブの方法で使用する方法
Javaでは、SwingはGUI(グラフィックユーザーインターフェース)ツールキットであり、ウィンドウ、ボタン、テキストボックスなどのGUIコンポーネントを作成するために使用できます。以下に、Swingの一般的な使用例を示します。
- 基本的なウィンドウを作成する:
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
- 追加ボタン:
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
add(button);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
- テキストボックスを追加:
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
add(textField);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
- レイアウトマネージャーを使ってコンポーネントを配置する。
import javax.swing.*;
import java.awt.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout()); // 使用流式布局管理器
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
add(button1);
add(button2);
add(button3);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
- ボタンクリックイベントのリスニング
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button clicked!");
}
});
add(button);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
これらは基本的な使い方の一部にすぎず、Swingでは他にも多くの機能やコンポーネントを使用できます。