0

So I've been trying to create this simple UI for a dentist and as I added the top menu under the header, I noticed that the "setPreferredSize" was not working as expected. Basically I want the menu to expand horizontally, so I'm using the GridBagLayout for that. I'm also setting the size of the JPanel containing the buttons to the full width size of my contentPane.

The weird thing is, if I resize the window (JFrame) and make it horizontally bigger then the JPanel is also resized to the preferred size.

JFrame when created:

Top menu's size is not correct (black panel)

This is the JFrame when I manually resize once its created (horizontally bigger by dragging the sides):

Top menu's size gets corrected (black JPanel)

As you can see once I make the window bigger the JPanel's size gets corrected. Also, I made sure that the window has enough space for the top menu (even made is like 50px larger than the top menu) but it still gets painted as in the first image when set to visivble.

The code for the main window is:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;

/**
 * Created by Matheus on 27/10/2016.
 */
public class WindowTest extends JFrame {

    private JPanel contentPane;
    private JPanel topMenu;
    private JPanel header;
    private JPanel dummy;
    private JButton home, appointments, healthCare,
                    patients, contact;


    public WindowTest(final int w,final int h) {
        super();

        // Colours we'll need to paint the UI (RGB format)
        final Color lightBlue = new Color(200, 200, 255);
        final Color bgBlue = new Color(112, 205, 255);
        final Color grey = new Color(128, 128, 128, 40);
        final Color white = new Color(255,255,255);
        final Color transWhite = new Color(255,255,255, 100);

        // Gradient drawing in this area
        JPanel contentPane = new JPanel(new GridBagLayout()) {
            public void paintComponent(Graphics g) {

                super.paintComponent(g);
                Graphics2D gb = (Graphics2D) g;
                gb.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                GradientPaint gp = new GradientPaint(0, 100, bgBlue, 0, h, white);
                gb.setPaint(gp);
                gb.fillRect(0, 0, w, h);

            }
        };
        contentPane.setPreferredSize(new Dimension(w, h));

        // Grid bag contraints here - Initial settings
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;




        // Create the header stuff here.
        gbc.gridy = 0;
        gbc.gridx = 0;
        gbc.weighty = 0;
        gbc.weightx = 0;
        try{
            File imgFile = new File(getClass().getResource("header.jpg").toURI());
            Image headerImg = ImageIO.read(imgFile);
            header = new ImagePanel(headerImg);

            contentPane.add(header, gbc);
        }
        catch (Exception e){
            System.out.println("Failed to load image");
        }




        // Top menu stuff here
        topMenu = new JPanel(new FlowLayout());
        topMenu.setBackground(new Color(0,0,0));
        topMenu.setPreferredSize(new Dimension(w, 60));
        System.out.println(topMenu.getSize());

        // Creating menu items
        home = new MenuButton(300, 75, "Home", transWhite);
        appointments = new MenuButton(300, 75, "Appointments", transWhite);
        patients = new MenuButton(300, 75, "Patients", transWhite);
        healthCare = new MenuButton(300, 75, "Health Care", transWhite);
        contact = new MenuButton(300, 75, "Contact", transWhite);

        home = new JButton("Home");
        appointments = new JButton("Appointments");
        patients = new JButton("Patients");
        healthCare = new JButton("Health Care Plan");
        contact = new JButton("Contact");

        topMenu.add(home);
        topMenu.add(appointments);
        topMenu.add(patients);
        topMenu.add(healthCare);
        topMenu.add(contact);
        topMenu.revalidate();

        gbc.gridy = 1;
        gbc.weightx = 1;
        gbc.weighty = 0;
        contentPane.add(topMenu, gbc);


        // Dummy here for the rest of the screen
        JPanel dummy = new JPanel();
        gbc.gridy = 1;
        gbc.weighty = 1;
        gbc.weightx = 1;
        contentPane.add(dummy, gbc);


        // Main window settings
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(contentPane);
        this.pack();
        this.revalidate();
        this.setVisible(true);
    }
}

I also tried to use different layout managers but they give the same result. Can someone help me?

Mat Gomes
  • 435
  • 1
  • 8
  • 22
  • 2
    Why don't you let the layout manager decide the size for you? That's the recommended way. – RealSkeptic Nov 07 '16 at 11:16
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Nov 07 '16 at 11:22
  • @RealSkeptic I tried that before. Removed all preferredSizes and the JPanel doesnt expand horizontally still. – Mat Gomes Nov 07 '16 at 11:29

1 Answers1

2

The easiest way to force components to fill all space is to use BorderLayout. In your case, it should be used twice.

// Initialize topMenu as before

// Create a panel for image and buttons
JPanel head = new JPanel(new BorderLayout());
// Image will be centered and its height will be preserved
head.add(new JLabel(new ImageIcon(getClass().getResource("header.jpg"))), BorderLayout.PAGE_START);
// Buttons also will be centered and their height will be preserved
head.add(topMenu, BorderLayout.PAGE_END);

// Gradient drawing in this area
JPanel contentPane = new JPanel(new BorderLayout()) {
    // paintComponent ...
};

// The height of the head will be preserver,
// but the width will be equal to the window width
contentPane.add(head, BorderLayout.PAGE_START);

// Main component
// Just for the example
final JButton main = new JButton("Test");
main.setOpaque(false);
main.setBackground(Color.MAGENTA);

// Main component will be stretched both vertically and horizontally
contentPane.add(main, BorderLayout.CENTER);
kgeorgiy
  • 1,477
  • 7
  • 9