Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 时间不会';t在Applet中重新绘制_Java_Date_Time_Applet - Fatal编程技术网

Java 时间不会';t在Applet中重新绘制

Java 时间不会';t在Applet中重新绘制,java,date,time,applet,Java,Date,Time,Applet,我有一个小问题,但我不知道如何解决它。我创建了一个简单的小程序,其中应该是简单的数字时钟。我正确创建了所有方法,但重新绘制方法不会重新绘制小程序。你能查一下我的密码并告诉我哪里错了吗。谢谢 public class DigitalClock extends JApplet implements Runnable { private Thread timeThread; Date date = new Date(); public void start() { timeThread =

我有一个小问题,但我不知道如何解决它。我创建了一个简单的小程序,其中应该是简单的数字时钟。我正确创建了所有方法,但重新绘制方法不会重新绘制小程序。你能查一下我的密码并告诉我哪里错了吗。谢谢

public class DigitalClock extends JApplet implements Runnable {

private Thread timeThread;
Date date = new Date();

public void start() {
    timeThread = new Thread(this, "Clock");
    timeThread.start();
}

@Override
public void stop() {
    if (timeThread == null) {
        return;
    }
    timeThread = null;
}

@Override
public void run() {
    while (timeThread != null) {
        repaint();
        try {
            timeThread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
}

@Override
public void paint(Graphics g) {
    date.setTime(System.currentTimeMillis());
    g.drawString(date.toString(), 50, 95);
}
}

您应该使用私有属性,如

private boolean running = true;
在停止方法中将其设置为
false
。在run方法中,您将其作为停止条件进行计算,而不是计算
timeThread!=空
。此过程更安全,因为否则您会在run方法中遇到由
NullPointerException
引起的并发问题


您应该通过在浏览器插件中查看其控制台输出来检查小程序的状态。您看到异常了吗?

您应该使用私有属性,如

private boolean running = true;
在停止方法中将其设置为
false
。在run方法中,您将其作为停止条件进行计算,而不是计算
timeThread!=空
。此过程更安全,因为否则您会在run方法中遇到由
NullPointerException
引起的并发问题


您应该通过在浏览器插件中查看其控制台输出来检查小程序的状态。您看到异常了吗?

只需使用
javax.swing.Timer

这里有一个例子。但是,与您正在做的在顶级容器(如
JApplet
)上进行绘制不同,我在
JPanel
上进行绘制,这是更推荐的

import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;

public class TimerPanel extends JPanel {

    private String dateString;
    private final SimpleDateFormat format;
    private final Font font;
    private final Date date;

    public TimerPanel() {
        format = new SimpleDateFormat("hh:mm:ss a");
        font = new Font("impact", Font.PLAIN, 30);
        date = new Date();

        date.setTime(System.currentTimeMillis());
        dateString = format.format(date);

        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                date.setTime(System.currentTimeMillis());
                dateString = format.format(date);
                repaint();
            }
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setFont(font);
        FontMetrics fm = g.getFontMetrics(font);
        int width = fm.stringWidth(dateString);
        int height = fm.getAscent();
        int x = getWidth() / 2 - width / 2;
        int y = getHeight() / 2 + height / 2;

        g.drawString(dateString, x, y);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 100);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TimerPanel timer = new TimerPanel();
                JOptionPane.showMessageDialog(
                        null, timer, "Digital Clock", JOptionPane.PLAIN_MESSAGE);
            }
        });
    }
}


更直接地回答您的问题,您的代码在我测试它时工作,您唯一忘记做的事情就是调用
super.paint()
。完成此操作后,工作正常

@Override
public void paint(Graphics g) {
    super.paint(g);

不过,你要避免使用
线程。您可能会注意到这会导致闪烁。最好使用
javax.swing.Timer
。这就是为什么我首先用我的例子回答。

只需使用
javax.swing.Timer

这里有一个例子。但是,与您正在做的在顶级容器(如
JApplet
)上进行绘制不同,我在
JPanel
上进行绘制,这是更推荐的

import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;

public class TimerPanel extends JPanel {

    private String dateString;
    private final SimpleDateFormat format;
    private final Font font;
    private final Date date;

    public TimerPanel() {
        format = new SimpleDateFormat("hh:mm:ss a");
        font = new Font("impact", Font.PLAIN, 30);
        date = new Date();

        date.setTime(System.currentTimeMillis());
        dateString = format.format(date);

        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                date.setTime(System.currentTimeMillis());
                dateString = format.format(date);
                repaint();
            }
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setFont(font);
        FontMetrics fm = g.getFontMetrics(font);
        int width = fm.stringWidth(dateString);
        int height = fm.getAscent();
        int x = getWidth() / 2 - width / 2;
        int y = getHeight() / 2 + height / 2;

        g.drawString(dateString, x, y);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 100);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TimerPanel timer = new TimerPanel();
                JOptionPane.showMessageDialog(
                        null, timer, "Digital Clock", JOptionPane.PLAIN_MESSAGE);
            }
        });
    }
}


更直接地回答您的问题,您的代码在我测试它时工作,您唯一忘记做的事情就是调用
super.paint()
。完成此操作后,工作正常

@Override
public void paint(Graphics g) {
    super.paint(g);

不过,你要避免使用
线程。您可能会注意到这会导致闪烁。最好使用
javax.swing.Timer
。这就是为什么我首先用我的例子来回答。

再看另一个例子。作为@peeskillet的回答,我还使用了
JPanel
来显示时间,但在我的代码中,我使用
JLabel
来显示时间

public class ClockPane extends JPanel {

    private JLabel clock;

    public ClockPane() {
        setLayout(new BorderLayout());
        clock = new JLabel();
        clock.setHorizontalAlignment(JLabel.CENTER);
        clock.setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 32f));
        tickTock();
        add(clock);

        Timer timer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tickTock();
            }
        });
        timer.setRepeats(true);
        timer.setCoalesce(true);
        timer.setInitialDelay(0);
        timer.start();
    }

    public void tickTock() {
        clock.setText(DateFormat.getDateTimeInstance().format(new Date()));
    }
    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            ClockPane clock = new ClockPane();
            JOptionPane.showMessageDialog(
                    null, clock, "Digital Clock", JOptionPane.PLAIN_MESSAGE);
        }
    });
    }
}


再看另一个例子。作为@peeskillet的回答,我还使用了
JPanel
来显示时间,但在我的代码中,我使用
JLabel
来显示时间

public class ClockPane extends JPanel {

    private JLabel clock;

    public ClockPane() {
        setLayout(new BorderLayout());
        clock = new JLabel();
        clock.setHorizontalAlignment(JLabel.CENTER);
        clock.setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 32f));
        tickTock();
        add(clock);

        Timer timer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tickTock();
            }
        });
        timer.setRepeats(true);
        timer.setCoalesce(true);
        timer.setInitialDelay(0);
        timer.start();
    }

    public void tickTock() {
        clock.setText(DateFormat.getDateTimeInstance().format(new Date()));
    }
    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            ClockPane clock = new ClockPane();
            JOptionPane.showMessageDialog(
                    null, clock, "Digital Clock", JOptionPane.PLAIN_MESSAGE);
        }
    });
    }
}


为什么要编写小程序?如果是由于老师的特殊要求,请参考。为什么要编写小程序?如果是由于老师的特殊要求,请参考。