亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按下按鈕時不會重置時間

按下按鈕時不會重置時間

胡說叔叔 2023-07-13 15:44:01
我想創建一個有 2 個按鈕“Go”和“Stop”的程序。當我按 Go 時,程序會查找按下按鈕的時間,當我按 Stop 時,程序會查找按下此按鈕的時間,然后顯示 time2-time1。問題是,當我按下 Go 按鈕時,它會向我顯示新的 time2-time1,兩者都已重置,但還會打印一個新的重置的 time2 減去第一個 time1,就像卡在循環中一樣。    go.addActionListener(new ActionListener() {        public void actionPerformed(ActionEvent evt) {            GregorianCalendar timesi= new GregorianCalendar();            int time1 =timesi.get(Calendar.MINUTE);        stop.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {                GregorianCalendar timesi1= new GregorianCalendar();                int time2 =timesi1.get(Calendar.MINUTE);                System.out.println(time2-time1);            }        });        }    });當我第一次按下 Go 并經過 1 分鐘時,當我按“停止”時,它會打印 1,但是當我按下 Go 并且已經過去 3 分鐘時,它會打印 34,3 是重置時間,4 是舊時間1 。我該如何更改它,以便在 time1 和 time2 都重置的情況下只打印 3?
查看完整描述

1 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

在 go 的監聽器中添加 stop 的動作監聽器是搬起石頭砸自己的腳,因為這意味著 stop 可能會不必要地添加多個監聽器。因此,不要這樣做,而是在 go 的偵聽器之外并在與添加 go 的偵聽器相同的代碼級別上添加一次 stop 的偵聽器。另外,將 time1 變量設置為類的私有字段,以便它在 stop 的偵聽器中可見。就像是:


public class MyGui {

    private JButton go = new JButton("Go");

    private JButton stop = new JButton("stop");

    private int time = 0;


    public MyGui() {

        go.addActionListener(new ActionListener() {

            GregorianCalendar timesi = new GregorianCalendar();

            // int time1 = timesi.get(Calendar.MINUTE);

            time1 = timesi.get(Calendar.MINUTE); // use the field not a local class

        });


        // stop's listener added at the same level as the go's listener

        stop.addActionListener(new ActionListener() {

            GregorianCalendar timesi1 = new GregorianCalendar();

            int time2 = timesi1.get(Calendar.MINUTE);


            System.out.println(time2-time1);

        });


        // more code here

    }       


    // main method....

}

筆記:

  • 上面的代碼尚未編譯或測試,發布更多是為了展示概念,而不是復制和粘貼作為直接解決方案。

  • 最好使用更新且更干凈的java.time.LocalTime類,而不是java.util.TimeGregorianCalendar。

這是一個更完整的示例,使用 LocalTime。

在此示例中,goButton 的 ActionListener 將:

  • 將 LocalTime 字段的 startTime 設置為當前時間,LocalTime.now()

  • 檢查 Swing Timer 是否正在運行,如果是,則停止它

  • 然后創建一個新的 Swing Timer 并啟動它。該計時器將每 50 微秒重復檢查從開始到當前時間的持續時間,然后用表示該持續時間的文本更新 JLabel

stopButton 的偵聽器將:

  • 檢查是否按下了 go 按鈕,startTime 是否不再為空。

  • 如果是這樣,它將檢查 Swing Timer(計時器)是否不為空,如果它當前正在運行,則停止它。

  • 如果 Swing Timer 仍在運行,則停止計時器并設置一個表示停止時間 LocalTime 的字段。

  • 計算開始時間和停止時間之間的時間差,并將其打印出來。

import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.time.LocalTime;

import java.time.temporal.ChronoUnit;

import javax.swing.*;


@SuppressWarnings("serial")

public class TimerGui extends JPanel {

    private static final int TIMER_DELAY = 50;

    private LocalTime startTime;

    private LocalTime stopTime;

    private JLabel timerLabel = new JLabel("00:00", SwingConstants.CENTER);

    private Timer timer = null;

    private JButton goButton = new JButton("Go");

    private JButton stopButton = new JButton("Stop");

    private JButton exitButton = new JButton("Exit");


    public TimerGui() {

        // make the timer label's text larger

        timerLabel.setFont(timerLabel.getFont().deriveFont(Font.BOLD, 24f));

        timerLabel.setBorder(BorderFactory.createTitledBorder("Elapsed Time"));


        // alt-key hotkeys for my buttons

        goButton.setMnemonic(KeyEvent.VK_G);

        stopButton.setMnemonic(KeyEvent.VK_S);

        exitButton.setMnemonic(KeyEvent.VK_X);


        // add ActionListeners

        goButton.addActionListener(e -> {

            // reset startTime

            startTime = LocalTime.now();


            // if timer running, stop it

            if (timer != null && timer.isRunning()) {

                timer.stop();

            }

            timer = new Timer(TIMER_DELAY, new TimerListener());

            timer.start();

        });

        stopButton.addActionListener(e -> {

            // if start has already been pressed

            if (startTime != null) {

                // if timer running, stop it

                if (timer != null && timer.isRunning()) {

                    timer.stop();

                    stopTime = LocalTime.now();

                }

                long minuteDifference = startTime.until(stopTime, ChronoUnit.MINUTES);

                long secondDifference = startTime.until(stopTime, ChronoUnit.SECONDS);

                System.out.println("Time difference in minutes: " + minuteDifference);

                System.out.println("Time difference in seconds: " + secondDifference);

            }            

        });

        exitButton.addActionListener(e -> {

            System.exit(0);

        });


        JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));

        buttonPanel.add(goButton);

        buttonPanel.add(stopButton);

        buttonPanel.add(exitButton);


        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        setLayout(new BorderLayout(5, 5));

        add(timerLabel, BorderLayout.PAGE_START);

        add(buttonPanel);

    }


    private class TimerListener implements ActionListener {

        @Override

        public void actionPerformed(ActionEvent e) {

            LocalTime endTime = LocalTime.now();

            long secondDifference = startTime.until(endTime, ChronoUnit.SECONDS);


            int minutes = (int) (secondDifference / 60);

            int seconds = (int) (secondDifference % 60);

            String timeText = String.format("%02d:%02d", minutes, seconds);

            timerLabel.setText(timeText);

        }

    }


    private static void createAndShowGui() {

        TimerGui mainPanel = new TimerGui();


        JFrame frame = new JFrame("Timer");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(mainPanel);

        frame.pack();

        frame.setLocationRelativeTo(null);

        frame.setVisible(true);

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> createAndShowGui());

    }

}


查看完整回答
反對 回復 2023-07-13
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號