gpt4 book ai didi

JavaGUI : Box layout with width fit to container?

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:34 26 4
gpt4 key购买 nike

我正在为自定义源服务器浏览器制作一个 GUI,并改进过滤功能。

这就是我所拥有的so far .

但是,当我 resize ...

当我调整窗口大小时,我希望 L4D2“过滤器面板”调整大小到容器的当前最大宽度。我还希望能够在列中添加更多此类面板(例如框布局提供的面板)。

Boxlayout 使面板出现在列中,但它对它们的宽度没有任何作用。我想我可能需要重写过滤器面板的首选大小方法,以便它们可以检索父容器的大小,但我不确定如何执行此操作。

我应该如何解决这个问题?

编辑:这是一个描述问题的示例程序。

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

public class guiExampleProblem {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final MyWindows wnd = new MyWindows("guiExampleProblem");
wnd.setVisible(true);
}
});
}
}

class MyWindows extends JFrame {
public MyWindows(String text) {
super(text);

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel containerPanel1 = new JPanel();
JPanel containerPanel2 = new JPanel();
JPanel containerPanel3 = new JPanel();
containerPanel1.setBackground(Color.BLACK);
containerPanel2.setBackground(Color.RED);
containerPanel3.setBackground(Color.GREEN);

mainPanel.add(containerPanel1);
mainPanel.add(containerPanel2);
mainPanel.add(containerPanel3);

this.add(mainPanel);
pack();
}
}

调整窗口大小时,我希望面板仅沿 x 轴扩展,并在 y 轴上保持恒定高度,但在示例中,面板在 x y 轴上扩展。

最佳答案

我设法通过重写“过滤器面板”getPreferedSize 方法来获得所需的功能,以便它们检索父容器宽度并使用它。以下是示例形式的代码:

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

public class guiExampleProblem {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final MyWindows wnd = new MyWindows("guiExampleProblem");
wnd.setVisible(true);
}
});
}
}

class MyWindows extends JFrame {
public MyWindows(String text) {
super(text);

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());


JPanel containerPanel1 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(this.getParent().getWidth(),60);
}
};
JPanel containerPanel2 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(this.getParent().getWidth(),60);
}
};
JPanel containerPanel3 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(this.getParent().getWidth(),60);
}
};
containerPanel1.setBackground(Color.BLACK);
containerPanel2.setBackground(Color.RED);
containerPanel3.setBackground(Color.GREEN);

mainPanel.add(containerPanel1);
mainPanel.add(containerPanel2);
mainPanel.add(containerPanel3);


this.add(mainPanel);
pack();
}
}

关于JavaGUI : Box layout with width fit to container?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21282795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com