1

This is a part of my java code, in this code I want that the progress bar should always remains under the label (at the back of label), progress bar is under the label when I start the program, but progress bar comes over/upon the label when I click the button and start progress. So please tell how can I keep the label always over the progress bar???

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;


public class Test {

    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    JProgressBar bar = new JProgressBar(JProgressBar.VERTICAL,0,100);
    JButton button = new JButton();

    public static void main(String arg[]) {
        new Test();
    }

    public Test() {
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setUndecorated(true);
        frame.setLayout(null);
        label.setOpaque(true);
        label.setBackground(Color.BLACK);
        label.setBounds(100,100,100,50);
        bar.setBounds(140,25,20,200);
        button.setBounds(220,100,50,50);
        button.addActionListener(new Progress());
        frame.add(label);
        frame.add(bar);
        frame.add(button);
        frame.setVisible(true);
    }

    class Progress extends SwingWorker<Void, Void> implements ActionListener {

        public Void doInBackground() {
            for(int i=0; i<101; i++) {
                bar.setValue(i);
                try {
                    Thread.sleep(100);
                } 
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        public void actionPerformed(ActionEvent e) {
            this.execute();
        }
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 4
    Don't use null layout. Learn and use layout managers. – Hovercraft Full Of Eels Aug 21 '14 at 02:00
  • 2
    Why do you need to do it this way? Can't you use [`JProgressBar#setStringPainted`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JProgressBar.html#setStringPainted(boolean)) instead? Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Aug 21 '14 at 02:01
  • 1
    @HovercraftFullOfEels Why would people ever consider using a tool the way it was designed to be used? What a revelation... – MadProgrammer Aug 21 '14 at 02:02
  • is there no way to solve my problem keeping null layout??? – Mirza Ghalib Aug 21 '14 at 02:29
  • @MadProgrammer Blame Oracle for this. They introduce absolute positioning in their tutorials, which had me using it for a while due to simplicity. Even though they recommend using a LayoutManager, they really shouldn't have introduced it, let alone allow it – Vince Aug 21 '14 at 02:32
  • @MirzaGhalib In reality, no. If using null layout, theres nothing forcing the label to stay within the progress bar (since you aren't placing components relative to other components) . Even if you were to get it working on your computer (through percise placing of components), the results could vary on other platforms – Vince Aug 21 '14 at 02:33
  • @MirzaGhalib You could apply a layout manager to the `JProgressBar` and add the `JLabel` to it...there's some other problems, but it's doable...but I don't see why... – MadProgrammer Aug 21 '14 at 02:36
  • @MadProgrammer I posted up my answer what do you think? :) – Kick Buttowski Aug 21 '14 at 02:54
  • @MirzaGhalib I posted my answer please me lemee know how it went – Kick Buttowski Aug 21 '14 at 02:56
  • 1
    @KickButtowski I'm still trying to work out what's wrong with [`JProgressBar#setStringPainted`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JProgressBar.html#setStringPainted(boolean)) – MadProgrammer Aug 21 '14 at 02:59
  • @MadProgrammer cool so lemme later what you think about my answer thank you :) your opinion is ** Google stock market** lol – Kick Buttowski Aug 21 '14 at 03:00

2 Answers2

7

I'm not sure why you're trying to do what you are, when JProgressBar already provides the means to display a String value...

See JProgressBar#setStringPainted for more details...

Progress

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ProgressBarTest {

    public static void main(String[] args) {
        new ProgressBarTest();
    }

    public ProgressBarTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {            
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                JProgressBar pb = new JProgressBar();
                pb.setValue(0);
                pb.setStringPainted(true);
                pb.setString("Look ma, no hands");
                frame.add(pb);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                SwingWorker worker = new SwingWorker() {
                    @Override
                    protected Object doInBackground() throws Exception {
                        for (int index = 0; index < 1000; index++) {
                            int progress = (int)Math.round((index / 1000f) * 100);
                            setProgress(progress);
                            Thread.sleep(10);
                        }
                        return null;
                    }
                };

                worker.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress".equals(evt.getPropertyName())) {
                            int value = (int) evt.getNewValue();
                            System.out.println(value);
                            pb.setValue(value);
                        }
                    }
                });

                worker.execute();

            }
        });
    }

}

Updated

Now, if you "really" want to put a label on top of a progress bar, there are some tricks you can do, for example...

Progress

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ProgressBarTest {

    public static void main(String[] args) {
        new ProgressBarTest();
    }

    public ProgressBarTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JLabel label = new JLabel("I feel the need for speed");
                JProgressBar pb = new JProgressBar();

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.weightx = 1;
                gbc.fill = GridBagConstraints.BOTH;
                gbc.ipady = 20;

                frame.add(pb, gbc);

                gbc.weightx = 0;
                gbc.fill = GridBagConstraints.NONE;
                gbc.insets = new Insets(5, 0, 5, 0);
                frame.add(label, gbc);


                frame.add(pb, gbc);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                SwingWorker worker = new SwingWorker() {
                    @Override
                    protected Object doInBackground() throws Exception {
                        for (int index = 0; index < 1000; index++) {
                            int progress = (int) Math.round((index / 1000f) * 100);
                            setProgress(progress);
                            Thread.sleep(10);
                        }
                        return null;
                    }
                };

                worker.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress".equals(evt.getPropertyName())) {
                            int value = (int) evt.getNewValue();
                            System.out.println(value);
                            pb.setValue(value);
                        }
                    }
                });

                worker.execute();

            }
        });
    }

}

Basically, this places both the label and progress bar at the same location within the GridBagLayout...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I think you are looking for this http://stackoverflow.com/questions/25416336/jprogressbar-setstringpaintedtrue-is-painting-two-strings question – Kick Buttowski Aug 21 '14 at 03:16
  • the op asks how to keep JLabel over JProgressbar – Kick Buttowski Aug 21 '14 at 03:18
  • 1
    @KickButtowski I know what the OP asks for, I'm asking why when `JProgressBar` already supports it. When the OP says "over", they mean "ontop off", look at the bounds they are using, the progress bar will cover the label...;) – MadProgrammer Aug 21 '14 at 03:20
  • 1
    @KickButtowski See also [Is “Don't do it” a valid answer?](http://meta.stackexchange.com/q/8891/155831) (yes) & [What is the XY problem?](http://meta.stackexchange.com/q/66377/155831) (this so far, is an XY problem). – Andrew Thompson Aug 21 '14 at 03:27
  • @AndrewThompson sorry I didn't get ur point. it seems I got this question all wrong – Kick Buttowski Aug 21 '14 at 03:28
  • 1
    *"I feel the need for speed"* "I feel the nafety for safety" (Leela). – Andrew Thompson Aug 21 '14 at 03:29
  • @KickButtowski You read both those questions, as well as at least the accepted answers, in less than a minute? Try reading them again, more slowly. Also, be more specific about what you don't understand. I do not intend writing a novel to explain each link I offer. – Andrew Thompson Aug 21 '14 at 03:31
  • @MadProgrammer I changed my answer could you lemme know what you think? – Kick Buttowski Aug 21 '14 at 04:43
0

Based on this post and idea that @MadProgrammer gave me

"You can use:

Initialising:

progressBar.setStringPainted(true);
Updating:

progressBar.setValue(newValue);
progressBar.setString(newValue + "%");"

Source of this answer :

How to add text on jprogressbar?

My answer to this problem is

Code:

JFrame frame = new JFrame();

    JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
    JButton button = new JButton("Button");

    public static void main(String arg[]) {
        new Test();
    }

    public Test() {


        bar.setStringPainted(true);
        bar.setString("I am a JProgressBar and ready to go here");
        button.addActionListener(new Progress());

        JPanel pane = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 40;      //make this component tall
        c.weightx = 0.0;
        c.gridwidth = 2;
        c.gridx = 2;
        c.gridy = 2;

        pane.add(bar, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridx = 2;
        c.gridy = 3;
        pane.add(button, c);

        frame.add(pane);
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    class Progress extends SwingWorker<Void, Void> implements ActionListener {

        @Override
        public Void doInBackground() {
            for (int i = 0; i < 101; i++) {
                bar.setValue(i);
                bar.setString(Integer.toString(i) + "%");

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            this.execute();
        }
    }
}

Output: enter image description here enter image description here

Community
  • 1
  • 1
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58