【问题标题】:Can't access variables for SwingWorker无法访问 SwingWorker 的变量
【发布时间】:2013-06-18 01:44:13
【问题描述】:

我正试图让这个 SwingWorker 正常工作。但是,需要访问的变量似乎不是全局的。我该怎么办?我尝试添加静态,但它会在以后从非静态访问静态产生更多错误和复杂性。 SwingWorker 中不起作用的变量是 LOCAL_FILE 和 URL_LOCATION 变量。

package professorphysinstall;

//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;

public class ProfessorPhysInstall {

/**
 * @param args the command line arguments
 */

static class Global {
   public String location;
}

public static void main(String[] args) {
    // TODO code application logic here
    //Variables
    final JFrame mainframe = new JFrame();
    mainframe.setSize(500, 435);
    final JPanel cards = new JPanel(new CardLayout());
    final CardLayout cl = (CardLayout)(cards.getLayout());
    mainframe.setTitle("Future Retro Gaming Launcher");
    //Screen1
    JPanel screen1 = new JPanel();
    JTextPane TextPaneScreen1 = new JTextPane();
    TextPaneScreen1.setEditable(false);
    TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
    TextPaneScreen1.setText("Welcome to the install wizard  for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
    TextPaneScreen1.setSize(358, 48);
    TextPaneScreen1.setLocation(0, 0);
    TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    TextPaneScreen1.setMargin(new Insets(4,4,4,4));
    screen1.add(TextPaneScreen1);
    JTextArea TextAreaScreen1 = new JTextArea();
    JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
    TextAreaScreen1.setRows(15);
    TextAreaScreen1.setColumns(40);
    TextAreaScreen1.setEditable(false);
    TextAreaScreen1.setText("stuff");
    TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    TextAreaScreen1.setMargin(new Insets(4,4,4,4));
    screen1.add(sbrText);
    final JCheckBox Acceptance = new JCheckBox();
    Acceptance.setText("I Accept The EULA Agreenment.");
    screen1.add(Acceptance);
    final JButton NextScreen1 = new JButton();
    NextScreen1.setText("Next");
    NextScreen1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            if(Acceptance.isSelected())
                cl.next(cards);
        }
    });      
    screen1.add(NextScreen1);        
    JButton CancelScreen1 = new JButton();
    CancelScreen1.setText("Cancel");
    CancelScreen1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            System.exit(0);
        }
    });      
    screen1.add(CancelScreen1);
    cards.add(screen1);

    //Screen2
    final JPanel screen2 = new JPanel();
    JPanel screen3 = new JPanel();
    JTextPane TextPaneScreen2 = new JTextPane();
    TextPaneScreen2.setEditable(false);
    TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
    TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
    TextPaneScreen2.setSize(358, 48);
    TextPaneScreen2.setLocation(0, 0);
    TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    TextPaneScreen2.setMargin(new Insets(4,4,4,4));
    screen2.add(TextPaneScreen2);
    JLabel screen2instructions = new JLabel();
    screen2instructions.setText("Launcher Location: ");
    screen2.add(screen2instructions);
    final JTextField folderlocation = new JTextField(25);
    screen2.add(folderlocation);
    final JButton Browse = new JButton();
    final JLabel filelocation = new JLabel();
    final JLabel filename = new JLabel();
    Browse.setText("Browse");
    Browse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            //Create a file chooser
            JFileChooser fc = new JFileChooser();
            fc.showOpenDialog(screen2);
            folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
            filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
            filename.setText(fc.getSelectedFile().getName());
        }
    });   
    screen2.add(filelocation);
    screen2.add(filename);
    screen3.add(filelocation);
    filelocation.setVisible(false);
    filename.setVisible(false);
    screen2.add(Browse);
    final JButton BackScreen2 = new JButton();
    BackScreen2.setText("Back");
    BackScreen2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            if(Acceptance.isSelected())
                cl.previous(cards);
        }
    });    
    screen2.add(BackScreen2);     
    final JButton NextScreen2 = new JButton();
    NextScreen2.setText("Next");
    NextScreen2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            //Checking Code
            String correctname = "Future_Retro_Gaming_Launcher.jar";
    if (filename.getText().equals(correctname))
    {
        cl.next(cards);
    }
    else
    {
        JFrame popup = new JFrame();
        popup.setBounds(0, 0, 380, 100);
        Label error = new Label();
        error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
        popup.add(error);
        popup.show();
    }
        }
    });      
    screen2.add(NextScreen2);        
    JButton CancelScreen2 = new JButton();
    CancelScreen2.setText("Cancel");
    CancelScreen2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            System.exit(0);
        }
    });      
    screen2.add(CancelScreen2);
    cards.add(screen2);
    //Screen3
    JTextPane TextPaneScreen3 = new JTextPane();
    TextPaneScreen3.setEditable(false);
    TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
    TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
    TextPaneScreen3.setSize(358, 48);
    TextPaneScreen3.setLocation(0, 0);
    TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    TextPaneScreen3.setMargin(new Insets(4,4,4,4));
    screen3.add(TextPaneScreen3);
    final JButton BackScreen3 = new JButton();
    BackScreen3.setText("Back");
    BackScreen3.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            if(Acceptance.isSelected())
                cl.previous(cards);
        }
    });    
    screen3.add(BackScreen2);     
    final JButton NextScreen3 = new JButton();
    NextScreen3.setText("Next");
    NextScreen3.addActionListener(new ActionListener() {
        @Override
        @SuppressWarnings({"null", "ConstantConditions"})
        public void actionPerformed(ActionEvent ae) {
            //ProgressBar/Install
            System.out.println("FILELOCATION:\n----------");
            System.out.println(filelocation.getText());
            String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
            String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
            System.out.println("LOCALFILE:\n-------");
            System.out.println(LOCAL_FILE);


            RandomAccessFile randomAccessFile = null;
    ISevenZipInArchive inArchive = null;
    try {
        randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
        inArchive = SevenZip.openInArchive(null, // autodetect archive type
                new RandomAccessFileInStream(randomAccessFile));

        // Getting simple interface of the archive inArchive
        ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

        System.out.println("   Hash   |    Size    | Filename");
        System.out.println("----------+------------+---------");

        for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
            final int[] hash = new int[] { 0 };
            if (!item.isFolder()) {
                ExtractOperationResult result;

                final long[] sizeArray = new long[1];
                result = item.extractSlow(new ISequentialOutStream() {
                    public int write(byte[] data) throws SevenZipException {
                        hash[0] ^= Arrays.hashCode(data); // Consume data
                        sizeArray[0] += data.length;
                        return data.length; // Return amount of consumed data
                    }
                });
                if (result == ExtractOperationResult.OK) {
                    System.out.println(String.format("%9X | %10s | %s", // 
                            hash[0], sizeArray[0], item.getPath()));
                } else {
                    System.err.println("Error extracting item: " + result);
                }
            }
        }
    } catch (Exception e) {
        System.err.println("Error occurs: " + e);
        System.exit(1);
    } finally {
        if (inArchive != null) {
            try {
                inArchive.close();
            } catch (SevenZipException e) {
                System.err.println("Error closing archive: " + e);
            }
        }
        if (randomAccessFile != null) {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                System.err.println("Error closing file: " + e);
            }
        }
    }
}

    });        
    screen3.add(NextScreen3);        
    JButton CancelScreen3 = new JButton();
    CancelScreen3.setText("Cancel");
    CancelScreen3.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            System.exit(0);
        }
    });      
    screen3.add(CancelScreen3);

    System.out.println("Done");
    JProgressBar progress = new JProgressBar();
    progress.setIndeterminate(true);
    screen3.add(progress);
    cards.add(screen3);
    mainframe.add(cards);
    mainframe.setVisible(true);
}
}

class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
    try {
            URL website = new URL(URL_LOCATION);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            System.out.println("--------\nDone Downloading\n---------");
            } catch (Exception e) {
                System.err.println(e);
            }
    return 42;
}

protected void done()
{
    try
    {
        System.out.println("done");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

【问题讨论】:

  • 您还没有告诉我们哪些变量给您带来了麻烦或您可能会看到哪些错误消息。
  • 我对其进行了编辑以包含该信息。
  • 见编辑回答。但同样,如果这段代码对你很重要,那么请考虑重写它。
  • 是的,代码很重要。感谢您的回复。

标签: java swing variables global swingworker


【解决方案1】:

您的程序主要是一个巨大的静态 main 方法。在第一次创建干净的 OOP 代码之前,您有点像是在尝试使用 SwingWorker 进行高级编程。换句话说——重新开始,做正确的事。然后类之间的联系会更加自然,并且更加更容易让事情正常工作。 main 方法应该只关心启动 Swing 事件线程、在该线程中创建 GUI 对象并显示它。其他一切都应该在创建对象的类中。

此外,在更实际的层面上,您还没有告诉我们哪些变量给您带来了麻烦,或者您可能会看到哪些错误。另外,您要在哪里创建和执行 SwingWorker?


编辑

一个可能会有所帮助的提示:为您的 SwingWorker 类提供一个构造函数,并通过构造函数参数将重要参数传递给您的 SwingWorker 对象。然后使用这些参数初始化将在 SwingWorker 的 doInBackground 方法中使用的类字段。

例如,

class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;

public DownLoadWorker(String urlLocation, String localFile) {
  this.urlLocation = urlLocation;
  this.localFile = localFile;
}


protected Integer doInBackground() throws Exception
{
    try {
            URL website = new URL(urlLocation);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            System.out.println("--------\nDone Downloading\n---------");
            } catch (Exception e) {
                System.err.println(e);
            }
    return 42;
}

protected void done()
{
    try
    {
        System.out.println("done");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

【讨论】:

  • 好的,感谢您的回复,但是我的代码看起来与我从 Oracle 看到的 OOP 非常相似,我不明白。你建议我怎么做?
  • @user2495419:抱歉,您的代码与 OOP 相差甚远。很抱歉直言不讳,但这是非常难看的代码。同样,如上所述,您的静态 main 方法应该非常短。您的代码应该集中于从 创建 objects。另外,请参阅上面对我的答案的编辑。
  • 好的,你能解释一下我将如何访问 DownloadWorker 函数吗?
  • @user2495419:请澄清你所说的“访问”这个类是什么意思。 Access 不是标准的 Java 编程术语,它可能意味着很多东西。如果您能更全面地解释您遇到的问题,我们可能会提供更好的帮助。
  • 在您的代码中,您有一个函数 DownloadWorker,它根据传递给它的参数分配变量。我将如何从主要访问该功能?我会使用 DownloadWorker.DownloadWorker(arg1,arg2) 吗?
猜你喜欢
  • 1970-01-01
  • 2021-09-22
  • 2018-01-10
  • 2020-12-13
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 2016-07-20
相关资源
最近更新 更多