setPreferredSize没有按预期工作,JPanel没有“打包”

时间:2016-11-07 11:12:32

标签: java swing

所以我一直在尝试为牙医创建这个简单的用户界面,当我在标题下面添加顶层菜单时,我注意到“setPreferredSize”没有按预期工作。基本上我希望菜单水平扩展,所以我正在使用GridBagLayout。我还将包含按钮的JPanel的大小设置为contentPane的全宽大小。

奇怪的是,如果我调整窗口大小(JFrame)并使其水平放大,那么JPanel也会调整为首选大小。

创建时的JFrame:

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

这是我创建时手动调整大小的JFrame(通过拖动两侧水平放大):

Top menu's size gets corrected (black JPanel)

正如你所看到的,一旦我把窗户做得更大,JPanel的尺寸就会得到纠正。此外,我确保窗口有足够的空间用于顶部菜单(甚至可以制作比顶部菜单大50px)但是当设置为可见时,它仍然会像第一个图像一样被绘制。

主窗口的代码是:

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);
    }
}

我也尝试使用不同的布局管理器,但它们给出了相同的结果。有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

强制组件填充所有空间的最简单方法是使用BorderLayout。在你的情况下,它应该使用两次。

// 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);