从动态JPanel创建对象

时间:2015-06-24 19:29:25

标签: java swing jpanel

我已经编写了一些动态创建JPanels的代码。我现在需要一种方法来捕获用户在这些JPanel中创建的数据。我目前有一个“创建”按钮。当被触发时,我希望这个按钮使用每个面板中的3种不同数据类型创建一个对象:name(String),count(int)和boolean。

我非常热衷于编程,但我面临的主要障碍是如何访问未命名为这些面板的动态对象?我想出了如何添加和删除它们,但我无法弄清楚从窗格中的字段捕获数据的方法。

谢谢,代码如下:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;


public class MainSnakeGUI {

    public static void main(String[] arg) {
        new MainSnakeGUI();
    }

    public MainSnakeGUI() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //Create the frame
                JFrame frame = new JFrame("Snake Channels");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new SnakePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SnakePane extends JPanel {
        public SnakePane() {
            //Create buttons and labels
            JButton btnAdd = new JButton("Add New Snake");
            JButton btnRemove = new JButton("Delete Snake");
            JLabel headerLabel = new JLabel("Create a Split Snake");
            JButton btnCreate = new JButton("Create");
            setLayout(new BorderLayout());
            //Create JPanels
            JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel header = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JPanel footer = new JPanel(new FlowLayout(FlowLayout.CENTER));
            //add items to JPanels
            buttons.add(btnAdd);
            buttons.add(btnRemove);
            header.add(headerLabel);
            footer.add(btnCreate);
            //add JPanels to window
            add(header, BorderLayout.NORTH);  //sets header at the top of window
            header.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(buttons, BorderLayout.BEFORE_LINE_BEGINS);  //sets the button to the left of the display pane
            buttons.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(footer, BorderLayout.AFTER_LAST_LINE);  //sets buttons on the bottom of window
            footer.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));


            //add panel to hold new frames
            final JPanel content = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weighty = 1;
            content.add(new JPanel(), gbc);

            //add scroll pane?
            add(new JScrollPane(content));

            //add listener for button
            btnAdd.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SplitSnakeCreationPane pane = new SplitSnakeCreationPane();  //create a new SnakeCreationPane
                    int insertAt = Math.max(0, content.getComponentCount() - 1);  //insert it at the end of the list
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridwidth = GridBagConstraints.REMAINDER;
                    gbc.fill = GridBagConstraints.HORIZONTAL;
                    gbc.weightx = 1;
                    content.add(pane, gbc, insertAt);  //add the pane to the window
                    content.revalidate();
                    content.repaint();
                }
            });

            btnRemove.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    content.remove(content.getComponent(paneCount-1));  //remove the pane at paneCount
                    content.revalidate();  //update window with changes
                    content.repaint();
                    SplitSnakeCreationPane.snakeCount--;  //update count for snakes
                }
            });

            btnCreate.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    for (int i=0; i<paneCount;){

                    }
                }
            });
        }

        //set size of window
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1200, 400);
        }
    }

    public static class SplitSnakeCreationPane extends JPanel {
        //Count of how many snakes created
        private static int snakeCount = 1;

        public SplitSnakeCreationPane() {

            //creates Snake Panes
            setLayout(new GridLayout(2, 4, 10, 10));
            add(new JLabel("Split Snake " + (snakeCount++) + "."));
            add(new JLabel("Snake Name"));
            add(new JLabel("Channel Count"));
            add(new JLabel(""));
            add(new JLabel(""));
            JTextField snakeName =  new JTextField(30);
            JTextField channelCount = new JTextField("0",3);
            JCheckBox artistSupplied = new JCheckBox("Artist Supplied?");
            add(snakeName); //Snake Name field
            add(channelCount);  //Channel Count field
            add(artistSupplied); //Artist supplied checkbox
            setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您不必将这些字段作为局部变量放在构造函数中,而是需要在SplitSnakeCreationPane中使用类变量,然后添加一个公共get方法来从这些字段中获取值。只要您拥有这些get方法,就可以使用它在任何需要的地方获取字段值。

按如下方式查看修改后的类:

public static class SplitSnakeCreationPane extends JPanel {
        //Count of how many snakes created
        private static int snakeCount = 1;

        private JTextField snakeName = null;
        private JTextField channelCount = null;        
        private JCheckBox artistSupplied = null;

        public SplitSnakeCreationPane() {

            //creates Snake Panes
            setLayout(new GridLayout(2, 4, 10, 10));
            add(new JLabel("Split Snake " + (snakeCount++) + "."));
            add(new JLabel("Snake Name"));
            add(new JLabel("Channel Count"));
            add(new JLabel(""));
            add(new JLabel(""));
            snakeName =  new JTextField(30);
            channelCount = new JTextField("0",3);
            artistSupplied = new JCheckBox("Artist Supplied?");
            add(snakeName); //Snake Name field
            add(channelCount);  //Channel Count field
            add(artistSupplied); //Artist supplied checkbox
            setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
        }

        public String getSnakeName() {
            return snakeName.getText();
        }

        public String getChannelCount() {
            return channelCount.getText();
        }

        public boolean getArtistSupplied() {
            return artistSupplied.isSelected();
        }
    }

这是完整的代码,复制粘贴并给它一个运行:结果将打印在控制台上。希望你能了解如何获得这些价值观

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;


public class MainSnakeGUI {

    public static void main(String[] arg) {
        new MainSnakeGUI();
    }

    public MainSnakeGUI() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //Create the frame
                JFrame frame = new JFrame("Snake Channels");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new SnakePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SnakePane extends JPanel {


        public SnakePane() {
            //Create buttons and labels
            JButton btnAdd = new JButton("Add New Snake");
            JButton btnRemove = new JButton("Delete Snake");
            JButton show = new JButton("show value");
            JLabel headerLabel = new JLabel("Create a Split Snake");
            JButton btnCreate = new JButton("Create");
            setLayout(new BorderLayout());
            //Create JPanels
            JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel header = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JPanel footer = new JPanel(new FlowLayout(FlowLayout.CENTER));
            //add items to JPanels
            buttons.add(btnAdd);
            buttons.add(btnRemove);
            buttons.add(show);
            header.add(headerLabel);
            footer.add(btnCreate);
            //add JPanels to window
            add(header, BorderLayout.NORTH);  //sets header at the top of window
            header.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(buttons, BorderLayout.BEFORE_LINE_BEGINS);  //sets the button to the left of the display pane
            buttons.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(footer, BorderLayout.AFTER_LAST_LINE);  //sets buttons on the bottom of window
            footer.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));


            //add panel to hold new frames
            final JPanel content = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weighty = 1;
            content.add(new JPanel(), gbc);

            //add scroll pane?
            add(new JScrollPane(content));

            //add listener for button
            btnAdd.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SplitSnakeCreationPane pane = new SplitSnakeCreationPane();  //create a new SnakeCreationPane
                    int insertAt = Math.max(0, content.getComponentCount() - 1);  //insert it at the end of the list
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridwidth = GridBagConstraints.REMAINDER;
                    gbc.fill = GridBagConstraints.HORIZONTAL;
                    gbc.weightx = 1;
                    content.add(pane, gbc, insertAt);  //add the pane to the window

                    System.out.println(insertAt);
                    content.revalidate();
                    content.repaint();
                }
            });

            btnRemove.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    content.remove(content.getComponent(paneCount-1));  //remove the pane at paneCount
                    content.revalidate();  //update window with changes
                    content.repaint();
                    SplitSnakeCreationPane.snakeCount--;  //update count for snakes
                }
            });


            show.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                    for(int n=0; n<content.getComponentCount(); n++){

                        if(content.getComponent(n) instanceof SplitSnakeCreationPane){

                            SplitSnakeCreationPane com = (SplitSnakeCreationPane) content.getComponent(n);

                            System.out.println("Sname Name is : " + com.getSnakeName());
                            System.out.println("ChannelCount is : " + com.getChannelCount());
                            System.out.println("ArtistSupplied  is : " + com.getArtistSupplied());
                        }


                    }



                }
            });


            btnCreate.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    for (int i=0; i<paneCount;){

                    }
                }
            });
        }

        //set size of window
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1200, 400);
        }
    }

    public static class SplitSnakeCreationPane extends JPanel {
        //Count of how many snakes created
        private static int snakeCount = 1;

        private JTextField snakeName = null;
        private JTextField channelCount = null;        
        private JCheckBox artistSupplied = null;

        public SplitSnakeCreationPane() {

            //creates Snake Panes
            setLayout(new GridLayout(2, 4, 10, 10));
            add(new JLabel("Split Snake " + (snakeCount++) + "."));
            add(new JLabel("Snake Name"));
            add(new JLabel("Channel Count"));
            add(new JLabel(""));
            add(new JLabel(""));
            snakeName =  new JTextField(30);
            channelCount = new JTextField("0",3);
            artistSupplied = new JCheckBox("Artist Supplied?");
            add(snakeName); //Snake Name field
            add(channelCount);  //Channel Count field
            add(artistSupplied); //Artist supplied checkbox
            setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
        }

        public String getSnakeName() {
            return snakeName.getText();
        }

        public String getChannelCount() {
            return channelCount.getText();
        }

        public boolean getArtistSupplied() {
            return artistSupplied.isSelected();
        }
    }
}

答案 1 :(得分:0)

执行此操作的最佳方法是创建自己的自定义操作侦听器:

public class CustomListener extends ActionListener {

    private List<SplitSnakeCreationPane> allPanes = new ArrayList<SplitSnakeCreationPane>();

    @Override
    public void actionPerformed(ActionEvent e) {
    //Create your pane
    //Add that pane to your 'allPanes' list.
    }

    public List<SplitSnakeCreationPane> getAllPanes(){
        return this.allPanes;
    }

}

现在您创建此类的对象并将其添加到按钮:

CustomListener createListener = new CustomListener();
btnCreate.addActionListener(createListener);

现在,如果您想要检索您添加的窗格,请致电:

List<SplitSnakeCreationPane> allPanes = createListener.getAllPanes();
相关问题