Я хочу добавить JLabel и текстовое поле динамически, нажав кнопку добавления - PullRequest
3 голосов
/ 24 февраля 2011

Когда я создаю текстовое поле и поле с меткой динамически, оно должно располагаться в формате «Textbox: Labelbox», затем, когда я снова нажимаю кнопку «Добавить», тот же шаблон должен повторяться на следующей строке и т. Д.использовать и как?

Это код, который я использовал

if(field_name.getText().equals("")){  
            error.setForeground(Color.red);    
            error.setText("Enter the Field name first");
        } else {  
        JLabel l = new JLabel(field_name.getText(), JLabel.RIGHT);   
        JTextField textField = new JTextField();  
        Dimension dim = new Dimension(20,30);  
        textField.setPreferredSize(dim);  
        field_layer.add(l);  
        field_layer.add(textField);  
        SpringUtilities.makeCompactGrid(field_layer,  
                                numPairs, 2, //rows, cols  
                                6, 6,        //initX, initY  
                                6, 6);       //xPad, yPad  
        numPairs++;  
        field_layer.invalidate();  
        this.pack();  
        }  

Ответы [ 4 ]

7 голосов
/ 24 февраля 2011

Один из вариантов: GridBagLayout . Чтобы правильно использовать этот макет, вам нужно понимать GridBagConstraints . Вот учебник , который поможет вам начать работу.

Вот краткий пример:

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

public class MyExample 
{
    // Field members
    static JPanel panel = new JPanel();
    static Integer indexer = 1;
    static List<JLabel> listOfLabels = new ArrayList<JLabel>();
    static List<JTextField> listOfTextFields = new ArrayList<JTextField>();

    public static void main(String[] args)
    {       
        // Construct frame
        JFrame frame = new JFrame();
        frame.setLayout(new GridBagLayout());
        frame.setPreferredSize(new Dimension(300, 300));
        frame.setTitle("My Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Frame constraints
        GridBagConstraints frameConstraints = new GridBagConstraints();

        // Construct button
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ButtonListener());

        // Add button to frame
        frameConstraints.gridx = 0;
        frameConstraints.gridy = 0;
        frame.add(addButton, frameConstraints);

        // Construct panel
        panel.setPreferredSize(new Dimension(200, 200));
        panel.setLayout(new GridBagLayout());
        panel.setBorder(LineBorder.createBlackLineBorder());

        // Add panel to frame
        frameConstraints.gridx = 0;
        frameConstraints.gridy = 1;
        frameConstraints.weighty = 1;
        frame.add(panel, frameConstraints);

        // Pack frame
        frame.pack();

        // Make frame visible
        frame.setVisible(true);
    }

    static class ButtonListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent arg0) 
        {       
            // Clear panel
            panel.removeAll();

            // Create label and text field
            listOfTextFields.add(new JTextField());
            listOfLabels.add(new JLabel("Label " + indexer));

            // Create constraints
            GridBagConstraints textFieldConstraints = new GridBagConstraints();
            GridBagConstraints labelConstraints = new GridBagConstraints();

            // Add labels and text fields
            for(int i = 0; i < indexer; i++)
            {
                // Text field constraints
                textFieldConstraints.gridx = 0;
                textFieldConstraints.gridy = i;

                // Label constraints
                labelConstraints.gridx = 1;
                labelConstraints.gridy = i;

                // Add them to panel
                panel.add(listOfTextFields.get(i), textFieldConstraints);
                panel.add(listOfLabels.get(i), labelConstraints);
            }

            // Align components top-to-bottom
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = indexer;
            c.weighty = 1;
            panel.add(new JLabel(), c);

            // Increment indexer
            indexer++;
        }
    }
}

Примечание: не ограничивайте себя этим конкретным менеджером макета. То есть вам следует изучить и других менеджеров по макету .

3 голосов
/ 03 января 2012

Я внес небольшое изменение в приведенный выше код .....

    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;

    public class MyExample 
    {
        // Field members
        static JPanel panel = new JPanel();
        static Integer indexer = 1;
        static List<JLabel> listOfLabels = new ArrayList<JLabel>();
        static List<JTextField> listOfTextFields = new ArrayList<JTextField>();

        public static void main(String[] args)
        {       
            // Construct frame
            JFrame frame = new JFrame();
            frame.setLayout(new GridBagLayout());
            frame.setPreferredSize(new Dimension(990, 990));
            frame.setTitle("My Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // Frame constraints
            GridBagConstraints frameConstraints = new GridBagConstraints();

            // Construct button
            JButton addButton = new JButton("Add");
            addButton.addActionListener(new ButtonListener());

            // Add button to frame
            frameConstraints.gridx = 0;
            frameConstraints.gridy = 0;
            frame.add(addButton, frameConstraints);

            // Construct panel
            panel.setPreferredSize(new Dimension(600, 600));
            panel.setLayout(new GridBagLayout());
            panel.setBorder(LineBorder.createBlackLineBorder());

            // Add panel to frame
            frameConstraints.gridx = 0;
            frameConstraints.gridy = 1;
            frameConstraints.weighty = 1;
            frame.add(panel, frameConstraints);

            // Pack frame
            frame.pack();

            // Make frame visible
            frame.setVisible(true);
        }

        static class ButtonListener implements ActionListener
        {
            @Override
            public void actionPerformed(ActionEvent arg0) 
            {       
                // Clear panel
                panel.removeAll();

                // Create label and text field
                JTextField jTextField = new JTextField();
                jTextField.setSize(100, 200);
                listOfTextFields.add(jTextField);
                listOfLabels.add(new JLabel("Label " + indexer));

                // Create constraints
                GridBagConstraints textFieldConstraints = new GridBagConstraints();
                GridBagConstraints labelConstraints = new GridBagConstraints();

                // Add labels and text fields
                for(int i = 0; i < indexer; i++)
                {
                    // Text field constraints
                    textFieldConstraints.gridx = 1;
                    textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
                    textFieldConstraints.weightx = 0.5;
                    textFieldConstraints.insets = new Insets(10, 10, 10, 10);
                    textFieldConstraints.gridy = i;

                    // Label constraints
                    labelConstraints.gridx = 0;
                    labelConstraints.gridy = i;
                    labelConstraints.insets = new Insets(10, 10, 10, 10);

                    // Add them to panel
                    panel.add(listOfLabels.get(i), labelConstraints);
                    panel.add(listOfTextFields.get(i), textFieldConstraints);
                }

                // Align components top-to-bottom
                GridBagConstraints c = new GridBagConstraints();
                c.gridx = 0;
                c.gridy = indexer;
                c.weighty = 1;
                panel.add(new JLabel(), c);

                // Increment indexer
                indexer++;
                panel.updateUI();
            }
        }
    }
2 голосов
/ 08 мая 2013

я изменяю некоторый код и

см. Этот пакет formbuilder;

                import java.awt.Dimension;
                import java.awt.GridBagConstraints;
                import java.awt.GridBagLayout;
                import java.awt.Insets;
                import java.awt.event.ActionEvent;
                import java.awt.event.ActionListener;
                import java.util.ArrayList;
                import java.util.List;
                import javax.swing.JButton;
                import javax.swing.JFrame;
                import javax.swing.JLabel;
                import javax.swing.JPanel;
                import javax.swing.JTextField;
                import javax.swing.border.LineBorder;

                public class CreateFormFields {
                    // Field members

                    static JPanel panel = new JPanel();
                    static Integer indexer = 1;
                    static List<JLabel> listOfLabels = new ArrayList<JLabel>();
                    static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
                    static List<JTextField> listDataType = new ArrayList<JTextField>();
                    static List<JTextField> listRange = new ArrayList<JTextField>();
                    static List<JTextField> listLable = new ArrayList<JTextField>();

                    public static void main(String[] args) {
                        // Construct frame
                        JFrame frame = new JFrame();
                        frame.setLayout(new GridBagLayout());
                        frame.setPreferredSize(new Dimension(990, 990));
                        frame.setTitle("Form Creator");
                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                        // Frame constraints
                        GridBagConstraints frameConstraints = new GridBagConstraints();

                        // Construct button
                        JButton addButton = new JButton("Add");
                         JButton createButton = new JButton("Create Form");
                        addButton.addActionListener(new ButtonListener());
                 createButton.addActionListener(new CreateForm());
                        // Add button to frame
                        frameConstraints.gridx = 0;
                        frameConstraints.gridy = 0;
                        frame.add(addButton, frameConstraints);
                         frameConstraints.gridx = 0;
                        frameConstraints.gridy = 1;
                         frame.add(createButton, frameConstraints);

                        // Construct panel
                        panel.setPreferredSize(new Dimension(900, 900));
                        panel.setLayout(new GridBagLayout());
                        panel.setBorder(LineBorder.createBlackLineBorder());

                        // Add panel to frame
                        frameConstraints.gridx = 0;
                        frameConstraints.gridy = 2;
                        frameConstraints.weighty = 1;
                        frame.add(panel, frameConstraints);

                        // Pack frame
                        frame.pack();

                        // Make frame visible
                        frame.setVisible(true);
                    }

                    static class ButtonListener implements ActionListener {

                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                            // Clear panel
                            panel.removeAll();

                            // Create label and text field
                            JTextField jTextField = new JTextField();
                            jTextField.setSize(5, 20);

                            JTextField jTextField2 = new JTextField();
                            jTextField2.setSize(6, 20);

                            JTextField jTextField3 = new JTextField();
                            jTextField3.setSize(7, 20);

                            JTextField jTextField4 = new JTextField();
                            jTextField4.setSize(8, 20);

                            listOfTextFields.add(jTextField);
                            listDataType.add(jTextField2);
                            listRange.add(jTextField3);
                            listLable.add(jTextField4);
                            listOfLabels.add(new JLabel("LableName | FieldName | DataType | Range "));

                            // Create constraints
                            GridBagConstraints textFieldConstraints = new GridBagConstraints();
                            GridBagConstraints labelConstraints = new GridBagConstraints();
                            GridBagConstraints gridlistDataType = new GridBagConstraints();
                            GridBagConstraints gridlistRange = new GridBagConstraints();
                            GridBagConstraints gridlistLable = new GridBagConstraints();

                            // Add labels and text fields
                            for (int i = 0; i < indexer; i++) {
                                // Label constraints
                                labelConstraints.gridx = 0;
                                labelConstraints.gridy = i;
                                labelConstraints.insets = new Insets(10, 10, 10, 10);

                                // Text field constraints
                                textFieldConstraints.gridx = 1;
                                textFieldConstraints.fill = 1;//GridBagConstraints.HORIZONTAL;
                                textFieldConstraints.weightx = 0.5;
                                textFieldConstraints.insets = new Insets(10, 10, 10, 10);
                                textFieldConstraints.gridy = i;


                                gridlistDataType.gridx = 2;
                                gridlistDataType.fill = 1;//GridBagConstraints.HORIZONTAL;
                                gridlistDataType.weightx = 0.5;
                                gridlistDataType.insets = new Insets(10, 10, 10, 10);
                                gridlistDataType.gridy = i;


                                gridlistRange.gridx = 3;
                                gridlistRange.fill = 1;//GridBagConstraints.HORIZONTAL;
                                gridlistRange.weightx = 0.5;
                                gridlistRange.insets = new Insets(10, 10, 10, 10);
                                gridlistRange.gridy = i;

                                gridlistLable.gridx = 4;
                                gridlistLable.fill = 1;//GridBagConstraints.HORIZONTAL;
                                gridlistLable.weightx = 0.5;
                                gridlistLable.insets = new Insets(10, 10, 10, 10);
                                gridlistLable.gridy = i;





                                // Add them to panel
                                panel.add(listOfLabels.get(i), labelConstraints);
                                panel.add(listOfTextFields.get(i), textFieldConstraints);
                                panel.add(listDataType.get(i), gridlistDataType);
                                panel.add(listRange.get(i), gridlistRange);
                                panel.add(listLable.get(i), gridlistLable);



                            }

                            // Align components top-to-bottom
                            GridBagConstraints c = new GridBagConstraints();
                            c.gridx = 0;
                            c.gridy = indexer;
                            c.weighty = 1;
                            panel.add(new JLabel(), c);

                            // Increment indexer
                            indexer++;
                            panel.updateUI();
                        }
                    }




                      static class CreateForm implements ActionListener {

                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                            // Clear panel
                            panel.removeAll();

                            // Create label and text field
                            JTextField jTextField = new JTextField();
                            jTextField.setSize(5, 20);

                            JTextField jTextField2 = new JTextField();
                            jTextField2.setSize(6, 20);

                            JTextField jTextField3 = new JTextField();
                            jTextField3.setSize(7, 20);

                            JTextField jTextField4 = new JTextField();
                            jTextField4.setSize(8, 20);

                            listOfTextFields.add(jTextField);
                            listDataType.add(jTextField2);
                            listRange.add(jTextField3);
                            listLable.add(jTextField4);
                            listOfLabels.add(new JLabel("LableName | FieldName | DataType | Range "));

                            // Create constraints
                            GridBagConstraints textFieldConstraints = new GridBagConstraints();
                            GridBagConstraints labelConstraints = new GridBagConstraints();
                            GridBagConstraints gridlistDataType = new GridBagConstraints();
                            GridBagConstraints gridlistRange = new GridBagConstraints();
                            GridBagConstraints gridlistLable = new GridBagConstraints();

                            // Add labels and text fields
                            for (int i = 0; i < indexer; i++) {
                                // Label constraints
                                labelConstraints.gridx = 0;
                                labelConstraints.gridy = i;
                                labelConstraints.insets = new Insets(10, 10, 10, 10);

                                // Text field constraints
                                textFieldConstraints.gridx = 1;
                                textFieldConstraints.fill = 1;//GridBagConstraints.HORIZONTAL;
                                textFieldConstraints.weightx = 0.5;
                                textFieldConstraints.insets = new Insets(10, 10, 10, 10);
                                textFieldConstraints.gridy = i;


                                gridlistDataType.gridx = 2;
                                gridlistDataType.fill = 1;//GridBagConstraints.HORIZONTAL;
                                gridlistDataType.weightx = 0.5;
                                gridlistDataType.insets = new Insets(10, 10, 10, 10);
                                gridlistDataType.gridy = i;


                                gridlistRange.gridx = 3;
                                gridlistRange.fill = 1;//GridBagConstraints.HORIZONTAL;
                                gridlistRange.weightx = 0.5;
                                gridlistRange.insets = new Insets(10, 10, 10, 10);
                                gridlistRange.gridy = i;

                                gridlistLable.gridx = 4;
                                gridlistLable.fill = 1;//GridBagConstraints.HORIZONTAL;
                                gridlistLable.weightx = 0.5;
                                gridlistLable.insets = new Insets(10, 10, 10, 10);
                                gridlistLable.gridy = i;





                                // Add them to panel
                                panel.add(listOfLabels.get(i), labelConstraints);
                                panel.add(listOfTextFields.get(i), textFieldConstraints);
                                panel.add(listDataType.get(i), gridlistDataType);
                                panel.add(listRange.get(i), gridlistRange);
                                panel.add(listLable.get(i), gridlistLable);



                            }

                            // Align components top-to-bottom
                            GridBagConstraints c = new GridBagConstraints();
                            c.gridx = 0;
                            c.gridy = indexer;
                            c.weighty = 1;
                            panel.add(new JLabel(), c);

                            // Increment indexer
                            indexer++;
                            panel.updateUI();
                        }
                    }

                }
2 голосов
/ 24 февраля 2011

Я бы порекомендовал GridBagLayout.Вы можете использовать:

JPanel pan = new JPanel(); // For Swing
//or Panel pan = new Panel(); for AWT
pan.setLayout(new GridBagLayout());
GridBagConstraints textC = new GridBagConstraints();
textC.gridx = 0;
GridBagConstraints labelC= new GridBagConstraints();
labelC.gridx = 1;
// For Every (J)TextField
pan.add(text,textC);
// For Every (J)Label
label.add(label,labelC);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...