上部にあるJPanelの中のテキストボタンで、中央のパネルにJComboBoxを追加します。
その処理に伴って、中央のパネルのパネルを拡大します。
見えない部分まで中央のパネルが大きくなるとスクロールできるようになります。
なお、追加したJComboBoxは、ArrayListに追加して、管理できるようにします。
package test;
import java.awt.*;//BorderLayoutなどのパッケージ用
import java.awt.event.*;//ActionListenerなどのパッケージ用
import javax.swing.*;//JPanelなどのパッケージ用
import java.util.*;//ArrayListなどのパッケージ用
class MainPanel extends JPanel implements ActionListener
{
JPanel panelNorth = new JPanel();//上部固定パネル
JPanel panelCenter = new JPanel(new BorderLayout());//中央のサイズを変更予定パネル
JTextField text = new JTextField("追加データ",10);
JButton btnAdd = new JButton("追加");
ArrayList <JComboBox> comboArray = new ArrayList<JComboBox>(); //コンボボックスを入れる配列
public MainPanel()
{
this.setLayout(new BorderLayout());
panelNorth.add(text);
panelNorth.add(btnAdd);
this.add(panelNorth, BorderLayout.NORTH);//パネルに配置
panelCenter.setLayout(null);
this.add(new JScrollPane(panelCenter), BorderLayout.CENTER);//パネルに配置
btnAdd.addActionListener(this);//ボタンアクションの登録
}
public void actionPerformed(ActionEvent e)
{
JComboBox comboBox = new JComboBox();
comboBox.addItem( text.getText() + " " + comboArray.size() + "1");
comboBox.addItem( text.getText() + " " + comboArray.size() + "2");
panelCenter.add(comboBox);//位置やサイズを指定する前で追加します
int y = comboArray.size() * 40 + 10;//comboBoxを配置するy座標取得
comboBox.setBounds(50, y , 200, 30);
panelCenter.setPreferredSize(new Dimension(300, y + 30 + 10));//パネルサイズを広げる
comboArray.add(comboBox); //ArrayListへcomboBoxを追加
this.validate();//コンテナのサブコンポーネントが変更されたことを反映させる
}
}
class TestFrame extends JFrame
{
MainPanel panel = new MainPanel();
public TestFrame()
{//コンストラクタ
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.getContentPane().add(panel, BorderLayout.CENTER);
this.setSize(400, 300);
this.setVisible(true);
}
}
public class TestJScrollPane extends JApplet
{//アプレット時
MainPanel panel = new MainPanel();
public TestJScrollPane()
{//コンストラクタ
this.getContentPane().add(panel, BorderLayout.CENTER);
}
public static void main(String[] args)
{//ローカル起動時
new TestFrame();
}
public void newTestFrame()
{
new TestFrame();
}
}