- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
@HovercraftFullofEels 很友善地帮助我,为我提供了以下代码的基础,我对其进行了一些修改(标有“行完全添加”注释和末尾的巨大注释,其中包含要放置的代码文件中的某处)。
原始文件是一个简单的秒表,我的修改是包含 3 个 JTextFields。分别表示分钟、秒和厘秒(1 厘秒 = 1/100 秒)。我还想包含一个“提交”按钮,它允许程序读取这 3 个文本字段的输入。我编写了单击“提交”时调用的方法的代码(包含在最后的巨大注释中)。单击它后,我希望程序立即从这些值开始倒计时从秒表启动的时间开始,而不是从单击按钮的时间开始。例如,如果秒表已经运行了20分钟,当用户点击“提交”并输入25分钟的时间时,就会开始5分钟的倒计时。
如果这仍然令人困惑,那么您真正需要知道的是我的方法以一行结尾,该行提供了我想要倒计时开始的位置的毫秒表示,此时我希望倒计时取代秒表。我还想删除“暂停”和“停止”按钮,但不是“开始”按钮(您会认为它们很容易删除,但我删除了我认为合适的内容并在编译时收到错误)并替换只需单击“提交”按钮即可。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.Font; //line completely added
import javax.swing.*;
@SuppressWarnings("serial")
public class MyTimer2 extends JPanel implements GuiTimer {
private static final String TIME_FORMAT = "%02d:%02d:%02d"; //changed from "%03d:%03d"
private static final int EXTRA_WIDTH = 50;
private JLabel timerLabel = new JLabel();
private TimerControl timerControl = new TimerControl(this);
JTextField minsField, secsField, centisField; //line completely added - should this be private?
JLabel colon, period; //line completely added - should this be private?
public MyTimer2() {
JPanel topPanel = new JPanel();
topPanel.add(timerLabel);
timerLabel.setFont(new Font("Arial", Font.BOLD, 64)); //line completely added
minsField = new JTextField("", 2);
secsField = new JTextField("", 2);
centisField = new JTextField("", 2);
colon = new JLabel(":");
period = new JLabel(".");
JPanel centerPanel = new JPanel();
centerPanel.add(minsField); //line completely added
centerPanel.add(colon); //line completely added
centerPanel.add(secsField); //line completely added
centerPanel.add(period); //line completely added
centerPanel.add(centisField); //line completely added
JPanel bottomPanel = new JPanel(); //line completely added
bottomPanel.add(new JButton(timerControl.getStartAction())); //changed from centerPanel
bottomPanel.add(new JButton(timerControl.getStopAction())); //changed from centerPanel
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END); //line completely added
setDeltaTime(0);
}
@Override
public void setDeltaTime(int delta) {
int mins = (int) delta / 60000; // line completely added
int secs = ((int) delta % 60000) / 1000; // %60000 added
int centis = ((int) delta % 1000) / 10; // / 10 added
timerLabel.setText(String.format(TIME_FORMAT, mins, secs, centis)); // mins added; mSecs changed to centis
}
@Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = superSz.width + EXTRA_WIDTH;
int prefH = superSz.height;
return new Dimension(prefW, prefH);
}
private static void createAndShowGui() {
MyTimer2 mainPanel = new MyTimer2();
JFrame frame = new JFrame("MyTimer2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //changed from DISPOSE_ON_CLOSE
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
interface GuiTimer {
public abstract void setDeltaTime(int delta);
}
@SuppressWarnings("serial")
class TimerControl {
private static final int TIMER_DELAY = 10;
private long startTime = 0;
private long pauseTime = 0;
private Timer timer;
private GuiTimer gui;
private StartAction startAction = new StartAction();
private StopAction stopAction = new StopAction();
public TimerControl(GuiTimer gui) {
this.gui = gui;
}
public Action getStopAction() {
return stopAction;
}
public Action getStartAction() {
return startAction;
}
enum State {
START("Start", KeyEvent.VK_S),
PAUSE("Pause", KeyEvent.VK_P);
private String text;
private int mnemonic;
private State(String text, int mnemonic) {
this.text = text;
this.mnemonic = mnemonic;
}
public String getText() {
return text;
}
public int getMnemonic() {
return mnemonic;
}
};
private class StartAction extends AbstractAction {
private State state;
public StartAction() {
setState(State.START);
}
public final void setState(State state) {
this.state = state;
putValue(NAME, state.getText());
putValue(MNEMONIC_KEY, state.getMnemonic());
}
@Override
public void actionPerformed(ActionEvent e) {
if (state == State.START) {
if (timer != null && timer.isRunning()) {
return; // the timer's already running
}
setState(State.PAUSE);
if (startTime <= 0) {
startTime = System.currentTimeMillis();
timer = new Timer(TIMER_DELAY, new TimerListener());
} else {
startTime += System.currentTimeMillis() - pauseTime;
}
timer.start();
} else if (state == State.PAUSE) {
setState(State.START);
pauseTime = System.currentTimeMillis();
timer.stop();
}
}
}
private class StopAction extends AbstractAction {
public StopAction() {
super("Stop");
int mnemonic = KeyEvent.VK_T;
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent e) {
if (timer == null) {
return;
}
timer.stop();
startAction.setState(State.START);
startTime = 0;
}
}
private class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
long time = System.currentTimeMillis();
long delta = time - startTime;
gui.setDeltaTime((int) delta);
}
}
}
/*not sure where this will go, but this is the code for clicking "Submit"
//upon clicking "Submit"...
public void actionPerformed(ActionEvent e)
{
String minsStr = minsField.getText();
String secsStr = secsField.getText();
String centisStr = centisField.getText();
int minsInput = Integer.parseInt(minsStr);
int secsInput = Integer.parseInt(secsStr);
int centisInput = Integer.parseInt(centisStr);
long millis = minsInput * 60000 + secsInput * 1000 + centisInput * 10;
long millisCountdown = millis - delta; //where "delta" is elapsed milliseconds
if(millisCountdown < 0)
JOptionPane.showMessageDialog("Invalid time entered.");
else
//then immediately change from stopwatch to countdown beginning from millisCountdown and ending at 00:00:00
minsField.setText(""); //clear minsField
secsField.setText(""); //clear secsField
centisField.setText(""); //clear centisField
}
*/
如果有人能帮助我解决这个问题,我将不胜感激。不幸的是,我不理解 Hovercraft 的大部分代码,所以我不知道在我已经完成的事情之后该去哪里。
谢谢!
编辑:这是@MadProgrammer代码的更新版本:
import java.awt.EventQueue;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Font;
import java.time.Duration;
import java.time.LocalTime;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class StopWatch {
public static void main(String[] args) {
new StopWatch();
}
public StopWatch() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final String TIME_FORMAT = "%02d:%02d.%02d";
private LocalTime startTime;
private LocalTime targetTime;
private JLabel label;
private JTextField minsField, secsField, centisField;
private JButton start, submit;
private Timer timer;
public TestPane() {
JPanel topRow = new JPanel();
JPanel centerRow = new JPanel();
JPanel bottomRow = new JPanel();
label = new JLabel(formatDuration(Duration.ofMillis(0)));
topRow.add(label);
minsField = new JTextField("", 2);
secsField = new JTextField("", 2);
centisField = new JTextField("", 2);
centerRow.add(minsField);
centerRow.add(secsField);
centerRow.add(centisField);
start = new JButton("Start");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!timer.isRunning()) {
startTime = LocalTime.now();
timer.start();
}
}
});
bottomRow.add(start);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
Duration runningTime = Duration.between(startTime, LocalTime.now());
// Subtract the required amount of time from the duration
String minsStr = minsField.getText();
String secsStr = secsField.getText();
String centisStr = centisField.getText();
if(minsStr.matches("\\d+$") && secsStr.matches("\\d+$") && centisStr.matches("\\d+$"))
{
int minsInput = Integer.parseInt(minsStr);
int secsInput = Integer.parseInt(secsStr);
int centisInput = Integer.parseInt(centisStr);
if(minsInput >= 0 && secsInput >= 0 && secsInput < 60 && centisInput >= 0 && centisInput < 100)
{
long millis = minsInput * 60000 + secsInput * 1000 + centisInput * 10;
runningTime = runningTime.minusMillis(millis);
timer.start();
// No negative times
if (runningTime.toMillis() > 0)
{
// When the timer is to end...
targetTime = LocalTime.now().plus(runningTime);
}
else
{
JOptionPane.showMessageDialog(null, "Invalid time entered.");
}
}
else
{
timer.start();
JOptionPane.showMessageDialog(null, "Invalid time entered.");
}
}
else
{
timer.start();
JOptionPane.showMessageDialog(null, "Invalid time entered.");
}
minsField.setText("");
secsField.setText("");
centisField.setText("");
}
}
});
bottomRow.add(submit);
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (targetTime != null) {
Duration duration = Duration.between(LocalTime.now(), targetTime);
if (duration.toMillis() <= 0) {
duration = Duration.ofMillis(0);
timer.stop();
targetTime = null;
}
label.setText(formatDuration(duration));
} else {
// Count up...
Duration duration = Duration.between(startTime, LocalTime.now());
label.setText(formatDuration(duration));
}
}
});
setLayout(new BorderLayout());
label.setFont(new Font("Arial", Font.BOLD, 64));
add(topRow, BorderLayout.PAGE_START);
add(centerRow, BorderLayout.CENTER);
add(bottomRow, BorderLayout.PAGE_END);
}
protected String formatDuration(Duration duration) {
long mins = duration.toMinutes();
duration = duration.minusMinutes(mins);
long seconds = duration.toMillis() / 1000;
duration = duration.minusSeconds(seconds);
long centis = duration.toMillis() / 10;
return String.format(TIME_FORMAT, mins, seconds, centis);
}
}
}
最佳答案
这利用新的 Java 8 Time API 来简化流程,允许您计算两个时间点之间的持续时间以及算术
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.LocalTime;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class StopWatch {
public static void main(String[] args) {
new StopWatch();
}
public StopWatch() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final String TIME_FORMAT = "%02dh %02dm %02ds";
private LocalTime startTime;
private LocalTime targetTime;
private JLabel label;
private JButton start;
private Timer timer;
public TestPane() {
label = new JLabel(formatDuration(Duration.ofMillis(0)));
start = new JButton("Start");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
Duration runningTime = Duration.between(startTime, LocalTime.now());
// Subtract the required amount of time from the duration
runningTime = runningTime.minusSeconds(5);
// No negative times
if (runningTime.toMillis() > 0) {
// When the timer is to end...
targetTime = LocalTime.now().plus(runningTime);
timer.start();
}
} else {
startTime = LocalTime.now();
timer.start();
}
}
});
timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (targetTime != null) {
Duration duration = Duration.between(LocalTime.now(), targetTime);
if (duration.toMillis() <= 0) {
duration = Duration.ofMillis(0);
timer.stop();
targetTime = null;
}
label.setText(formatDuration(duration));
} else {
// Count up...
Duration duration = Duration.between(startTime, LocalTime.now());
label.setText(formatDuration(duration));
}
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(label, gbc);
add(start, gbc);
}
protected String formatDuration(Duration duration) {
long hours = duration.toHours();
duration = duration.minusHours(hours);
long mins = duration.toMinutes();
duration = duration.minusMinutes(mins);
long seconds = duration.toMillis() / 1000;
return String.format(TIME_FORMAT, hours, mins, seconds);
}
}
}
I also want to remove the "Pause" and "Stop" buttons (you would think they would be easy to remove, but I removed what I thought was appropriate and received an error when compiling) and replace them with the single "Submit" button.
看看Creating a GUI With JFC/Swing了解更多详情
Unfortunately I don't understand the majority of Hovercraft's code
我们为您提供的任何其他解决方案都会得到相同的结果。您需要将您的需求分解为可管理的 block ,计算出计时器如何向前移动,然后计算出如何使其向后移动,然后计算出如何将这两个概念结合起来,以便您可以从运行中减去目标值时间并将其向后移动。
关于Java - 更新现有秒表代码以包括倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512527/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!