【问题标题】:ChildPanel in ParentPanel resizes its content automaticallyParentPanel 中的 ChildPanel 自动调整其内容的大小
【发布时间】:2014-01-22 12:51:38
【问题描述】:

我目前的项目涉及将多个 JPanel 合二为一。我面临的问题是: ChildPanels 的内容会自动调整大小,而我并不想要这个。 我不使用布局管理器,我只是更喜欢自己调整所有内容的大小。

有什么办法可以防止自动调整大小?

一些示例代码:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class Test {

public static void main(String[] args) {

    JFrame f = new JFrame("TestFrame");
    f.setVisible(false);
    f.setLayout(null);
    f.setLocation(100, 100);
    f.setSize(350, 350);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ChildPanel cp1 = new ChildPanel(Color.red, 20, 20);
    ChildPanel cp2 = new ChildPanel(Color.blue, 120, 120);
    ParentPanel pp = new ParentPanel();
    pp.add(cp1);
    pp.add(cp2);
    f.getContentPane().add(pp);
    f.setVisible(true);

}

public static class ChildPanel extends JPanel {

    private Color col;

    public ChildPanel(Color col, int x, int y) {
        super();
        this.col = col;
        setSize(50, 50);
        setLocation(x, y);
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(col);
        g.fillRect(0, 0, 50, 50);
    }

}

public static class ParentPanel extends JPanel {

    public ParentPanel() {
        super();
        setSize(200, 200);
        setLocation(50, 50);
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.black);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, 0, w, h);
    }
}


}

【问题讨论】:

  • 布局管理器的存在是有原因的,如果你“更喜欢”手动做事,那么你将不得不一直解决这样的问题——更不用说如果你的代码最终会发生什么在一些不幸的 Mac 或 Linux PC 上。
  • 我的代码不是为在 Linux 或 Mac 上工作而设计的,因为我在我的项目中也使用了 JNI。

标签: java swing resize jpanel


【解决方案1】:

我不使用布局管理器

嗯,事实上你是。父面板没有设置布局管理器,所以默认使用 FlowLayout。为了防止这种情况发生,您可以将上面的代码更改如下:

public ParentPanel() {
    super(null);
    setSize(200, 200);
    setLocation(50, 50);
}

不建议在没有布局管理器的情况下工作,但如果需要,您应该将每个面板的布局管理器显式设置为 null。可以通过构造函数调用或setLayout(null); 调用来实现。

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多