在java swing中动态添加复选框

时间:2015-07-08 05:19:34

标签: java swing dynamic checkbox

对给定code..i的引用可以访问for-loop中的if语句内的print语句(在try-catch块内),但是复选框没有添加。 我正在使用重新验证和重绘功能,但仍然无法正常工作。 除了添加jscrollpane之外,try-catch块内的for循环正在运行。我哪里错了?

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anurag;
import com.anurag.HttpURLConnectionExample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 *
 * @author Anurag
 */
public class MainGui {

   static JFrame frame = new JFrame("Rest Testing");

    public static void main(String args[]) {

frame.setLayout(new FlowLayout());
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  final JTextField path = new JTextField("getresponse.xls");
   frame.add(path);


  JButton upload = new JButton("Upload");
    frame.add(upload);

    upload.addActionListener(new ActionListener(){ 
        @Override
        public void actionPerformed(ActionEvent arg0) {



             JScrollPane jscrlpLabel = new JScrollPane(new JLabel(
             "<HTML>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></HTML>"));
             jscrlpLabel.setPreferredSize(new Dimension(200, 100));
             frame.add(jscrlpLabel);
             frame.revalidate();
             frame.repaint();


       try{    
             System.out.println(path.getText());
             HttpURLConnectionExample http  = new HttpURLConnectionExample();
             int noOfRows = http.setPath(path.getText());

              Workbook workbook = Workbook.getWorkbook(new File(path.getText()));
              Sheet sheet = workbook.getSheet(0);

             Cell cell= sheet.findCell("S. No.");

             int col=cell.getColumn();
             int row=cell.getRow();
             row=row+2;
             //System.out.println("row="+row+"col="+col);
             for(int i=row;i<noOfRows;i++,row++)
             {   
                 int p=http.readFile(col,row);
                 if(p==1){

                      JCheckBox cb = new JCheckBox("CheckBox");
                      JScrollPane jscrlp = new JScrollPane(cb);
                      jscrlp.setPreferredSize(new Dimension(140, 95));
                      frame.add(jscrlp);
                      frame.revalidate();
                     frame.repaint();



                     System.out.println("Checkbox created");
                  }  
                 else if(p==2){
                     JCheckBox cb1 = new JCheckBox("CheckBox ");
                     Box box = Box.createVerticalBox();
                     box.add(cb1);
                     JScrollPane jScrollPane1 = new JScrollPane(box);
                     jScrollPane1.setPreferredSize(new Dimension(140, 95));
                     frame.add(jScrollPane1);
                     frame.revalidate();
                     frame.repaint();

                     System.out.println("Checkbox created with textfield");
                 }
             }
             http.getData();

        }catch(Exception e){System.out.println("Exception is "+e);}

            }
    });









 //JOptionPane.showMessageDialog(null, "Done", "Alert", WIDTH);
 JCheckBox a = new JCheckBox("A");
JCheckBox b = new JCheckBox("B");
JLabel label = new JLabel("Option");

Box box = Box.createVerticalBox();
box.add(label);
box.add(a);
box.add(b);

JScrollPane jscrlpBox = new JScrollPane(box);
jscrlpBox.setPreferredSize(new Dimension(240, 150));
//f.add(jscrlpLabel);
frame.add(jscrlpBox);

frame.setVisible(true);
}

}

2 个答案:

答案 0 :(得分:2)

首先阅读Creating a GUI With JFC/SwingLaying Out Components Within a ContainerConcurrency in SwingHow to Use Scroll Panes

  • Box实际上不是&#34;可见&#34;组件,它意味着与BoxLayout
  • 一起使用的功能
  • 您在单个视图中添加了多个JScrollPane,这对我来说很奇怪
  • Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
  • 您正在事件调度线程中更新UI,但是您做出决策的过程可能需要一段时间才能运行,这可能会使UI看起来像是在做在actionPerformed方法存在之前没有任何内容
  • 在调用revaldiate时始终没有什么意义,只要你完成整个用户界面的更新,就可以保留它,从长远来看,它会提供更好的性能

首先创建JPanel,然后将JScrollPane包裹起来,将JScrollPane添加到基本用户界面

根据需要,添加和删除此JPanel中的组件,例如......

Example

public class MainGui {

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

    private JFrame frame = new JFrame("Rest Testing");
    private JPanel checkboxes;

    public MainGui() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                frame.setSize(500, 500);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final JTextField path = new JTextField("getresponse.xls");

                JPanel fields = new JPanel();
                fields.add(path);

                JButton upload = new JButton("Upload");
                fields.add(upload);

                frame.add(fields, BorderLayout.NORTH);

                checkboxes = new JPanel(new GridBagLayout());
                JScrollPane scrollPane = new JScrollPane(checkboxes);

                frame.add(scrollPane);

                upload.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent arg0) {

                        GridBagConstraints gbc = new GridBagConstraints();
                        gbc.gridwidth = GridBagConstraints.REMAINDER;
                        gbc.anchor = GridBagConstraints.WEST;
                        gbc.weightx = 1;

                        checkboxes.add(new JLabel("<HTML>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></HTML>"), gbc);

                        try {
                            int noOfRows = 100;
                            for (int row = 0; row < noOfRows; row++, row++) {
                                int p = (int) ((Math.random() * 2) + 1);
                                System.out.println(p);
                                if (p == 1) {

                                    JCheckBox cb = new JCheckBox("CheckBox");
                                    checkboxes.add(cb, gbc);

                                } else if (p == 2) {

                                    JCheckBox cb1 = new JCheckBox("CheckBox ");
                                    JPanel stuff = new JPanel();
                                    stuff.add(cb1);
                                    stuff.add(new JTextField(10));
                                    checkboxes.add(stuff, gbc);

                                }
                            }

                        } catch (Exception e) {
                            System.out.println("Exception is " + e);
                        }

                        checkboxes.revalidate();
                        checkboxes.repaint();
                    }
                });

                //JOptionPane.showMessageDialog(null, "Done", "Alert", WIDTH);
                JCheckBox a = new JCheckBox("A");
                JCheckBox b = new JCheckBox("B");
                JLabel label = new JLabel("Option");

                JPanel stuff = new JPanel();
                stuff.add(label);
                stuff.add(a);
                stuff.add(b);
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                gbc.anchor = GridBagConstraints.WEST;
                gbc.weightx = 1;
                checkboxes.add(stuff, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

            }
        });
    }

}

现在,我不是100%肯定,但您可能会发现使用JTable会产生您之后的样子。 How to Use Tables

答案 1 :(得分:0)

您无法将复选框直接添加到滚动窗格,您需要创建列表模型。您将需要滚动窗格,列表渲染器,模型和自定义JCheckboxList类。请参阅以下问题:

How do I make a list with checkboxes in Java Swing?

此外,您可能会遇到我在JScrollPane的视口中所做的问题:

Components in JList are Hidden by White Square Thing Until Clicked

相关问题