繁体   English   中英

尽管有值可以使用,但setValue无法工作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM