2012-01-19 26 views
4

也許有類似的問題,但我找不到一個。製作程序自動在java中添加文本字段

像我的程序(awt或swing)自動添加控件(如文本字段)的Id。

例如:一個對話框程序有10個字段用於輸入名字,但我需要11個,所以通過按下一個按鈕,一個新字段就會出現。

預先感謝您。

回答

6

下面是使用Box一個例子:

enter image description here

import java.awt.BorderLayout; 
import java.awt.event.*; 

import javax.swing.Box; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 

public class MultiJComponentsTest extends JFrame 
{ 
    private JButton btnAdd; 
    private JPanel centerPanel; 
    private Box vBox; 

    public MultiJComponentsTest() 
    { 
     super("The Title"); 
     btnAdd = new JButton("Add new JTextField!"); 
     btnAdd.addActionListener(new ActionListener(){ 

      @Override 
      public void actionPerformed(ActionEvent e) 
      { 
       vBox.add(new JTextField(20)); 
       pack(); 
      } 

     }); 
     vBox = Box.createVerticalBox(); 
     centerPanel = new JPanel(); 
     JPanel contentPanel = (JPanel) getContentPane(); 
     contentPanel.setLayout(new BorderLayout()); 
     contentPanel.add(btnAdd, "South"); 
     contentPanel.add(centerPanel, "Center"); 
     centerPanel.add(vBox); 
     pack(); 
    } 

    public static void main(String args[]) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       new MultiJComponentsTest().setVisible(true); 
      } 
     }); 
    } 
} 
相關問題