1

I'm trying to make a JFrame with a JProgressbar and a JButton inside, for the user to be see how far the process is and able to abort the process.

The only issue I seem to encounter, the progressbar and button components to always adjust to the JFrame size, and not the size I set them to. See picture one; Picture 1

The goal is to make it look like this example; Picture 2

Does anyone have some suggestions? See my code below;

JFrame f = new JFrame("Retrieve Datalog");
JButton b = new JButton("Abort");

JProgressBar progressBar = new JProgressBar();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setIconImage(ICONBAR.getImage());
f.setResizable(false);
f.setSize(300, 100);    
f.setLocationRelativeTo(getFrame());      
b.setSize(50, 10);            

progressBar.setSize(f.getWidth() - 100, f.getHeight() - 50);    
progressBar.setValue(50);
progressBar.setStringPainted(true);

f.add(progressBar, BorderLayout.NORTH);
f.add(b, BorderLayout.CENTER);    
f.setVisible(true);

PS: I'm using NetBeans 8.1 IDE, JDK v8u91

Zwetje
  • 13
  • 2
  • Consider nulling out the frame layout. f.setLayout(null); Not the gratest solution but still should work. – DamianoPantani Aug 17 '16 at 10:32
  • The compontent are now resizable, only they seem to get stuck in the upper left corner. Tadesse posted the correct solution. – Zwetje Aug 17 '16 at 12:50

1 Answers1

0

I try some code. You can use Grid bag layout. There is the code and snapshot Snapshot

import java.awt.*;
import javax.swing.*;

/**
 * JFrame with a progress bar and button. With the size of their own.
 *
 * @author Tadesse
 */
public class Test extends JFrame {

    JButton button = new JButton("Cancel");
    JProgressBar progressBar = new JProgressBar();

    public Test() {
        GridBagConstraints g = new GridBagConstraints();
        setLayout(new GridBagLayout());
        set(g, 0, 0, GridBagConstraints.CENTER);
        add(progressBar, g);
        set(g, 0, 1, GridBagConstraints.CENTER);
        add(button, g);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200, 100);
        setVisible(true);
    }

    public void set(GridBagConstraints c, int x, int y, int anchor) {
        c.gridx = x;
        c.gridy = y;
        c.anchor = anchor;
    }

    public static void main(String[] args) {
        new Test();
    }
}
Tadesse
  • 76
  • 2
  • 4
  • Thanks, this works perfect! Dont forget to make use of c.ipady and c.ipadx if you want to (re)size any of the components. – Zwetje Aug 17 '16 at 12:49