java - 如何嵌入我的秒表

标签 java swing netbeans timer gui-builder

我通过netbeans用Java编写了一个程序,在现有的项目中我想添加一个秒表。我有以下 Java 秒表代码,但我无法确定将其嵌入到我的程序中的方法:

//All the imports were written here (I deleted them to make the code clear)   


public class NewJFrame extends javax.swing.JFrame {

Toolkit toolkit;
Timer timer;


public NewJFrame() {


    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            JFrame frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new TestPane());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });

}


public class TestPane extends JPanel {

    private JTextField field;
    private JButton button;
    private int tick; 
    private Timer timer;

    public TestPane() {

        field = new JTextField(10);
        field.setEditable(false);
        button = new JButton("Start");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                button.setEnabled(false);
                tick = 0;
                timer.start();
            }
        });

        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                field.setText(Integer.toString(++tick));
                if (tick > 4) {
                    timer.stop();
                    button.setEnabled(true);
                }
            }
        });
        timer.setInitialDelay(0);

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        add(field, gbc);
        add(button, gbc);

    }
}




/**
 * Creates new form NewJFrame
 */


/**
 * 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() {

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );

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

/**
 * @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
     */


    System.out.format("About to schedule task.%n");
    new NewJFrame();
System.out.format("Task scheduled.%n");



    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
// End of variables declaration                   
}

我无法弄清楚什么是 TestPane 以及如何在没有 Testpane 的情况下做到这一点,因为在上面的代码中 gui 元素是通过编写 java 代码创建的,但在我想要嵌入它的程序中,我使用了 netbeans GUI构建器来完成所有 GUI 元素的制作。 那么如何嵌入它呢?

最佳答案

由于您使用的是 Netbeans GUI Builder,因此嵌入秒表的最简单方法是创建一个 JPanel 表单并将计时器代码放在那里。您还可以在该类中使用启动、停止、重置时钟的方法。然后,您可以从包资源管理器中将 JPanel 拖到 JFrame 上,如 here 所示。

关于java - 如何嵌入我的秒表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910104/

相关文章:

java - 关于Java语法的基本问题

Java AWT-EventQueue-0 错误

java - Swing - JTabbedPane - 两个选项卡均未显示面板

java - 可运行 jar 文件中的 RXTX - 为什么它不起作用?

java - 以矩阵格式打印二维数组

java - cursor.getstring() 在数据库中获取错误的字段

java - 跨 JVM 分配订阅者

java - 当图标为空时,JLabel 出现意外的文本对齐行为

java - Netbeans:为 JEditorPane 中的 Java 语法添加颜色

Java Jlayer Mp3 Player - 如何重复和停止歌曲