基于前一个面板中的用户输入显示可变GUI面板的建议

时间:2012-03-05 16:20:03

标签: java swing user-interface

我正在编写一个允许用户选择csv文件的程序,该文件具有不同数量的列和列标题,从csv文件中选择他们想要绘制的列,最后绘制图形。此界面是一个显示三个步骤的GUI,其代码如下所示。我的问题是“步骤2”的面板只能在用户选择文件后显示,因为csv文件中的列数可能不同,选择列标题的复选框也会相应变化。

我目前正在研究顺序显示面板的方法。理想情况下,我想保留目前看来的gui。我已经简要地阅读了有关使用组件侦听器的内容,但我不确定它们是否适合我需要的内容,这就是我所看到的示例:ComponentEventDemo

我见过的另一个建议是使用像Creating Wizard Dialogs with Java Swing这样的向导对话框,但是如果可能的话,我宁愿让前面的步骤可见。

任何有关解决此问题的合适方法的建议都会很棒。谢谢!

package dynamicgui;

import java.awt.event.*;
import static javax.swing.GroupLayout.Alignment.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;

public class Attempt2GUI extends JPanel {//{
    //  implements ItemListener{

    public javax.swing.JFileChooser fc;
    //public JFileChooser fc;// = new JFileChooser(); 
    JFrame frame = new JFrame();
    JPanel panel1 = new JPanel(); //setp 1 panel
    JPanel panel2 = new JPanel(); //setp 2
    JPanel panel3 = new JPanel(); //step 3
    public String[] checkBoxNames = {"open", "close", "high", "low", "max",
        "today", "yesterday", "tomorrow", "lowest", "min"};

    public void setupGUI() {

        GroupLayout p1layout = new GroupLayout(panel1);
        panel1.setLayout(p1layout);
        //      panel1.addComponentListener(this);
        p1layout.setAutoCreateGaps(true);
        p1layout.setAutoCreateContainerGaps(true);

        GroupLayout p2layout = new GroupLayout(panel2);
        panel2.setLayout(p2layout);
        //     panel2.addComponentListener(this);
        p2layout.setAutoCreateGaps(true);
        p2layout.setAutoCreateContainerGaps(true);

        GroupLayout p3layout = new GroupLayout(panel3);
        panel3.setLayout(p3layout);
        //     panel3.addComponentListener(this);
        p3layout.setAutoCreateGaps(true);
        p3layout.setAutoCreateContainerGaps(true);


        //CONTENTS OF TOP PANEL
        JLabel step1 = new JLabel("Step 1:");
        step1.setFont(new java.awt.Font("Tahoma", 1, 11));
        step1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);

        JLabel inst1 = new JLabel("Select the file you use for this program.");

        JButton fileChooseBtn = new JButton("Select File");

        fileChooseBtn.addActionListener(new ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileChooseBtnActionPerformed(evt);
            }
        });

        JButton toStep2Btn = new JButton("Next Step");
        //       toStep2Btn.addComponentListener(this);
        toStep2Btn.setActionCommand("toStep2");


        fc = new javax.swing.JFileChooser();
        //note: 'fc' is the public file chooser 

        JSeparator p1lineBreak = new JSeparator();

        //CONTENTS OF SECOND PANEL
        JLabel step2 = new JLabel("Step 2:");
        step2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        step2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);

        JLabel inst2 = new JLabel("Select the title of the columns you wish to plot.");


        System.out.println("checkBoxNames length = " + checkBoxNames.length);

        System.out.println("length / 4 = " + checkBoxNames.length / 4);
        System.out.println("length % 4 = " + checkBoxNames.length % 4);


        JCheckBox[] checkBox;// = new JCheckBox[checkBoxNames.length];
        checkBox = new JCheckBox[checkBoxNames.length];

        JButton toStep3Btn = new JButton("Next Step");

        JSeparator p2lineBreak = new JSeparator();

        //CONTENTS OF THIRD PANEL
        JLabel step3 = new JLabel("Step :3");
        step3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        step3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);

        JLabel inst3 = new JLabel("Plot the Graph.");

        JButton plotBtn = new JButton("Plot Graph");

        plotBtn.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                graphBtnActionPerformed(evt);
            }
        });

        //***************************************************************        
        //----------------LAYOUT PANELS-------------------------------
        //***************************************************************

        //TOP PANEL - panel to choose file to use
        //horizonttal layout
        GroupLayout.ParallelGroup p1withSeparator = p1layout.createParallelGroup(LEADING);
        GroupLayout.SequentialGroup p1leftToRight = p1layout.createSequentialGroup();
        p1leftToRight.addComponent(step1);
        GroupLayout.ParallelGroup p1rightColumn = p1layout.createParallelGroup(LEADING);
        p1rightColumn.addComponent(inst1);
        p1rightColumn.addComponent(fileChooseBtn);
        p1rightColumn.addComponent(toStep2Btn);
        p1leftToRight.addGroup(p1rightColumn);
        p1withSeparator.addGroup(p1leftToRight);
        p1withSeparator.addGap(17, 17, 17);
        p1withSeparator.addComponent(p1lineBreak);

        p1layout.setHorizontalGroup(p1withSeparator);

        //vertical layout
        GroupLayout.SequentialGroup p1topToBottom = p1layout.createSequentialGroup();
        GroupLayout.ParallelGroup p1topRow = p1layout.createParallelGroup(BASELINE);
        p1topRow.addComponent(step1);
        p1topRow.addComponent(inst1);
        p1topToBottom.addGroup(p1topRow);
        p1topToBottom.addComponent(fileChooseBtn);
        p1topToBottom.addComponent(toStep2Btn);
        p1topToBottom.addGap(20, 20, 20);
        p1topToBottom.addComponent(p1lineBreak);

        p1layout.setVerticalGroup(p1topToBottom);

        //    panel1.addComponentListener(this);

        //***********************************************************************
        //---------SECOND PANEL - checkboxes for column titles
        //***********************************************************************        

        //horiszontal layout - before dynamic
        GroupLayout.ParallelGroup p2withSeparatorH = p2layout.createParallelGroup(LEADING);
        GroupLayout.SequentialGroup p2leftToRight = p2layout.createSequentialGroup();
        p2leftToRight.addComponent(step2);
        GroupLayout.ParallelGroup p2rightColumnH = p2layout.createParallelGroup(LEADING);
        p2rightColumnH.addComponent(inst2);

        //vertical group - before dynamic             

        GroupLayout.SequentialGroup p2withSeparatorV = p2layout.createSequentialGroup();
        GroupLayout.ParallelGroup p2topToBottom = p2layout.createParallelGroup(BASELINE);
        p2topToBottom.addComponent(step2);
        GroupLayout.SequentialGroup p2rightColumnV = p2layout.createSequentialGroup();
        p2rightColumnV.addComponent(inst2);

        //add dynamic - both horizontal and vertical 
        if (checkBoxNames.length > 0) {
            int rows = checkBoxNames.length / 4; //change '4' to alter num boxes from left to right
            int remainder = checkBoxNames.length % 4;

            if (rows > 0 || remainder > 0) {
                GroupLayout.SequentialGroup boxesLeftToRightH = p2layout.createSequentialGroup();
                GroupLayout.ParallelGroup boxesTopToBottomV = p2layout.createParallelGroup();
                GroupLayout.ParallelGroup column1H = p2layout.createParallelGroup();
                GroupLayout.ParallelGroup column2H = p2layout.createParallelGroup();
                GroupLayout.ParallelGroup column3H = p2layout.createParallelGroup();
                GroupLayout.ParallelGroup column4H = p2layout.createParallelGroup();

                GroupLayout.SequentialGroup column1V = p2layout.createSequentialGroup();
                GroupLayout.SequentialGroup column2V = p2layout.createSequentialGroup();
                GroupLayout.SequentialGroup column3V = p2layout.createSequentialGroup();
                GroupLayout.SequentialGroup column4V = p2layout.createSequentialGroup();

                if ((rows > 1) || (rows == 1 && remainder > 0)) {

                    for (int c = 0; c < 4; c++) {
                        //cycle through each of the 4columns, change '4' to alter num boxes from left to right
                        for (int i = c; i < checkBoxNames.length - remainder; i = i + 4) {
                            //change '4' to alter num boxes from left to right
                            checkBox[i] = new JCheckBox(checkBoxNames[i]);
                            JCheckBox cb = new JCheckBox(checkBoxNames[i]);
                            cb.addItemListener(new MyCheckBoxListener());
                            //  cb.setActionCommand(checkBoxNames[i]);

                            switch (c) {
                                case 0:
                                    column1H.addComponent(cb);
                                    column1V.addComponent(cb);
                                    break;
                                case 1:
                                    column2H.addComponent(cb);
                                    column2V.addComponent(cb);
                                    break;
                                case 2:
                                    column3H.addComponent(cb);
                                    column3V.addComponent(cb);
                                    break;
                                case 3:
                                    column4H.addComponent(cb);
                                    column4V.addComponent(cb);
                                    break;
                            }
                        }
                        if (remainder - c > 0) {
                            checkBox[checkBoxNames.length - (remainder - c)] = new JCheckBox(
                                checkBoxNames[checkBoxNames.length - (remainder - c)]);
                            JCheckBox cb = new JCheckBox(checkBoxNames[checkBoxNames.length - (remainder - c)]);
                            cb.addItemListener(new MyCheckBoxListener());
                            //   cb.setActionCommand(checkBoxNames[c]);
                            switch (c) {
                                case 0:
                                    column1H.addComponent(cb);
                                    column1V.addComponent(cb);
                                    break;
                                case 1:
                                    column2H.addComponent(cb);
                                    column2V.addComponent(cb);
                                    break;
                                case 2:
                                    column3H.addComponent(cb);
                                    column3V.addComponent(cb);
                                    break;
                                case 3:
                                    column4H.addComponent(cb);
                                    column4V.addComponent(cb);
                                    break;
                            }
                        }
                    }
                }

                if (rows == 0 && remainder > 0) {
                    for (int i = 0; i < checkBoxNames.length; i++) {
                        //change '4' to alter num boxes from left to right

                        if (remainder - i > 0) {
                            checkBox[checkBoxNames.length - (remainder - i)] = new JCheckBox(
                                checkBoxNames[checkBoxNames.length - (remainder - i)]);
                            JCheckBox cb = new JCheckBox(checkBoxNames[checkBoxNames.length - (remainder - i)]);
                            cb.addItemListener(new MyCheckBoxListener());
                            //     cb.setActionCommand(checkBoxNames[i]);
                            switch (i) {
                                case 0:
                                    column1H.addComponent(cb);
                                    column1V.addComponent(cb);
                                    break;
                                case 1:
                                    column2H.addComponent(cb);
                                    column2V.addComponent(cb);
                                    break;
                                case 2:
                                    column3H.addComponent(cb);
                                    column3V.addComponent(cb);
                                    break;
                                case 3:
                                    column4H.addComponent(cb);
                                    column4V.addComponent(cb);
                                    break;
                            }
                        }
                    }
                }

                boxesLeftToRightH.addGroup(column1H);
                boxesLeftToRightH.addGroup(column2H);
                boxesLeftToRightH.addGroup(column3H);
                boxesLeftToRightH.addGroup(column4H);

                boxesTopToBottomV.addGroup(column1V);
                boxesTopToBottomV.addGroup(column2V);
                boxesTopToBottomV.addGroup(column3V);
                boxesTopToBottomV.addGroup(column4V);

                p2rightColumnH.addGroup(boxesLeftToRightH);
                p2rightColumnV.addGroup(boxesTopToBottomV);

            }

        }// end if length >0  


        //add horizonatal - after dygnamic    
        p2rightColumnH.addComponent(toStep3Btn);
        p2leftToRight.addGroup(p2rightColumnH);
        p2withSeparatorH.addGroup(p2leftToRight);
        p2withSeparatorH.addGap(17, 17, 17);
        p2withSeparatorH.addComponent(p2lineBreak);
        p2layout.setHorizontalGroup(p2withSeparatorH);

        //add vertical - after dynamic
        p2rightColumnV.addComponent(toStep3Btn);
        p2topToBottom.addGroup(p2rightColumnV);
        p2withSeparatorV.addGroup(p2topToBottom);
        p2withSeparatorV.addGap(20, 20, 20);
        p2withSeparatorV.addComponent(p2lineBreak);
        p2layout.setVerticalGroup(p2withSeparatorV);

        //   panel2.addComponentListener(this);


        //***********************************************************************        
        //------------BOTTOM PANEL - panel that plots the graphs-----------------
        //***********************************************************************

        //horizontal layout
        GroupLayout.SequentialGroup p3leftToRight = p3layout.createSequentialGroup();
        p3leftToRight.addComponent(step3);
        GroupLayout.ParallelGroup p3rightColumn = p3layout.createParallelGroup(LEADING);
        p3rightColumn.addComponent(inst3);
        p3rightColumn.addComponent(plotBtn);
        p3leftToRight.addGroup(p3rightColumn);

        p3layout.setHorizontalGroup(p3leftToRight);

        //vertical layout
        GroupLayout.SequentialGroup p3topToBottom = p3layout.createSequentialGroup();
        GroupLayout.ParallelGroup p3topRow = p3layout.createParallelGroup(BASELINE);
        p3topRow.addComponent(step3);
        p3topRow.addComponent(inst3);
        p3topToBottom.addGroup(p3topRow);
        p3topToBottom.addComponent(plotBtn);
        p3layout.setVerticalGroup(p3topToBottom);



        //***************************************************************        
        //----------------ADD PANELS TO MAIN PANEL-------------------------------
        //***************************************************************


        /*  
        frame.getContentPane().setLayout(new GridLayout(3,0));
        frame.getContentPane().add(panel1);
        frame.getContentPane().add(panel2);
        frame.getContentPane().add(panel3);

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


         * 
         */

    }//end setupGUI

    public void addToFrame() {

        Attempt2GUI a2g = new Attempt2GUI();

        //   a2g.setupGUI();

        frame.setTitle("Plot Graph");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.getContentPane().setLayout(new GridLayout(3, 0));
        frame.getContentPane().add(panel1);
        frame.getContentPane().add(panel2);
        frame.getContentPane().add(panel3);

        frame.pack();
        frame.setVisible(true);
    }
    /*
     * for the select file button to open file chooser window
     */
    private static String selFilepath = "XXX";

    private void fileChooseBtnActionPerformed(ActionEvent evt) {

        System.out.println("the filepath before file selected is " + selFilepath);
        // Show open dialog; this method does not return until the dialog is closed
        fc.showOpenDialog(this);
        File selFile = fc.getSelectedFile();
        selFilepath = selFile.getAbsolutePath();

        System.out.println("the file selected is " + selFile);
        System.out.println("the file selected in string form is " + selFilepath);
    }

    /*
     * the filepath will be passed to the reader class
     */
    public String getFilepath() {
        return selFilepath;
    }

    /*
     * set the second panel visible
     *
    private void toStep2BtnActionPerformed(ActionEvent evt) {

    if("toStep2".equals(evt.getActionCommand())){
    panel2.setVisible(true);

    //Need to revalidate and repaint, or else the panel
    //will probably be drawn in the wrong place.
    panel2.revalidate();
    panel2.repaint();
    }
    }

    /*
     * set the third panel visible
     *
    private void toStep3BtnActionPerformed(ActionEvent evt) {
    throw new UnsupportedOperationException("Not yet implemented");

    }


    /*
     * call in the graph class 
     */
    private void graphBtnActionPerformed(ActionEvent evt) {
    }

    public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(
                UIManager.getSystemLookAndFeelClassName());

        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        Attempt2GUI a2 = new Attempt2GUI();
        a2.setupGUI();
        a2.addToFrame();

        System.out.println("filepath is " + a2.getFilepath());
        a2.getFilepath();

        //    mmg.getSelectedBoxes();
    }

    /*
     * keep running total of all checkboxes selected
     */
    public static ArrayList<Integer> selected = new ArrayList<Integer>();

    public int[] addSelectedBoxes(int index) {

        selected.add(index);

        for (int i = 0; i < selected.size(); i++) {
            System.out.println("selected list in lineGUI is " + selected.get(i));
        }

        int[] selectedBoxes = {1, 2, 3};
        return selectedBoxes;
    }
}//end class lineGUI

/*
 * handle the itemLIstener on the checkboxes 
 */
class MyCheckBoxListener implements java.awt.event.ItemListener {

    ComponentGUI lg = new ComponentGUI();
    String[] boxes = lg.checkBoxNames;
    ArrayList<Integer> selectedList = new ArrayList<Integer>();
    /*
     * tdentify the selected boxes and return an array of the indexes of these boxes
     * to be used by the gui to plot each in the selected list series selected
     */

    @Override
    public void itemStateChanged(ItemEvent ie) {

        for (int i = 0; i < boxes.length; i++) {
            if (ie.getItem().toString().endsWith("text=" + boxes[i] + "]")) {
                selectedList.add(i);
                lg.addSelectedBoxes(i);
            }
        }

        int[] selectedArray = new int[selectedList.size()];

        for (int i = 0; i < selectedList.size(); i++) {
            selectedArray[i] = selectedList.get(i);
        }

        for (int i = 0; i < selectedArray.length; i++) {
            System.out.println("box selected = " + selectedArray[i]);
            System.out.println("selectedList = " + selectedList.get(i));
        }
    }

    public ArrayList<Integer> getNewBoxTick() {
        return selectedList;
    }
}

1 个答案:

答案 0 :(得分:1)

您链接的向导文章提供了如何滚动自己的向导实现的基本描述,您应该能够轻松显示步骤列表并突出显示当前步骤。

我推出了自己的向导实现,并没有太复杂。以下是一些关于如何做到这一点的提示:

  • 创建一个包含3个区域的向导对话框:步骤列表,实际步骤控件和导航步骤的按钮
  • 导航到上一个/下一个步骤时,您可能希望执行以下操作:
    • 根据步骤列表中的位置更新后退/下一步按钮
    • 执行“下一步”操作或根据需要回滚上一个操作
    • 更换步骤控件(如果每个步骤都有一个面板,只需更换面板)

您可能希望为向导步骤创建基类,以提供常见数据,如 next rollback 方法,步骤描述/名称,步骤控制面板等。

可能有其他解决方案可能会使用选项卡式窗格或CardLayout布局管理器。