需要帮助访问内部类内部的变量以进行循环

我在访问内部类Code中的变量int i时遇到问题:


public class OnColumnSelectPanel {


JFrame jFrame;

JPanel mainJPanel;

//JPanel jPanel1;

//JTextField jTextField;

//JButton jButton;

//JComboBox jComboBox [];

MigLayout layout;

MigLayout frameLayout;

//column names

ColumnNames cn = new ColumnNames();

List<String> listedColumnNames = cn.getColumnNames();

String columnNames[] = listedColumnNames.toArray(new String[0]);


public OnColumnSelectPanel(int n) {


    //jPanel1 = new JPanel();

    jFrame = new JFrame("Create Structure of Columns");

    // mainJPanel = new JPanel();

    layout = new MigLayout("flowy", "[center]rel[grow]", "[]10[]");

    frameLayout = new MigLayout("flowx", "[center]rel[grow]", "[]10[]");

    //mainJPanel.setLayout(new BoxLayout(mainJPanel, BoxLayout.X_AXIS));

    //MigLayout mainJPanelLayout = new MigLayout("flowy", "[]rel[grow]", "[]5[]");


    // declare & initialize array

    JPanel jPanel[] = new JPanel[n];

    JComboBox jComboBox[] = new JComboBox[n];

    JButton jButton[] = new JButton[n];

    final int num = 0;

    for (int i = 0; i < n; i++) {


        //assign array

        jComboBox[i] = new JComboBox(columnNames);

        jButton[i] = new JButton("add Sub Heading");

        jPanel[i] = new JPanel();

        System.out.println("Loop number: " + i);


        jButton[i].addActionListener(new ActionListener() {


            @Override

            public void actionPerformed(ActionEvent ae) {


                for (int j = 0; j < n; j++) {

                    if (j <= n) {

                        jComboBox[j] = new JComboBox(columnNames);

                        jPanel[j].add(jComboBox[j]);

                        jFrame.revalidate();

                    } else {

                        JOptionPane.showMessageDialog(null, "You have exceeded your limit");

                    }

                }


            }

        });



如您所见,输出图像。这里的问题是,当我单击添加子标题按钮时,组合框将添加到每个jpanel中。这是因为我无法将值i传递给内部类。知道可能的解决方案将会很有趣。


仅供参考,我正在使用Mig Layout。



德玛西亚99
浏览 106回答 1
1回答

HUH函数

只能从匿名类访问有效的最终变量。 i由循环修改,因此它实际上不是最终的。解决方法如下所示:for (int i = 0; i < n; i++) {&nbsp; &nbsp;...&nbsp; final int effectivelyFinal = i;&nbsp; jButton[i].addActionListener(new ActionListener() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void actionPerformed(ActionEvent ae) {&nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; // use effectivelyFinal instead of i&nbsp; &nbsp; });}但是,正如其他人建议的那样,将匿名类提取到真实类中并使用构造函数传递所有必需的参数会更好。看起来可能像这样:class MyListener implements ActionListener {&nbsp; &nbsp; private final int index;&nbsp; &nbsp; // add more fields for other required parameters&nbsp; &nbsp; public MyListener(int index) {&nbsp; &nbsp; &nbsp; &nbsp; this.index = index;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; // use index&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}用法:jButton[i].addActionListener(new MyListener(i));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java