Search code examples
javaswingjtextpanejprogressbar

JProgressBar in JTextPane


I added a progress bar to my text pane but I cannot re-size the width of the progress bar added (can re-size height). could you please help me with this issue and also tell me how can I remove the progress bar once I am done with it.

JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setPreferredSize(new Dimension(50, 15));
progressBar.setMinimum(0);
progressBar.setMaximum((int) file.length());

textPane.setSelectionStart(textPane.getText().length());
textPane.setSelectionEnd(textPane.getText().length());
textPane.insertComponent(progressBar);

Solution

  • I think you are questioning about how to set your preferred width for the JProgressBar, right?

    If this is your question, you should use setMaximumSize instead of setPreferredSize:

    JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    //progressBar.setPreferredSize(new Dimension(50, 15));
    progressBar.setMaximumSize(new Dimension(50, 15)); // This line instead of above line
    progressBar.setMinimum(0);
    progressBar.setMaximum((int) file.length());
    

    [EDIT] For removing components you should assume the components in your JTextPane as some characters, and then remove them from JTextPane's Document object. I also assumed a temp JButton to raise the remove event:

    JButton b = new JButton("Remove!");
    b.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
                try {
                    textPane.getDocument().remove(0, 1);
                } catch (BadLocationException e1) {
                    e1.printStackTrace();
                }
            }
        });
    

    Good Luck.