java - 如何获取计时器(Util 或 Swing)以允许我调用 Netbeans 桌面应用程序中的方法?

标签 java swing timer jsr296

(完整源代码在底部)

所以现在我已经花了相当长的一段时间来研究这个问题。我有一个最终目标,但为了学习如何做到这一点,我创建了一个应用程序,它只需将数字加 1 并每秒将其显示为 jLabel1。我的问题是我无法让 Timer 工作。

我的研究向我展示了不同的方法,以及使用包 java.util.timerjavax.swing.timerTimer 函数的示例>。迄今为止,它们都没有发挥作用。这绝不是代码错误的问题,而是某些方法似乎没有被调用。在我的大多数试验中,这通常归结为时间表方法。在我最近的尝试中,它归结为:

new Timer(delay, taskPerformer).start();

一直给我带来问题。原来的错误是

illegal start of type

invalid method declaration; return type required

cannot find symbol
  symbol:   class delay
  location: class timer.TimerView.two

<identifier> expected

cannot find symbol
  symbol:   class taskPerformer
  location: class timer.TimerView.two

<identifier> expected

';' expected

延迟明确定义为整数,但即使我用 1000 替换延迟后,它也会告诉我

illegal start of type

invalid method declaration; return type required

illegal start of type

所以现在我很茫然。我看了又看,我见过很多成功的故事,但它们几乎从不与 netbeans 默认 bs 一起工作。我无法导入 java.util.timer ,因为根据我的理解,javax.swing.timer 导入它本身或一些废话。

我很少寻求帮助,但在几个小时的查找过程中,我得到了与 36 小时前完全相同的源代码,但有一堆橡皮擦烧伤。所以我真的希望有人至少能指出我正确的方向。我看过 Oricals 教程等。这总是让我留在同一个地方。我尝试过操纵其他使用计时器功能的程序,甚至尝试对 netbeans 中空白桌面应用程序附带的状态栏进行逆向工程。只是似乎没有什么想要工作。或者更有可能的是,我的经验不足让我找错了地方。在我看来,这并不是一个罕见的问题,但我无法让它发挥作用。下面发布的是我的完整程序,由于其简单性,它与空白的 Netbeans 应用程序相差不远。 (它只有一个 jLabel 和我一直在研究的类)

/*
 * TimerView.java
 */

package timer;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;

/**
 * The application's main frame.
 */
public class TimerView extends FrameView {

    public TimerView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = TimerApp.getApplication().getMainFrame();
            aboutBox = new TimerAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        TimerApp.getApplication().show(aboutBox);
    }

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

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(timer.TimerApp.class).getContext().getResourceMap(TimerView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(178, 178, 178)
                .addComponent(jLabel1)
                .addContainerGap(188, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(107, 107, 107)
                .addComponent(jLabel1)
                .addContainerGap(133, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(timer.TimerApp.class).getContext().getActionMap(TimerView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>




   public class two {



        int delay = 1000;
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {

          int Number = 0;
          String Output;
          Number++;
          Output = Integer.toString(Number);
          jLabel1.setText(Output);
      }
  };
  new Timer(1000, taskPerformer).start();


   }







    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}

最佳答案

1) 我建议使用javax.swing.Timer而不是 java.util.Timer,因为 javax.swing.Timer 的输出始终为 EDT

2) 从 java.util.Timer 到 GUI 的输出必须包装到 invokeLater 中,否则无法保证任何内容都应该显示/更改/重新绘制

3) 要了解更多信息,您必须阅读Concurency in Swing

4) 我建议您手动创建代码,而不是使用不受支持的 Java 桌面应用程序 并使用 GroupLayout 进行布局,

关于java - 如何获取计时器(Util 或 Swing)以允许我调用 Netbeans 桌面应用程序中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485151/

相关文章:

Qt: 如何实现 "per minute"定时器?避免失火和双火的更好选择?

Java 事件绑定(bind)

java - 将按钮添加到 GXT 网格单元

java - 用于检查在 Java 中不起作用的允许字符的正则表达式

java - 通过按钮作为显示面板打开另一个类(class)

java - Swing JSplitPane问题

javascript - ReactJS:单击按钮时调用计时器函数

java - 如何从 mySql 数据库中只读取 10 行?

java - 如何在没有用户单击的情况下单击 JButton?

c++ - 如何使用 Boost 库创建 TimerHandler