简体   繁体   English

为什么在按下JButton之后什么也没发生

[英]Why nothing happens after JButton is pressed

I have the following code - all Netbeans generated except for the method defining the action that should be taken when the button is pressed. 我有以下代码-生成了除定义按下按钮时应采取的操作的方法以外的所有Netbeans。 When I press the button, first of all it doesn't come back up, and nothing appears in the standard output window in the Netbeans IDE. 当我按下按钮时,首先它不会恢复,并且在Netbeans IDE的标准输出窗口中什么也没有显示。 What is going wrong? 怎么了?

import javax.swing.JFrame;

public class CodeCenter extends JFrame {

    /**   
    * Creates new  form CodeCenter
    */
    public CodeCenter() {
        initComponents();
    }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Run");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addGap(288, 288, 288)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
        layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(17, 17, 17)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 548, Short.MAX_VALUE)
            .addContainerGap())
    );

         pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //writes each line of user code to seperate array place
        //userCodeArray can then be passed into an enhanced for loop to act on each line individually
        // May need to be moved into different class
        String[] userCodeArray = getTextasArray();

        System.out.println("Printing");

        if(userCodeArray[0].equals("TEST")) {
            System.out.println("Text read");
        } else {
            System.out.print("Text not read");
        }

    }                                        

    //Sets up Intrigued machine and the codecenter
    public static void main(String args[]) {

        //Not relevant to question
        IntriguedMachine machine = new IntriguedMachine();

        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(CodeCenter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CodeCenter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CodeCenter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CodeCenter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CodeCenter().setVisible(true);
            }
        });
    }

    //Takes the user code, splits it into a single String for each line, puts each String into userCodeArray, and returns userCodeArray
    //Not automatically-generated
        public String[] getTextasArray() {
            int lineCount = jTextArea1.getLineCount();
            String[] userCodeArray = new String[lineCount];
            for(int i = 0; i<lineCount; lineCount++){

                String [] throwawayArray = jTextArea1.getText().split("//n");
            userCodeArray = throwawayArray;
        }

        return userCodeArray;
    } //End of getTextasArray;

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration                   
}

Okay, no offense, but your getTextasArray function is totally jacked. 好的,没有冒犯,但您的getTextasArray函数完全被劫持了。 The reason that nothing happens when you press the JButton is because the for loop is infinite due to a typo, no doubt. 毫无疑问,按下JButton时什么也不发生的原因是因为输入错误, for循环是无限的。 Let's look at the loop declaration, shall we? 让我们看一下循环声明,好吗?

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

Can you see what's wrong? 你看到什么问题了吗? Look at the incrementer part. 看一下增量器部分。 Instead of incrementing i , you increment lineCount , which I don't think you meant to do. 不用增加i ,而是增加lineCount ,我认为这不是您想要的。 This means that i will never be greater than or equal to lineCount . 这意味着i将永远不会大于或等于lineCount You've gotta be careful about that stuff, as you saw first hand. 正如您亲眼所见,您必须小心这些内容。 :) :)

But let's just get rid of this loop and do it the right way. 但是,让我们摆脱这个循环并以正确的方式进行操作。 I kind of see what you were trying to accomplish by using that for loop, but there's a much easier way. 我有点想知道您要通过使用for循环来完成什么,但是有一种简单的方法。 Just write your function like this: 像这样编写您的函数:

public String[] getTextasArray() {
    return jTextArea1.getText().split("\n");       
}

This takes the text area and splits it by newlines. 这将占用文本区域并用换行符将其分割。 Notice that I used the string \\n instead of //n . 注意,我使用字符串\\n代替//n Using //n would split it by a literal 'slash slash N`. 使用//n会将其拆分为文字“斜杠//n ”。 Hopefully this'll get you what you want! 希望这会给您您想要的!

The problem is this line 问题是这条线

String[] userCodeArray = getTextasArray();

Specifically 特别

for(int i = 0; i < lineCount; lineCount++) {
        String [] throwawayArray = jTextArea1.getText().split("//n");
        userCodeArray = throwawayArray;
    }

You are not incrementing i here, but lineCount. 您不是在这里递增i,而是lineCount。 This leads to an infinite loop where the handler never terminates. 这导致处理程序永不终止的无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM