Swingコンポーネントの窓をJavaでどのように使用しますか?
Swingのコンポーネントを使用してウィンドウを作成する手順は次のとおりです:
- Swingクラスをインポートする
import javax.swing.JFrame;
import javax.swing.JPanel;
- JFrameを自然な日本語で言い換えると「ウィンドウフレーム」です。
JFrame frame = new JFrame("Swing Window");
- ウィンドウのサイズと位置を設定します。
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // 居中显示窗口
- 設定ウィンドウの閉じる操作
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- パネル
JPanel panel = new JPanel();
- 他のSwingコンポーネント(ボタン、テキストボックスなど)をパネルに追加する。
panel.add(new JButton("Button"));
panel.add(new JTextField("Text Field"));
- ウィンドウのコンテンツパネルとしてパネルを設定します。
frame.setContentPane(panel);
- ウィンドウを表示
frame.setVisible(true);
以下は完全なサンプルコードです:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SwingWindowExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Window");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(new JButton("Button"));
panel.add(new JTextField("Text Field"));
frame.setContentPane(panel);
frame.setVisible(true);
}
}
上記のコードを実行すると、ボタンとテキストボックスが付いたウィンドウが表示されます。