【问题标题】:Implementing JScrollPane/JTextArea in SwingWorker在 SwingWorker 中实现 JScrollPane/JTextArea
【发布时间】:2013-12-26 02:47:20
【问题描述】:

在使用 SwingWorker 时,我的 JScrollPane/JTextArea 出现了一些问题。这是我目前拥有的:

JTextArea txtDirs;
Task task;

//EDT
public void createGUI(){
    txtDirs = new JTextArea();
    txtDirs.setBounds(10, 56, 414, 125);
    txtDirs.setEditable(false);
    contentPane.add(new JScrollPane(txtDirs));

    task = new Task();
    task.execute();
}

class Task extends SwingWorker<Void, Void>{
    @Override
    public void doInBackground(){
        for(file : files){
            txtDirs.append(file.getAbsolutePath);
        }
    }

    @Override
    public void done(){
        closeWindow();
    }
}

这不是确切的代码,但它应该给你它的要点。无论如何,问题是 JScrollPane 根本没有出现,尽管 doInBackground() 方法中的代码确实运行了。我希望它与在后台任务中更新(txtDirs.append(file.getAbsolutePath()))有关。但是,我不太确定如何使它在这种情况下工作。该框架按预期显示,但它完全是空白的。 Task 类中应该有一个“进程”方法吗?那是应该放置“txtDirs.append(file.getAbsolutePath())”的地方吗?恐怕我对 SwingWorkers 的使用还比较陌生,因此我们将不胜感激。

编辑:

经过一番困惑后,我决定只发布我的完整代码。我知道它有问题,而且我可能误解了 cmets 中提到的一些内容,所以我希望发布此内容能让有人指出我犯的任何明显错误。

完整代码:

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
import javax.swing.SwingWorker;

import org.apache.commons.io.FileUtils;

@SuppressWarnings("serial")
public class BasicCopy extends JFrame {

    private JPanel contentPane;
    private JTextArea txtCopiedDirs;
    private JButton btnCancel;
    private JProgressBar progressBar;
    private JLabel lblCopying;
    private String mainDrive;
    private String backupDrive;
    private String username;
    private String backupDir;
    long totalSize = 0L;        //total size of directories/files
    long currentSize = 0L;      //current size of files counting up to ONE_PERCENT
    long currentPercent = 0L;   //current progress in %
    long ONE_PERCENT;       //totalSize / 100
    Task task;

    public BasicCopy() {
    }

    public BasicCopy(String inDrive, String outDrive, String username, long space){
        mainDrive = inDrive;
        backupDrive = outDrive;
        this.username = username;
        totalSize = space*1048576;
        ONE_PERCENT = totalSize/100;
        createGUI();
    }

    public void createGUI(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Backup Progress");
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        txtCopiedDirs = new JTextArea(10, 50);
        txtCopiedDirs.setEditable(false);
        contentPane.add(new JScrollPane(txtCopiedDirs));

        btnCancel = new JButton("Cancel");
        btnCancel.setBounds(169, 227, 89, 23);
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                closeWindow();
            }
        });
        contentPane.add(btnCancel);

        progressBar = new JProgressBar(0, 100);
        progressBar.setBounds(10, 192, 414, 24);
        progressBar.setValue(0);
        contentPane.add(progressBar);

        lblCopying = new JLabel("Now backing up your files....");
        lblCopying.setBounds(10, 11, 157, 34);
        contentPane.add(lblCopying);

        setVisible(true);
        task = new Task();
        task.execute();
    }


    /**
     * Swing Worker class
     */
    class Task extends SwingWorker<Void, String>{
        @Override
        public Void doInBackground(){
            setProgress(0);

            //Create Backup Directory
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy_HMMSS");
            String timestamp = sdf.format(date);
            backupDir = backupDrive + ":\\" + "Backup_" + timestamp;
            File backupDirectory = new File(backupDir);
            backupDirectory.mkdir();

            //Copy Files
            //Main directories
            String pics = mainDrive + ":\\Users\\" + username + "\\Pictures\\";
            String docs = mainDrive + ":\\Users\\" + username + "\\Documents\\";
            String vids = mainDrive + ":\\Users\\" + username + "\\Videos\\";
            String musc = mainDrive + ":\\Users\\" + username + "\\Music\\";
            //Backup directories
            String bkPics = backupDir + "\\Pictures\\";
            String bkDocs = backupDir + "\\Documents\\";
            String bkVids = backupDir + "\\Documents\\";
            String bkMusc = backupDir + "\\Pictures\\";

            String[] directories = {pics, docs, vids, musc};
            String[] bkDirectories = {bkPics, bkDocs, bkVids, bkMusc};

            //Loop through directories and copy files
            for (int i = 0; i < directories.length; i++){
                File dir = new File(directories[i]);
                File dest = new File(bkDirectories[i]);
                for(File file: dir.listFiles()){
                    try{
                        if(file.isFile()){
                            FileUtils.copyFileToDirectory(file, dest);
                            publish(file.getAbsolutePath() + "\n");
                        } else if (file.isDirectory()){
                            FileUtils.copyDirectoryToDirectory(file, dest);
                            publish(file.getAbsolutePath() + "\n");
                        }
                        if(getDirSize(file) >= ONE_PERCENT){
                            currentPercent = getDirSize(file)/ONE_PERCENT;
                            progressBar.setValue((int)currentPercent);
                            currentSize = 0;
                        } else {
                            currentSize = currentSize + getDirSize(file);
                            if(currentSize >= ONE_PERCENT){
                                currentPercent = currentSize/ONE_PERCENT;
                                currentPercent++;
                                progressBar.setValue((int)currentPercent);
                                currentSize = 0;
                            }
                        }
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        public void process(List<String> chunks){
            for(String path : chunks){
                txtCopiedDirs.append(path);
            }
        }

        @Override
        public void done(){
            closeWindow();
        }
    }

    public static Long getDirSize(File file) {
        long size = 0L;

        if (file.isFile() && file != null){       
            size += file.isDirectory() ? getDirSize(file) : file.length();
        } else if (file.isDirectory()){
            for (File f : file.listFiles()) {
            size += f.isDirectory() ? getDirSize(f) : file.length();
        }
        }
        return size;
    }

    /* Close current window */
    public void closeWindow() {
        WindowEvent close = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(close);
        System.exit(0);
    }
}

编辑 #2:

我对 createGUI() 方法进行了一些更改,以避免 contentPane 的布局为空:

public void createGUI(){
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Backup Progress");
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel(new BorderLayout());
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    txtCopiedDirs = new JTextArea(10, 50);
    txtCopiedDirs.setEditable(false);
    scrollPane = new JScrollPane(txtCopiedDirs);
    contentPane.add(scrollPane, BorderLayout.CENTER);

    btnCancel = new JButton("Cancel");
    btnCancel.setBounds(169, 227, 89, 23);
    btnCancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            closeWindow();
        }
    });
    contentPane.add(btnCancel);

    progressBar = new JProgressBar(0, 100);
    progressBar.setBounds(10, 192, 414, 24);
    progressBar.setValue(0);
    contentPane.add(progressBar);

    lblCopying = new JLabel("Now backing up your files....");
    lblCopying.setBounds(10, 11, 157, 34);
    contentPane.add(lblCopying);

    setVisible(true);
    task = new Task();
    task.execute();
}

【问题讨论】:

  • 让你的 SwingWorker&lt;Void,String&gt; 调用 publish(filesNameString) 并覆盖 process ,在处理过程中追加到 txtDirs

标签: java implementation jtextarea swingworker jscrollbar


【解决方案1】:
  • 不要使用setBounds,而是使用JTextArea(rows, cols)
  • 不要从 EDT 外部修改任何 UI 组件,而是使用 publish 并覆盖 process。 process 在 EDT 的内容中被调用

查看Concurrency in Swing了解更多详情

问题的可能原因包括...

  • 在框架使用 BorderLayout 时向框架添加其他组件,但不指定位置约束(BorderLayout.CENTER 除外)
  • 在添加组件之前调用可见

更新

主要问题是,contentPane 使用的是null 布局,滚动窗格的默认边界是0x0 位置,0x0 宽度和高度。

最好的选择是不使用 WinodwBuilder 并学习如何使用layout managers

更新示例

这是一个使用两个布局管理器的示例,BorderLayout 作为基本布局,GridBagLayout 为额外的组件提供一些额外的支持。

基本经验法则。如果它是一个 UI 组件,特别是如果它在屏幕上(或者您不知道它是否在屏幕上),您只能从 EDT 的上下文中更新它。

这意味着从doInBackground 中调用progressBar.setValue 违反了Swing 的单线程规则。 SwingWorker 通过 PropertyChange 支持提供进度更新

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
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.SwingWorker;
import javax.swing.border.EmptyBorder;

public class BasicCopy extends JFrame {

    private JPanel contentPane;
    private JTextArea txtCopiedDirs;
    private JButton btnCancel;
    private JProgressBar progressBar;
    private JLabel lblCopying;
    private String mainDrive;
    private String backupDrive;
    private String username;
    private String backupDir;
    long totalSize = 0L;        //total size of directories/files
    long currentSize = 0L;      //current size of files counting up to ONE_PERCENT
    long currentPercent = 0L;   //current progress in %
    long ONE_PERCENT;       //totalSize / 100
    Task task;

    public BasicCopy() {
    }

    public BasicCopy(String inDrive, String outDrive, String username, long space) {
        mainDrive = inDrive;
        backupDrive = outDrive;
        this.username = username;
        totalSize = space * 1048576;
        ONE_PERCENT = totalSize / 100;
        createGUI();
    }

    public void createGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Backup Progress");
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout());

        txtCopiedDirs = new JTextArea(10, 50);
        txtCopiedDirs.setEditable(false);
        contentPane.add(new JScrollPane(txtCopiedDirs));

        JPanel controls = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(4, 4, 4, 4);

        lblCopying = new JLabel("Now backing up your files....");
        contentPane.add(lblCopying, gbc);

        gbc.gridy++;

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        contentPane.add(progressBar, gbc);

        gbc.gridy++;

        btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                closeWindow();
            }
        });
        controls.add(btnCancel, gbc);
        contentPane.add(controls, BorderLayout.SOUTH);

        setLocationRelativeTo(null);
        pack();
        setVisible(true);
        task = new Task();
        task.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                    progressBar.setValue((int) evt.getNewValue());
                }
            }
        });
        task.execute();
    }

    /**
     * Swing Worker class
     */
    class Task extends SwingWorker<Void, String> {

        @Override
        public Void doInBackground() throws Exception {
            setProgress(0);

            //Create Backup Directory
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy_HMMSS");
            String timestamp = sdf.format(date);
            backupDir = backupDrive + ":\\" + "Backup_" + timestamp;
            File backupDirectory = new File(backupDir);
            backupDirectory.mkdir();

            //Copy Files
            //Main directories
            String pics = mainDrive + ":\\Users\\" + username + "\\Pictures\\";
            String docs = mainDrive + ":\\Users\\" + username + "\\Documents\\";
            String vids = mainDrive + ":\\Users\\" + username + "\\Videos\\";
            String musc = mainDrive + ":\\Users\\" + username + "\\Music\\";
            //Backup directories
            String bkPics = backupDir + "\\Pictures\\";
            String bkDocs = backupDir + "\\Documents\\";
            String bkVids = backupDir + "\\Documents\\";
            String bkMusc = backupDir + "\\Pictures\\";

            String[] directories = {pics, docs, vids, musc};
            String[] bkDirectories = {bkPics, bkDocs, bkVids, bkMusc};

            //Loop through directories and copy files
            for (int i = 0; i < directories.length; i++) {
                File dir = new File(directories[i]);
                File dest = new File(bkDirectories[i]);
                for (File file : dir.listFiles()) {
                    try{
                    if (file.isFile()) {
                        FileUtils.copyFileToDirectory(file, dest);
                        publish(file.getAbsolutePath() + "\n");
                    } else if (file.isDirectory()) {
                        FileUtils.copyDirectoryToDirectory(file, dest);
                        Thread.sleep(1000);
                        publish(file.getAbsolutePath() + "\n");
                    }
                    if (getDirSize(file) >= ONE_PERCENT) {
                        currentPercent = getDirSize(file) / ONE_PERCENT;
                        setProgress((int) currentPercent);
                        currentSize = 0;
                    } else {
                        currentSize = currentSize + getDirSize(file);
                        if (currentSize >= ONE_PERCENT) {
                            currentPercent = currentSize / ONE_PERCENT;
                            currentPercent++;
                            setProgress((int) currentPercent);
                            currentSize = 0;
                        }
                    }
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        public void process(List<String> chunks) {
            for (String path : chunks) {
                txtCopiedDirs.append(path);
            }
        }

        @Override
        public void done() {
            closeWindow();
        }
    }

    public static Long getDirSize(File file) {
        long size = 0L;

        if (file.isFile() && file != null) {
            size += file.isDirectory() ? getDirSize(file) : file.length();
        } else if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                size += f.isDirectory() ? getDirSize(f) : file.length();
            }
        }
        return size;
    }

    /* Close current window */
    public void closeWindow() {
        WindowEvent close = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(close);
        System.exit(0);
    }
}

【讨论】:

  • 谢谢,我想我们以前讨论过这个问题。也许不是你,但无论如何,“setBounds”是自动生成的,一旦我让代码工作,我会回去更改它。很快就会看链接
  • 这可能意味着您的框架使用的是空布局,这可以解释为什么您什么都看不到
  • 当我不使用 JScrollPane 时,框架工作正常并且组件出现。文本附加得很好,但在边缘被切断了。这就是我尝试使用 JScrollPane 来显示文本的原因,以便用户可以根据需要(通过滚动)查看所有文本
  • 正如我所怀疑的那样。 contentPane 使用 null 布局,但滚动窗格的位置和大小未定义(或 0)。这里最好的选择是不要依赖 WindowBuilder 并学习如何使用布局管理器
  • 再一次,我根本不依赖 WindowBuilder。自从我第一次设置窗口的基本布局以来,我还没有使用它。我只用它来定位文本区域、进度条和按钮。从那以后(几天前),我只在编辑代码本身。至于 contentPane/scroll 窗格,它应该如何创建?我知道我做错了很多事情,这就是我在这里的原因。
【解决方案2】:

试试这个,我不知道append是否是线程安全的,尝试在你知道EDT调用的地方调用发布。

class Task extends SwingWorker<Void, String>{
    @Override
    public void doInBackground(){
        for(file : files){
            publish(file.getAbsolutePath); //or you can store them in an array and call it later
        }
    }

    @Override
    public void process(List<String> chunks){
           for(String filePath : chunks){
             txtDirs.append(filePath);
           }
    }

    @Override
    public void done(){
        closeWindow();
    }
}

如果这没有帮助,请考虑发布SSCCE

【讨论】:

  • 很好奇,JScrollPane 呢?我应该保持原样吗?
  • @derstrom8 先试试这个,在另一个不是EDT的线程中更新组件可能会出问题,调用发布就知道会调用进程,进程在EDT中执行。如果 append 它是线程安全的,我在 java7 文档中找不到
  • 我想我可能误解了这篇文章。我可能应该只添加我的真实代码。我只是犹豫了一下,因为它有点长。我会将其添加到我的原始帖子的编辑中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
相关资源
最近更新 更多