今回は、JavaのJPanelクラスを定義し、パネルを作成するための方法を解説していきたいと思います。
Javaは様々なアプリやシステムを作っている有名なプログラミング言語です。
GUIの基礎として今回は、パネルを作成する方法をマスターしていきましょう。
目次
目次
- パネルを作成する
- パネルの背景色を変更する
- パネルにボタンやラベルなどのコンポーネントを配置する
1. パネルを作成する

① JPanel関数を定義する
public class test{ JFrame frame = new JFrame(); public test() { frame = new JFrame("test_sample"); JPanel panel = new JPanel(); frame.add(panel); frame.setSize(600,600); frame.setVisible(true); frame.setLocationRelativeTo(null); } public static void main(String[] args) { // TODO Auto-generated method stub test gui = new test(); } }
上記のコードによりJFrameの中にJPanelを定義することが出来ます。
JPanel panel = new JPanel();でPanelを定義し、frame.add(panel);でframeにpanelを追加します。
それでは、実際どうなったのか実行して見てみましょう。
② 実行して結果を見てみる

こんな感じでFrameが表示されていますが、Panelはどこ?って感じですよね。
でも実際は、ちゃんとpanelは表示されているんです。
これから分かりやすくイメージするためにPanelの背景色を変えて見てみましょう。
2. パネルの背景色を変更する

public class test{ JFrame frame = new JFrame(); public test() { frame = new JFrame("test_sample"); JPanel panel = new JPanel(); panel.setBackground(Color.RED); //panel.setBackground(Color.BLUE); //panel.setBackground(Color.CYAN); //panel.setBackground(Color.GREEN); frame.add(panel); frame.setSize(600,600); frame.setVisible(true); frame.setLocationRelativeTo(null); } public static void main(String[] args) { // TODO Auto-generated method stub test gui = new test(); } }
さきほどのコードに背景色を指定するコードを追加します。
すると上の画像の様に実際にPanelが表示されていたことが分かると思います。
ちなみにカラーコードで指定することも出来ます。
任意の好きな色に変えて見てくださいね。
public class test{ JFrame frame = new JFrame(); public test() { frame = new JFrame("test_sample"); JPanel panel = new JPanel(); //panel.setBackground(Color.RED); //panel.setBackground(Color.BLUE); //panel.setBackground(Color.CYAN); //panel.setBackground(Color.GREEN); panel.setBackground(new Color(40,40,40)); frame.add(panel); frame.setSize(600,600); frame.setVisible(true); frame.setLocationRelativeTo(null); } public static void main(String[] args) { // TODO Auto-generated method stub test gui = new test(); } }
panel.setBackground(new Color(40,40,40));の数字を変えたら好きな色に出来ますよ!
参考にカラーコード一覧を載せておきますね。
好きな色を探してみてくださいね。
カラーコード一覧はこちら
3. パネルにボタンやラベルなどのコンポーネントを配置する

Frameだけではなく、PanelにもLabelやButtonなどのコンポーネントを配置することが出来ます。
今回は、例としてLabelとボタンを配置してみましょう。
public class test{ JFrame frame = new JFrame(); public test() { frame = new JFrame("test_sample"); JPanel panel = new JPanel(); //panel.setBackground(Color.RED); //panel.setBackground(Color.BLUE); //panel.setBackground(Color.CYAN); //panel.setBackground(Color.GREEN); panel.setBackground(new Color(240,240,240)); frame.add(panel); JLabel label = new JLabel("Hello World!"); panel.add(label); JButton button = new JButton("ボタン"); panel.add(button); frame.setSize(600,600); frame.setVisible(true); frame.setLocationRelativeTo(null); } public static void main(String[] args) { // TODO Auto-generated method stub test gui = new test(); } }
以上のようなコードを追加することでパネルにコンポーネントを配置することが出来ます。
以上、JPanelクラスの定義方法について確認し、実際に JPanelでパネルを表示する方法について解説しました。
自由にカスタマイズして楽しんでください!