为什么Java后台进程很慢?

3

请注意,我是新手Java程序员,之前只用过C#开发桌面应用。

我刚刚创建了一个全新的项目,并想在窗口打开时加载内容。我有一个带有JPanel(Swing)的JFrame,经过多次尝试,我发现“windowOpened”是C#中“onload”方法的等效项。但当我尝试使用此事件来加载内容时,尝试多次后我仍然得不到任何东西,于是我简单调用了System.out.print("Test");

JFrame成功加载,但是控制台上没有出现消息,直到我关闭了窗口。后来我添加了一个按钮玩耍,用相同的打印操作,但是在单击按钮时我在控制台上没有看到任何输出,除非我重复点击5到6次,这很奇怪。因此,我在打印语句后添加了一个showMessageDialog,结果很惊讶,信息对话框按预期工作,但在重复点击多次后才显示打印的消息。

这是我第三次尝试加载内容的全新项目,但它们似乎都是以相同的方式工作的,请问这是我的电脑问题还是Java的正常行为?我能改变这种行为吗?正确的做法是什么?

这是控制台日志:

cd PATH\NetBeansProjects\mavenproject1; "JAVA_HOME=C:\\Program Files\\Java\\jdk-16.0.2" cmd /c "\"PATH" -Dexec.vmArgs= -Dexec.args=\"${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}\" -Dexec.appArgs= -Dexec.mainClass=.mavenproject1.NewJFrame -Dexec.executable=\"PATH" -Dmaven.ext.class.path=\"PATH"
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...

-----------------------< mavenproject1 >------------------------
Building mavenproject1 1.0
--------------------------------[ jar ]---------------------------------

--- exec-maven-plugin:3.0.0:exec (default-cli) @ mavenproject1 ---
not working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expectednot working as expected
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time:  13.098 s
Finished at: 2021-08-16T17:14:40-05:00
------------------------------------------------------------------------

以下是代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package .mavenproject1;

import javax.swing.JOptionPane;

/**
 *
 * @author 
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        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() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jButton1.setText("jButton1");
        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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(196, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(131, 131, 131))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(196, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(79, 79, 79))
        );

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

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
       System.out.print("not working as expected");
    }                                 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       System.out.print("not working as expected");
       javax.swing.JOptionPane.showMessageDialog(this,"","",JOptionPane.OK_OPTION);
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }

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

4
缓冲输出。将“print”更改为“println”。 - apangin
一个问题是你在不理解Swing如何与GUI工作的情况下使用GUI Builder。Oracle有一个很棒的教程,使用Swing创建GUI,它将教你如何使用Swing。跳过Netbeans部分。 - Gilbert Le Blanc
@apangin,谢谢你的帮助,现在它可以工作了。你有没有什么文章或Javadoc可以让我更深入地了解这个问题?我看了Javadoc,但只找到了这个链接:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/BufferedOutputStream.html - Ezequiel
1
请参阅PrintStream(这是System.out流的类型)。 - apangin
如果您解决了问题,请发布并接受自己的问题答案,以标记此页面为已解决。这样您也可以帮助未来的读者。 - Basil Bourque
1个回答

1
正如@apangin所说,这是因为输出被缓存了,只需将print更改为println,即可看到即时结果,这正是我想要的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接