Java实现swing api,对象JButton的实例无法识别

时间:2017-11-15 15:46:10

标签: java swing

我有一个非常简单的小程序,使用swing库创建静态秒表。问题在于,每当我尝试使用“javac program.java”在命令行编译它时,它似乎会给出一系列错误,好像编译器无法识别与对象按钮相关的语句。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class StopWatch implements ActionListener {

    JLabel jlab;
    long start;  // holds the start time in milliseconds

    StopWatch() {
        // Create a new JFrame Container.
        JFrame jfrm = new JFrame("A Simple StopWatch");

        // Specify the FlowLayout for the layout manager.
        jfrm.setLayout(new FlowLayout());

        // Give the frame an initial size.
        jfrm.setSize(230,90);

        // Terminates the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make two buttons
        JButton JbtnStart = new JButton("Start");
        JButton JbtnStop = new JButton("Stop");

        // Add action listeners. 
        jbtnStart.addActionListener(this);
        jbtnStop.addActionListener(this);

        // Add the buttons to the content pane
        jfrm.add(jbtnStart); 
        jfrm.add(jbtnStop);

        // Create a text-based label
        jlab = new JLabel("Press Start to begin timing.");

        // Add the label
        jfrm.add(jlab);

        jfrm.setVisible(true);

    }

    // Handle button events
    public void actionPerformed(ActionEvent ae) {
        Calendar cal = Calendar.getInstance();  // get current system time

        if (ae.getActionCommand().equals("Start")) { 
            start = cal.getTimeInMillis();
            jlab.setText("Stopwatch is Running...");
        }

        else
            // Compute the elapsed time.
            jlab.setText("Elapsed time is "+(double)(cal.getTimeInMillis() - start)/1000);
    }

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

}

以下是错误消息:

StopWatch.java:30: error: cannot find symbol
jbtnStart.addActionListener(this);
        ^
Symbol:   variable jbtnStart
location: class StopWatch
StopWatch.java:31: error: cannot find symbol
jbtnStop.addActionListener(this);
        ^
symbol:   variable jbtnStop
location: class StopWatch
StopWatch.java:34: error: cannot find symbol
jfrm.add(jbtnStart); 
                 ^
symbol:   variable jbtnStart
location: class StopWatch
StopWatch.java:35: error: cannot find symbol
jfrm.add(jbtnStop);
                     ^
symbol:   variable jbtnStop
location: class StopWatch
4 errors

jbtnStop和jbtnStart会在java语言中成为保留字吗?

3 个答案:

答案 0 :(得分:1)

修正这些变量名称:

next_service_date

他们应该从小写字母开始:

JButton JbtnStart = new JButton("Start");
JButton JbtnStop = new JButton("Stop");

Java是一种区分大小写的语言,因此您应该小心命名

答案 1 :(得分:1)

我已使用text/xml对您的代码进行了更改JbtnStartjbtnStartJbtnStop

jbtnStop

答案 2 :(得分:0)

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d    

%matplotlib notebook

fig = ...

Java是一种区分大小写的语言。