0

私はコア Java を学び、netbeansを使い始めたばかりですが、プロジェクトの実行時にボタンやラベルなどのコンポーネントを追加しようとしていた時点で立ち往生しています。Google で検索しましたが、例は私が調べたものには、パネルを使用するための余分なオーバーヘッドが含まれていますが、次のようにメモ帳のような単純なエディターでコンポーネントを作成していたので、実行時にコンポーネントを作成できないのはなぜですか

JButton b4=new JButton("ok");
add b4;

動いていない。

4

1 に答える 1

0

実行時に Swing フレームワーク要素を追加するには、要素を追加する JFrame が必要です。JFrame は、使用する他のウィンドウと同様に (そして NetBeans と同様に)、単なるウィンドウであり、 と呼ばれるメソッドがありadd(Component comp)ます。パラメータは、JFrame に追加する Swing または AWT コンポーネントです。開始するためのサンプル コードを次に示します。

// This line creates a new window to display the UI elements:
JFrame window = new JFrame("Window title goes here");

// Set a size for the window:
window.setSize(600, 400);

// Make the entire program close when the window closes:
// (Prevents unintentional background running)
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// This makes it so we can position elements freely:
window.setLayout(null);

// Create a new button:
JButton b4 = new JButton("ok");

// Set the location and size of the button:
b4.setLocation(10, 10);
b4.setSize(100, 26);

// Add the button to the window:
window.add(b4);

// Make the window visible (this is the only way to show the window):
window.setVisible(true);

うまくいけば、これはあなたを助けます!私が Java を始めたときのことを覚えています。まずは GUI 関連以外のことをできる限り上達することを強くお勧めしますが、Swing の準備ができている場合は、上記のコードが機能するはずです。頑張ってください!

于 2013-01-04T18:44:42.603 に答える