[英]setValue wont work though there is a value to use
嗨,我試圖讓進度條正常工作,我有一個值,並且無法訪問屬性,這是我的代碼,只是表單,因為我知道進度已經過去,因為我可以使用getValue將其打印出來,這是我的代碼
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mashisgood;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JProgressBar;
/**
*
* @author brett
*/
public class MashForm extends javax.swing.JFrame {
private JProgressBar progressBar;
/**
* Creates new form MashForm
*/
public MashForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
fileChooser = new javax.swing.JFileChooser();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jProgressBar1 = new javax.swing.JProgressBar();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setText("Add afile to compile");
jProgressBar1.setToolTipText("");
jProgressBar1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jProgressBar1.setStringPainted(true);
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(jButton2)
.addContainerGap(175, Short.MAX_VALUE))
);
jProgressBar1.getAccessibleContext().setAccessibleName("mystatusbar");
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
jTextField1.setText(file.getAbsolutePath());
} else {
System.out.println("File access cancelled by user.");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//MashIsGood goodo = new MashIsGood();
String[] arguments = new String[] {"1234"};
try {
MashIsGood.main(arguments);
} catch (IOException ex) {
Logger.getLogger(MashForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
void setPGValue(int progress) {
jProgressBar1.setValue(progress);
System.out.println("Get Value:"+" "+jProgressBar1.getValue());
jProgressBar1.setValue(69);
setbar(progress);
}
public void setbar(int goods){
jProgressBar1.setValue(goods);
//System.out.println();
//return
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MashForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new MashForm().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JFileChooser fileChooser;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
public static javax.swing.JProgressBar jProgressBar1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
這是第二節課
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mashisgood;
import java.io.*;
import java.util.Scanner;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.stage.Stage;
/**
*
* @author brett
*/
public class MashIsGood extends Application {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", "C:\\Users\\brett\\Documents\\Telegraph_Road.mp4", "C:\\Users\\brett\\Documents\\out.mp4");
final Process p = pb.start();
// create a new thread to get progress from ffmpeg command , override
// it's run method, and start it!
new Thread() {
@Override
public void run() {
Scanner sc = new Scanner(p.getErrorStream());
// Find duration
Pattern durPattern = Pattern.compile("(?<=Duration: )[^,]*");
String dur = sc.findWithinHorizon(durPattern, 0);
if (dur == null) {
throw new RuntimeException("Could not parse duration.");
}
String[] hms = dur.split(":");
double totalSecs = Integer.parseInt(hms[0]) * 3600 + Integer.parseInt(hms[1]) * 60 + Double.parseDouble(hms[2]);
System.out.println("Total duration: " + totalSecs + " seconds.");
// Find time as long as possible.
Pattern timePattern = Pattern.compile("(?<=time=)[\\d:.]*");
String match;
String[] matchSplit;
while (null != (match = sc.findWithinHorizon(timePattern, 0))) {
matchSplit = match.split(":");
double progress = (Integer.parseInt(matchSplit[0]) * 3600 + Integer.parseInt(matchSplit[1]) * 60 + Double.parseDouble(matchSplit[2])) / totalSecs;
// System.out.printf("Progress: %.2f%%%n", progress * 100);
MashForm pgbar = new MashForm();
int prog = (int)(progress * 100);
pgbar.setPGValue(prog);
pgbar.setbar(prog);
}
}
}.start();
}
@Override
public void start(Stage primaryStage) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
在您的類MashIsGood中,您在while循環的每次迭代中創建一個MashForm對象。
因此,您始終會設置未運行實例的新進度條的值,並立即將其丟棄。
您必須將正在運行的MashForm實例傳遞給Thread並使用該實例。
更改並重命名您的類MashIsGood的主要方法以傳遞MashForm實例(重命名僅是為了不與啟動應用程序的主進入方法混淆)。
class MashIsGood {
//public static void main(String[] args) throws IOException {
public static void startThread(MashForm mashForm) throws IOException {
然后使用此參數設置進度條值;
while (null != (match = sc.findWithinHorizon(timePattern, 0))) {
matchSplit = match.split(":");
double progress = (Integer.parseInt(matchSplit[0]) * 3600 + Integer.parseInt(matchSplit[1]) * 60 + Double.parseDouble(matchSplit[2])) / totalSecs;
// System.out.printf("Progress: %.2f%%%n", progress * 100);
int prog = (int)(progress * 100);
mashForm.setPGValue(prog);// <-- Use mashForm
mashForm.setbar(prog);
}
然后在MashForm中更改您的ActionListener並將MashForm實例傳遞給startThread
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// MashIsGood.main(arguments);
MashIsGood.startThread(this);
} catch (IOException ex) {
Logger.getLogger(MashForm.class.getName()).log(Level.SEVERE, null,ex);
}
}
就是這樣。 它有效,我已經測試過了。
嗨,我看了一眼:)我不知道您要做什么,但是
改變這個
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
//MashIsGood goodo = new MashIsGood();
String[] arguments = new String[] {"1234"};
this.main(arguments);
}
到您想要button2做的任何事情:)
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
//MashIsGood goodo = new MashIsGood();
String[] arguments = new String[] {"1234"};
setPGValue(jProgressBar1.getValue() + 1);
}
每當您點擊按鈕2時,這將使進度條的值增加1 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.