为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

德玛西亚99 2021-04-02 18:15:33
我在访问内部类Code中的变量int i时遇到问题:public class OnColumnSelectPanel {JFrame jFrame;JPanel mainJPanel;//JPanel jPanel1;//JTextField jTextField;//JButton jButton;//JComboBox jComboBox [];MigLayout layout;MigLayout frameLayout;//column namesColumnNames 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。
查看完整描述

1 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

只能从匿名类访问有效的最终变量。 i由循环修改,因此它实际上不是最终的。


解决方法如下所示:


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

   ...


  final int effectivelyFinal = i;

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


    @Override

    public void actionPerformed(ActionEvent ae) {

      ...

      // use effectivelyFinal instead of i

    });

}

但是,正如其他人建议的那样,将匿名类提取到真实类中并使用构造函数传递所有必需的参数会更好。看起来可能像这样:


class MyListener implements ActionListener {


    private final int index;


    // add more fields for other required parameters


    public MyListener(int index) {

        this.index = index;

    }


    @Override

    public void actionPerformed(ActionEvent e) {

      // use index    

    }

}

用法:


jButton[i].addActionListener(new MyListener(i));


查看完整回答
反对 回复 2021-04-21
  • 1 回答
  • 0 关注
  • 105 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信