gpt4 book ai didi

java - 如何使用 JProgressBar 显示我的应用程序延迟?

转载 作者:行者123 更新时间:2023-12-02 00:52:54 27 4
gpt4 key购买 nike

我编写了一个简单的应用程序,我想用 JProgressBar 显示它的延迟,请帮助我;

我想用 Joptionpane 显示 JProgressBar ,带有取消按钮,它应该是模态的

这是我的源代码:

class CustomFrame extends JFrame {

private JProgressBar progressBar;

public CustomFrame() {
long start = System.currentTimeMillis();
myMethod();
this.getContentPane().setLayout(null);
this.setSize(200, 200);

//JOptionPane. ?????

this.setTitle("JFrame");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
long end = System.currentTimeMillis();
System.out.print("\nTime: " + (end - start));
}
public void myMethod(){
try {
java.io.File file = new java.io.File("i://m.txt");
BufferedReader input =
new BufferedReader(new FileReader(file));
String line;
while ((line = input.readLine()) != null) {
if (line.indexOf("CREATE KGCGI=") != -1 ){
System.out.println(line);
}
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
}

谢谢...

最佳答案

要使其正常工作,您需要执行以下几项操作:

  1. 您应该注意 Swing 中的线程问题。您的 GUI 绘制应该在 EventDispatchThread 上完成,磁盘 I/O 应该在工作线程中完成。请参阅this tutorialSwingWorker JavaDoc ,和SwingUtilities.invokeLater了解更多详情
  2. 然后,您需要获取文件的大小 (file.length()) 以确定如何确定进度条的范围 (myProgressBar.setMaximum(length) )
  3. 当您迭代文件中的行时,您将需要触发进度栏的更新 (myProgressBar.setValue(myProgressBar.getValue()+lineLength))。

通过批评的方式提出几点:

  • 你的构造函数不应该完成所有的工作(即加载文件并弹出一个可以取消的选项 Pane 。构造函数应该只完成创建对象所需的工作。你可能想要考虑让构造函数创建类,然后单独调用需要完成的工作,或者在 init() 方法之类的方法中调用。
  • 目前尚不清楚您将 JFrame 作为父类(super class)来做什么。 JOptionPane 是一个类,它将弹出一个非常基本的模式对话框,其中包含一些文本,可能是图标或输入字段。它不是嵌入在对话框中的面板。
  • 由于 JOptionPane 是用于创建基本消息对话框的非常基本的构造,因此使用 JDialog 可能会更容易,它也可以设为模态。 JDialog 将允许您根据需要添加按钮,而作为独立的 JOptionPane 将要求您使用“是/否”、“是/否/取消”或“确定/取消”等.
  • 如果您仍想使用 JOptionPane,并且仅显示取消按钮,则可以实例化 JOptionPane(而不是使用实用程序 show* 方法),进度条作为消息JOptionPane.CANCEL_OPTION 作为optionType 参数。您仍然需要将其放入 JDialog 中以使其可见。请参阅this tutorial了解更多详情:

JOptionPane (constructor)

Creates a JOptionPane with the specified buttons, icons, message, title, and so on. You must then add the option pane to a JDialog, register a property-change listener on the option pane, and show the dialog. See Stopping Automatic Dialog Closing for details.

关于java - 如何使用 JProgressBar 显示我的应用程序延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2278911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com