【问题标题】:Removing multiple JComboBoxes from the JPanel从 JPanel 中删除多个 JComboBoxes
【发布时间】:2019-07-19 11:10:02
【问题描述】:

我正在努力在我正在处理的程序中创建一个简单的动作事件。 该程序,当我右键单击它时,它必须添加新的 JComboBoxes。它有效。 它必须将这些 JcomboBoxes 中的文本添加到字符串数组列表中。它有效。 现在的问题。也许用户想删除一个 JComboBox,所以它会从 JComboBox 数组中删除,然后文本将从字符串数组中删除,最后从屏幕中删除。它会从两个数组中正确删除,但只会从屏幕上删除一次。这是为什么?我添加了 validate 和 repaint 方法,但它只会删除“visual” JComboBox 的最后一行,而不会“看到”其他的。我究竟做错了什么? 程序内部有一些绘画检查,仅用于调试目的,所以我知道除了从 JPanel 中删除之外一切正常。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class TestingGround
{
    Toolkit toolkit;
    JFrame frame;
    JPopupMenu menu;

    private ArrayList <JComboBox> projectLineComboBoxList;
    private String [] productLineDefinedList = {"-","A","B","C" ,"D","E","F","G", "H", "I", "J","K","L", "M"};   
    private ArrayList userOptionList;
    private JComboBox productLineBox;
    int countAddClicks;

    public TestingGround()
    {
        frame = new JFrame("Testing ground area");

        centerToScreen();

        menu = new JPopupMenu();
        JMenuItem addRow = new JMenuItem("Add ComboBox");
        JMenuItem removeRow = new JMenuItem("Remove ComboBox");
        JPanel panel = new JPanel();
        JPanel mainGridPanel = new JPanel(); 

        mainGridPanel.setLayout(new GridLayout(0,2));
        mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
        panel.add(mainGridPanel);

        userOptionList = new ArrayList();
        projectLineComboBoxList = new ArrayList();

        JButton button = new JButton("save state");
        productLineBox = new JComboBox(productLineDefinedList);
        countAddClicks =0;
        panel.add(button);

        // ACTION LISTENERS
        addRow.addActionListener(new ActionListener(){ // Right click to add JComboBoxes to the screen
                public void actionPerformed(ActionEvent event) {
                    System.out.println("Initial click is: " + countAddClicks);

                    productLineBox = new JComboBox(productLineDefinedList); // add a new JComboBox
                    projectLineComboBoxList.add(countAddClicks,productLineBox); // add this JComboBox to the JComboBox Array List

                    countAddClicks++;  
                    System.out.println("After click is: " + countAddClicks);


                    mainGridPanel.add(productLineBox);   
                    mainGridPanel.repaint();
                    mainGridPanel.revalidate();

                }
            });

            // Problem is right here!
        removeRow.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent event) {
                    countAddClicks--;  
                    System.out.println("After removal click is: " + countAddClicks);
                    projectLineComboBoxList.remove(projectLineComboBoxList.size()-1); // delete from the Array of JComboBoxes
                    userOptionList.remove(userOptionList.size()-1);



                   mainGridPanel.remove(productLineBox); // THIS action removes only the last ComboBox from the screen, and does not "see" the other ones that I want to remove. It should remove one by one from the screen.
                   mainGridPanel.revalidate();      
                   mainGridPanel.repaint();


                }
            });

        button.addActionListener (new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    userOptionList.clear(); 

                    for (int i=0; i<projectLineComboBoxList.size(); i++) {                            
                        JComboBox tempBoxxx = projectLineComboBoxList.get(i);
                        String tzz = tempBoxxx.getSelectedItem().toString();
                        userOptionList.add(tempBoxxx.getSelectedItem().toString()); // Add the text to the String Array List             
                    }

                    System.out.println();
                    System.out.println("The length of the JComboBox Array is: " + projectLineComboBoxList.size() );
                    System.out.println("The content of the String array is: " + userOptionList );
                    System.out.println("The size of the String array is: " + userOptionList.size());
                    System.out.println();

                }

            });

        // Cand dau click din butonul cel mai din dreapta (3) se deschide menium popup 
        frame.addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent event) {
                    if (event.getButton() == event.BUTTON3) {
                        menu.show(event.getComponent(), event.getX(),event.getY());
                    }
                } 
            }); 

        menu.add(addRow);
        menu.add(removeRow);

        frame.add(panel);

        frame.setVisible(true);
    }

    public void centerToScreen()
    {
        frame.setSize(700,600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("A Popup Menu");

        toolkit = frame.getToolkit();
        Dimension size = toolkit.getScreenSize();
        frame.setLocation((size.width-frame.getWidth())/2, (size.height-frame.getHeight())/2);

    }

    public static void main(String[]args){
        new TestingGround();
    }
}

【问题讨论】:

    标签: java swing jcombobox


    【解决方案1】:

    我已经尝试过你的代码,但总是出现异常

    userOptionList.remove(userOptionList.size()-1);
    

    因为给定的列表总是空的。所以我把它删除了。

    要解决您的删除问题,您只需将最后一个删除的组合框保存在变量productLineBox 中。所以需要换行

    projectLineComboBoxList.remove(projectLineComboBoxList.size()-1); // delete from the Array of JComboBoxes
    

    逐行

    productLineBox = projectLineComboBoxList.remove(projectLineComboBoxList.size()-1); // delete from the Array of JComboBoxes
    

    在这种情况下一切正常,您可以删除所有添加的组合框。

    这是我稍微重构的完整代码

    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.SwingUtilities;
    
    public class TestingGround {
    
        private static final String[] PRODUCT_LINE_LIST = {"-", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"};
    
        private final List<JComboBox<String>> projectLineComboBoxList;
    
        private final List<String> userOptionList;
    
        private int countAddClicks;
    
        public TestingGround() {
            JFrame frame = new JFrame("Testing ground area");
    
            centerToScreen(frame);
    
            JPopupMenu menu = new JPopupMenu();
            JMenuItem addRow = new JMenuItem("Add ComboBox");
            JMenuItem removeRow = new JMenuItem("Remove ComboBox");
            JPanel panel = new JPanel();
            JPanel mainGridPanel = new JPanel();
    
            mainGridPanel.setLayout(new GridLayout(0, 2));
            mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
            panel.add(mainGridPanel);
    
            userOptionList = new ArrayList<>();
            projectLineComboBoxList = new ArrayList<>();
    
            JButton button = new JButton("save state");
            countAddClicks = 0;
            panel.add(button);
    
            // ACTION LISTENERS
            addRow.addActionListener(new ActionListener() { // Right click to add JComboBoxes to the screen
                @Override
                public void actionPerformed(ActionEvent event) {
                    System.out.println("Initial click is: " + countAddClicks);
    
                    JComboBox<String> productLineBox = new JComboBox<>(PRODUCT_LINE_LIST); // add a new JComboBox
                    projectLineComboBoxList.add(countAddClicks, productLineBox); // add this JComboBox to the JComboBox Array List
    
                    countAddClicks++;
                    System.out.println("After click is: " + countAddClicks);
    
                    mainGridPanel.add(productLineBox);
                    mainGridPanel.repaint();
                    mainGridPanel.revalidate();
    
                }
            });
    
            // Problem is right here!
            removeRow.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    countAddClicks--;
                    System.out.println("After removal click is: " + countAddClicks);
                    // delete from the Array of JComboBoxes
                    JComboBox<String> productLineBox = projectLineComboBoxList.remove(projectLineComboBoxList.size() - 1);
                    // userOptionList.remove(userOptionList.size() - 1);
    
                    mainGridPanel.remove(productLineBox); // THIS action removes only the last ComboBox from the screen, and does not "see" the
                                                          // other ones that I want to remove. It should remove one by one from the screen.
                    mainGridPanel.revalidate();
                    mainGridPanel.repaint();
    
                }
            });
    
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
    
                    userOptionList.clear();
    
                    for (int i = 0; i < projectLineComboBoxList.size(); i++) {
                        JComboBox<String> tempBoxxx = projectLineComboBoxList.get(i);
                        String tzz = tempBoxxx.getSelectedItem().toString();
                        userOptionList.add(tzz); // Add the text to the String Array List
                    }
    
                    System.out.println();
                    System.out.println("The length of the JComboBox Array is: " + projectLineComboBoxList.size());
                    System.out.println("The content of the String array is: " + userOptionList);
                    System.out.println("The size of the String array is: " + userOptionList.size());
                    System.out.println();
    
                }
    
            });
    
            ((JComponent) frame.getContentPane()).setComponentPopupMenu(menu);
    
            menu.add(addRow);
            menu.add(removeRow);
    
            frame.add(panel);
    
            frame.setVisible(true);
        }
    
        private void centerToScreen(JFrame frame) {
            frame.setSize(700, 600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("A Popup Menu");
            frame.setLocationRelativeTo(null);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(TestingGround::new);
        }
    }
    

    【讨论】:

    • 是的,我的错。稍后我将在 catch 异常上实现以停止错误消息。更换那条线奏效了。但我想了解它,为什么。我的意思是我从逻辑上认为我需要从 JComboBox 数组中删除 JcomboBox,然后从字符串数组中删除它的值,然后从 JPanel 中删除 JComboBox。为什么正确的说法是:combobox = arrayOfComboBoxes.remove(fromThatArray the last one)。我不明白,组合框不是数组,而只是框本身的一个实例。为什么它充当数组?
    • @zypa 好吧,您需要删除正确的 JComboBox 实例。您创建了许多 JComboBox,但总是尝试删除最后一个。例如,当创建 4 个 JComboBox 时,如果没有我的更改,您总是会删除第四个。使用我的更改,您删除了第四个、第三个、第二个和第一个。
    • 好的,谢谢。我有不同的想法,但这是有道理的。最后一个问题,与上述问题无关。这是我正在进行的正确方式吗?我的意思是我自己学习 Java,当我因为一个问题而失去一天以上的时间时,我会在这里问。我制作了许多教程,但我的第一个项目似乎将所有教程绑定在一个地方,有时找到解决方案有点困难。谢谢。这是提高我技能的正确方法吗?
    • Swing 对于初学者来说有点复杂。它需要有关面向对象编程和设计模式的知识(就像 Java 中的所有高级事物一样)。在你的位置上,我会举一些例子并与他们一起玩(尝试改进一些东西)。不要试图从头开始做某事。注意:Swing 今天已经不用了(有些公司还在使用,但是 Oracle 不再改进这个库)。
    • 那么你会推荐 JavaFX 作为 gui 吗?
    猜你喜欢
    • 2012-08-03
    • 2015-02-20
    • 1970-01-01
    • 2012-12-07
    • 2011-01-30
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多