如何在Java中使用循环在面板上添加组件?

时间:2016-04-03 06:50:34

标签: java

我想在面板上添加一些按钮,表格,并从文本字段输入中获取按钮或面板的数量。这意味着我从文本字段中获取了我添加了多少按钮或添加多少表的输入!

这是我的代码(有错误):

public class panel_scroll extends JFrame{

    JPanel main_panel = new JPanel();
    JPanel content_panel = new JPanel();
    JPanel action_panel = new JPanel();
    int range,i; 
    JButton btn = new JButton("Action");
    JTextField txt =  new JTextField(20);
    JScrollPane scroll = new JScrollPane(content_panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    public panel_scroll(){
        init();
        cmp();
        btn_action();
    }

    private void btn_action(){
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                range = Integer.parseInt(txt.getText().trim());
                JOptionPane.showMessageDialog(null, "Total button i required: "+range);
                for(i=1; i<=range; i++){
                    JButton (btn_i+""+i) = new JButton(); //i want to create button of different object but here what i have to do i dont understand//
                }
            }
        });
    }

    private void init(){
        setSize(500,500);
        setVisible(true);
        setResizable(true);
        setLocationRelativeTo(null);
        setTitle("Panel with scroll bar");
    }

    private void cmp(){
        add(main_panel);
        main_panel.setLayout(new BorderLayout());
        main_panel.add(scroll,BorderLayout.CENTER);
        child_panel_work();
        main_panel.add(action_panel,BorderLayout.SOUTH);
        action_panel_work();
    }

    private void action_panel_work(){
        action_panel.setLayout(new GridLayout(1,2,5,5));
        action_panel.add(txt);
        action_panel.add(btn);
    }

    private void child_panel_work(){
        content_panel.setBorder(BorderFactory.createLineBorder(Color.black));
        content_panel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
    }

    public static void main(String args[]){
        panel_scroll obj = new panel_scroll();
    }
}

1 个答案:

答案 0 :(得分:0)

您可以匿名将它们放在列表或数组中,然后用它们填充容器

实施例

//define a list    
List<JButton> listOfButtons = new ArrayList<JButton>();
//use a loop to fill the list
for(i=1; i<=range; i++){
    listOfButtons.add( new JButton()); 
}
//then get the button at index 0 for example
listOfButtons.get(0);

或者如果你考虑,你可以使用Map<String,JButton>,其中字符串是某种id,让我们说按钮的名称