/****************************/ /* コンポーネントの再配置 */ /* coded by Y.Suganuma */ /****************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; public class Test { public static void main(String[] args) { Win win = new Win("Test Window"); } } class Win extends JFrame implements DocumentListener { int n; JTextField tx; JScrollPane sp; Container cP; Font f; /******************/ /* コンストラクタ */ /******************/ Win (String name) { // JFrameクラスのコンストラクタ super(name); // ウィンドウサイズ setSize(450,200); // レイアウト,背景色,フォント cP = getContentPane(); cP.setLayout(new BorderLayout(5, 10)); cP.setBackground(new Color(225, 255, 225)); f = new Font("TimesRoman", Font.BOLD, 20); cP.setFont(f); // 上のパネル JPanel pn = new JPanel(); pn.setBackground(new Color(225, 255, 225)); cP.add(pn, BorderLayout.NORTH); JLabel lb= new JLabel("データの数"); lb.setFont(f); pn.add(lb); tx = new JTextField(5); tx.setFont(f); tx.getDocument().putProperty("name", "no"); tx.getDocument().addDocumentListener(this); pn.add(tx); // 中央のパネル sp = new JScrollPane(); cP.add(sp, BorderLayout.CENTER); // ウィンドウを表示 setVisible(true); // イベントアダプタ addWindowListener(new WinEnd()); } /************************************/ /* パラメータが変更されたときの処理 */ /************************************/ public void removeUpdate(DocumentEvent e) {} public void changedUpdate(DocumentEvent e) {} public void insertUpdate(DocumentEvent e) { int i1; try { remove(sp); JPanel pn = new JPanel(); sp.add(pn); n = Integer.parseInt(tx.getText()); if (n <= 0) { pn.setBackground(new Color(255, 255, 225)); JTextArea ta = new JTextArea(3,20); ta.setForeground(Color.red); ta.setFont(f); ta.setText(" 0 より大きい数値を入力してください"); pn.add(ta); } else { pn.setBackground(new Color(204, 255, 255)); pn.setLayout(new GridLayout(n, 1, 10, 10)); JPanel pn1[] = new JPanel [n]; JTextField tx1[] = new JTextField [n]; for (i1 = 0; i1 < n; i1++) { pn1[i1] = new JPanel(); pn1[i1].setBackground(new Color(204, 255, 255)); pn.add(pn1[i1]); JLabel lb = new JLabel((i1+1) + " 番目のデータ"); lb.setFont(f); pn1[i1].add(lb); tx1[i1] = new JTextField(5); tx1[i1].setFont(f); pn1[i1].add(tx1[i1]); } } sp = new JScrollPane(pn); cP.add(sp, BorderLayout.CENTER); validate(); } catch (NumberFormatException em) {} } /************/ /* 終了処理 */ /************/ class WinEnd extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } }