解答例 - 実習課題4 - 6.コンテナ
(実習課題4)
以下のサンプルプログラムを作成しなさい。
- ウィンドウの中央に「JSplitPane」、下にボタンを2つ配置する。
- 「JSplitPane」は左右に分割し、それぞれの領域に色違いのボタンを配置する。テキスト・色は任意。
- それぞれのボタンを押すと、該当する領域が大きくなるように中央線が動くようにする事。
- またウィンドウの下部にあるボタンのテキストは「left」と「right」で、それぞれを押すと中央線が「左に」「右に」動くようにする事。
解答例
/**
* SplitPaneControlFrame.java
* TECHSCORE Javaユーザインタフェース6章 実習課題4
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.ui.chapter6.exercise4;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class SplitPaneControlFrame extends JFrame implements ActionListener {
private JButton leftPaneButton, rightPaneButton;
private JButton leftButton, rightButton;
private JSplitPane splitPane;
public SplitPaneControlFrame() {
super("SplitPaneControlFrame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setPreferredSize(new Dimension(200, 100));
getContentPane().add(splitPane);
// 左のボタン
leftPaneButton = new JButton("red");
leftPaneButton.setBackground(Color.red);
leftPaneButton.addActionListener(this);
splitPane.setLeftComponent(leftPaneButton);
// 右のボタン
rightPaneButton = new JButton("blue");
rightPaneButton.setBackground(Color.blue);
rightPaneButton.addActionListener(this);
splitPane.setRightComponent(rightPaneButton);
// 下のボタン配置用パネル
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
leftButton = new JButton("left");
rightButton = new JButton("right");
leftButton.addActionListener(this);
rightButton.addActionListener(this);
panel.add(leftButton);
panel.add(rightButton);
pack();
// ディバイダを中央に設定
splitPane.setDividerLocation(
(splitPane.getMinimumDividerLocation() + splitPane.getMaximumDividerLocation()) / 2);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == leftPaneButton || event.getSource() == rightButton) {
splitPane.setDividerLocation(splitPane.getDividerLocation() + 1);
} else if (event.getSource() == rightPaneButton || event.getSource() == leftButton) {
splitPane.setDividerLocation(splitPane.getDividerLocation() - 1);
}
}
public static void main(String args[]) {
new SplitPaneControlFrame().setVisible(true);
}
}

