【问题标题】:The for-loop to get the array in the ActionListener is not working在 ActionListener 中获取数组的 for 循环不起作用
【发布时间】:2016-04-18 10:22:47
【问题描述】:

您好,我正在尝试从 JTextField 获取整数数组,然后将它们用于冒泡排序。这里显示的 JButton 应该从 JTextField 中获取一个数组并将其放入一个整数数组中。我认为问题出在for循环中?如何让 for 循环将整数放入数组中?这是我的代码的一部分:

public class BubbleSort implements Runnable {
private JButton addSize, addNum, bubSort;
private JLabel lblSize, lblNum;
private JTextField tfSize, tfNum;
private JPanel content, top, mid1, mid2, bottom;
private JTextArea ta;

int size, p, i, c, num;
int[] A;
String numbers;
String[] strNum;


@Override
public void run() {
    JFrame f = new JFrame();
    ..... 
    addSize = new JButton ("Enter");
    addSize.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            try{
                int size = Integer.parseInt(tfSize.getText());
                tfNum.requestFocus();
            }
            catch(NumberFormatException ex) {
                JOptionPane.showMessageDialog(f.getComponent(0), "Input is not a number");
            }
        }
    });
    final int[] A = new int[size];
    addNum = new JButton (" Add ");
    addNum.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            String numbers = tfNum.getText().trim();
            String[] strNum = numbers.split(",");
            for(i = 0; i < size; i++) {
                try{
                    A[i] = Integer.parseInt(strNum[i]);
                    System.out.println(Arrays.toString(A)); //what I used to check the for loop
                }
                catch(NumberFormatException nf) {
                    JOptionPane.showMessageDialog(f.getComponent(0), "No parsable integer!");
                }
            }
       });
    .....

    f.pack();
    f.setSize(500,500);
    f.setResizable(false);
    f.setVisible(true);

}
public static void main(String[] args) {
    SwingUtilities.invokeLater(new BubbleSort());
}

任何建议将不胜感激。

【问题讨论】:

  • 看起来你从未初始化过'size'。
  • @MitchWeaver 抱歉,我现在已经对其进行了编辑,以便您可以看到“size”在不同的 ActionListener 中被初始化

标签: java arrays for-loop actionlistener


【解决方案1】:

我能想出的一个解决方案是使用静态模型,这样您就可以在侦听器实例中修改模型并允许其他对象使用它。我找到了一个与我相似的solution

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多