画面切り替えを実装する-Java CardLayoutの実装- Javaでデスクトップトップアプリ(予定&ToDo管理)を作る-025
今回は、前回解説したJava Swing CardLayoutを使って、実際にアプリに画面切り替え機能を実装します。
MainFrame内のMainPanelにCardLayout機能を実装し、サイドバーのボタンを押すと画面が切り替わるようにしていきます。
実装手順
1. MainFrameのフィールドに JPanel MainPanel, CardLayout layoutを追加する。
2. MainPanelを作成し、CardLayoutを設定する。
[MainFrame.java]
/*今までのコード*/
this.mainPanel = new JPanel();
this.layout = new CardLayout();
this.mainPanel.setLayout(layout);
3. 切り替えView用のパネルを作成する。(「追加」、「今日」、「明日」、「スケジュール」、「いつか」、「完了済み」のうち、「追加」モード用のパネルは作成済みなので、それ以外のパネルを作成)
[MainFrame.java]
/*今までのコード*/
/*View用のパネル追加*/
JPanel todayModePanel = new JPanel();
JPanel tomorrowModePanel = new JPanel();
JPanel scheduleModePanel = new JPanel();
JPanel somedayModePanel = new JPanel();
JPanel doneModePanel = new JPanel();
4. MainPanelにそれぞれのPanelを追加し、mainPanelをcantentPaneに追加する。
[MainFrame.java]
/*今までのコード*/
/*CardLayout*/
this.mainPanel.add(addModePanel.getPanel(),"Add");
this.mainPanel.add(todayModePanel,"Today");
this.mainPanel.add(tomorrowModePanel,"Tomorrow");
this.mainPanel.add(scheduleModePanel,"Schedule");
this.mainPanel.add(somedayModePanel,"Someday");
this.mainPanel.add(doneModePanel,"Done");
contentPane.add(mainPanel);
5. Sideバーのボタンにアクションコマンドを設定し、アクションリスナーを追加する。
[MainFrame.java]
/*今までのコード*/
SideButton buttonAddMode = new SideButton("追加");
buttonAddMode.setActionCommand("Add");
buttonAddMode.addActionListener(this);
SideButton buttonTodayMode = new SideButton("今日");
buttonTodayMode.setActionCommand("Today");
buttonTodayMode.addActionListener(this);
SideButton buttonTomorrowMode = new SideButton("明日");
buttonTomorrowMode.setActionCommand("Tomorrow");
buttonTomorrowMode.addActionListener(this);
SideButton buttonScheduleMode = new SideButton("スケジュール");
buttonScheduleMode.setActionCommand("Schedule");
buttonScheduleMode.addActionListener(this);
SideButton buttonSomedayMode = new SideButton("いつか");
buttonSomedayMode.setActionCommand("Someday");
buttonSomedayMode.addActionListener(this);
SideButton buttonDoneMode = new SideButton("完了済み");
buttonDoneMode.setActionCommand("Done");
buttonDoneMode.addActionListener(this);
6. ActionPerformedメソッドにレイアウト切り替えを追加する
[MainFrame.java]
/*今までのコード*/
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
layout.show(this.mainPanel,cmd);
}
これで、実装完了です。
実行してみます。
アプリを起動すると、最初にCardLayoutに追加されたAddModePanelが表示されます。
サイドバーにある「今日」などのボタンを押すと画面が切り替わります。
アプリ開発記の次の記事はこちら => Swingで自由自在なレイアウトを実現する-SpringLayoutの説明- Javaでデスクトップトップアプリ(予定&ToDo管理)を作る-026