Swingコンポーネントの窓をJavaでどのように使用しますか?

Swingのコンポーネントを使用してウィンドウを作成する手順は次のとおりです:

  1. Swingクラスをインポートする
import javax.swing.JFrame;
import javax.swing.JPanel;
  1. JFrameを自然な日本語で言い換えると「ウィンドウフレーム」です。
JFrame frame = new JFrame("Swing Window");
  1. ウィンドウのサイズと位置を設定します。
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // 居中显示窗口
  1. 設定ウィンドウの閉じる操作
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  1. パネル
JPanel panel = new JPanel();
  1. 他のSwingコンポーネント(ボタン、テキストボックスなど)をパネルに追加する。
panel.add(new JButton("Button"));
panel.add(new JTextField("Text Field"));
  1. ウィンドウのコンテンツパネルとしてパネルを設定します。
frame.setContentPane(panel);
  1. ウィンドウを表示
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);
    }

}

上記のコードを実行すると、ボタンとテキストボックスが付いたウィンドウが表示されます。

bannerAds