【问题标题】:Dynamic JPanel addition动态 JPanel 添加
【发布时间】:2011-10-14 05:07:18
【问题描述】:

我正在尝试创建一个动态的 Swing GUI。当我点击添加/删除按钮时,我需要添加/删除JPanels。我无法动态添加JPanels。最初JPanel 加载但JPanels 的数组无法工作。我该怎么做?

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.print.attribute.standard.JobHoldUntil;
import javax.swing.*;

public class AccessoryFileChooser2 extends JFrame {
  JFileChooser chooser = null;
  JLabel statusbar;
  JLabel file;
  JCheckBox checkBox;
  int count;
  int increment;
  JPanel [] panel = new JPanel[10]; //array

  public AccessoryFileChooser2() {
    setSize(350, 200);
    count=0;
    increment=1;
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final Container c = getContentPane();

    c.setLayout(new BorderLayout());
    checkBox =new JCheckBox("");
    String fileName = "Choose File Name";
   file = new JLabel(fileName);
    final JButton accButton = new JButton("Browse");
    final JButton add = new JButton("Add");
    final JButton validate = new JButton("Validate");
    final JButton delete = new JButton("Delete");

    accButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        int option = chooser.showOpenDialog(AccessoryFileChooser2.this);
        if (option == JFileChooser.APPROVE_OPTION) {
          statusbar.setText(
           (
            chooser.getSelectedFile().getPath()));
        }
      }
    });

    statusbar = new JLabel("Output of your selection will go here");
    chooser = new JFileChooser();


   final JPanel panels =new JPanel();

   //JPanel panel2 =new JPanel();
   panel[count]=new JPanel();
   panel[count].add(checkBox);
   panel[count].add(file);
   panel[count].add(accButton );
   panel[count].add(statusbar);
   c.add(panel[count],BorderLayout.CENTER);
   panels.add(add);
   panels.add(delete);
   panels.add(validate);

   add.addActionListener(new ActionListener() {

       public void actionPerformed(ActionEvent e)
       {
          count=count+1;;
          increment=increment+1;;
          panel[count]=new JPanel();
           System.out.println("You clicked the ADD button");

           panel[count].add(checkBox);
           panel[count].add(file);
           panel[count].add(accButton );
           panel[count].add(statusbar);
           panel[count].revalidate();
           panel[count].repaint();
           panel[count].updateUI();
           c.add(panel[count]);

       }
   });

   delete.addActionListener(new ActionListener() {

       public void actionPerformed(ActionEvent e)
       {
           increment--;
           System.out.println("You clicked the Delete button");
           System.out.println(checkBox.isSelected());
           for (int i = 0; i < panel.length; i++) {
               JCheckBox box=(JCheckBox) panel[i].getComponent(0);
               if(box.isSelected()){
   c.remove(panel[i]);
   }
        }

       }
   });

   validate.addActionListener(new ActionListener() {

       public void actionPerformed(ActionEvent e)
       {
           System.out.println("You clicked the Validate button");
       }
   });


   c.add(panels,BorderLayout.SOUTH);

  }

  public static void main(String args[]) {
    AccessoryFileChooser2 afc = new AccessoryFileChooser2();
    afc.setVisible(true);
  }
}

【问题讨论】:

    标签: swing jpanel java


    【解决方案1】:

    不是说不正确,新手错误很多,

    1/ 因为与您为JPanels 创建数组的方式相同

    JPanel [] panel = new JPanel[10]; 
    

    你需要为其JComponents创建Array,因为一个JComponent一次只能添加一次

    编辑:部分修改/更改的代码显示了这个问题

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
    
    public class AccessoryFileChooser2 extends JFrame {
    
        private static final long serialVersionUID = 1L;
        private JFileChooser chooser = null;
        private JLabel statusbar;
        private JLabel file;
        private JCheckBox checkBox;
        private int count;
        private int increment = 10;
        private JPanel parentPanel = new JPanel();
        private JPanel panels = new JPanel();
        private JPanel[] panel = new JPanel[increment]; //array
        private JButton accButton = new JButton("Browse");
        private JButton addButton = new JButton("Add");
        private JButton validate = new JButton("Validate");
        private JButton delete = new JButton("Delete");
    
        public AccessoryFileChooser2() {
            count = 0;
            parentPanel.setLayout(new GridLayout(10, 1, 10, 10));
            checkBox = new JCheckBox("");
            String fileName = "Choose File Name";
            file = new JLabel(fileName);
            accButton.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent ae) {
                    int option = chooser.showOpenDialog(AccessoryFileChooser2.this);
                    if (option == JFileChooser.APPROVE_OPTION) {
                        statusbar.setText((chooser.getSelectedFile().getPath()));
                    }
                }
            });
            statusbar = new JLabel("Output of your selection will go here");
            chooser = new JFileChooser();
            panel[count] = new JPanel();
            panel[count].add(checkBox);
            panel[count].add(file);
            panel[count].add(accButton);
            panel[count].add(statusbar);
            panel[count].setPreferredSize(new Dimension(450, 40));
            panel[count].setBorder(new LineBorder(Color.BLACK, 1));
            parentPanel.add(panel[count]);
            addButton.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    if (count < increment - 1) {
                        count += 1;
                        panel[count] = new JPanel();
                        System.out.println("You clicked the ADD button");
                        panel[count].add(checkBox);
                        panel[count].add(file);
                        panel[count].add(accButton);
                        panel[count].add(statusbar);
                        panel[count].revalidate();
                        panel[count].repaint();
                        //panel[count].updateUI();
                        parentPanel.add(panel[count]);
                        parentPanel.revalidate();
                        parentPanel.repaint();
                        pack();
                        if (count == increment - 1) {
                            addButton.setEnabled(false);
                        }
                    }
                }
            });
            delete.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("You clicked the Delete button");
                    System.out.println(checkBox.isSelected());
                    /*for (int i = 0; i < parentPanel.getComponentCount(); i++) {
                    JCheckBox box = (JCheckBox) panel[i].getComponent(0);
                    if (box.isSelected()) {
                    parentPanel.remove(panel[i]);
                    }
                    }*/
                }
            });
            validate.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("You clicked the Validate button");
                }
            });
            panels.setLayout(new GridLayout(1, 3, 10, 10));
            panels.add(addButton);
            panels.add(delete);
            panels.add(validate);
            add(parentPanel, BorderLayout.CENTER);
            add(panels, BorderLayout.SOUTH);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    
        public static void main(String args[]) {
            AccessoryFileChooser2 afc = new AccessoryFileChooser2();
        }
    }
    

    将此输出到 GUI

    2/ 以此类推...

    不要这样做,可能会出现很多性能问题,如果您多次添加和删除JPanel[] ...,GUI 将冻结或无响应

    最好按照here 的建议寻找JTable 和一个TableColumn

    【讨论】:

    • 非常感谢。是的,我是 Swings 的新手。所以尝试一些事情来熟悉。
    【解决方案2】:

    在可见的 GUI 中添加或删除组件时,一般代码应为:

    panel.add(...);
    panel.revalidate();
    panel.repaint();
    

    重新验证基本上调用布局管理器。

    重绘确保组件在布局发生变化时被重绘。

    【讨论】:

    • 嗨,它适用于我 revalidate();只是,repaint() 方法是必要的吗?为什么?
    • @MarwenTrabelsi,当你只添加一个组件时,repaint() 通常是没有必要的。但是,有时如果您删除然后添加一个组件,您可能需要强制重新绘制,因为布局管理器可能认为面板大小相同并且不调用 repaint()。
    【解决方案3】:

    我已经成功了:

    repaint();
    validate();
    

    在运行时对 gui 进行更改后。当我创建、删除、移动面板时,我会在组件/容器上调用这两个方法。

    【讨论】:

      【解决方案4】:

      c.add(panel[count]); 之后添加c.validate() 以更新GUI。

      还建议检查JPanels的当前数量,因为这样你会很快得到ArrayIndexOutOfBoundsException...

      【讨论】:

      • 它有帮助吗?根据文档,您必须在 add 之后调用它
      • 我添加了 c.validate 因为 c.revalidate 不存在。但它仍然无法正常工作。感谢您的回复。
      • 尝试之前拨打invalidate()
      猜你喜欢
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多