gpt4 book ai didi

java - GUI、BoxLayout 添加面板

转载 作者:行者123 更新时间:2023-11-30 03:49:16 24 4
gpt4 key购买 nike

总体研究 BoxLayout 和 GUI。我想在框架上放置一个面板。稍后我将添加一个相同的面板并测试 BoxLaoyout。但我不明白为什么这段代码生成的不是大小为 200x400 的面板,而是生成框架左侧中间的一个红点(坐标约为 (300,0))。

public class View extends JFrame {
public View(){
this.setPreferredSize(new Dimension(600, 600));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.pack();

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.RED, Color.BLACK);

JPanel p1 = new JPanel();
p1.setSize(200, 400);
p1.setBorder(border);
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));


panel.add(p1);

this.add(panel);
this.setVisible(true);
}

}

最佳答案

布局管理器 (BoxLayout) 使用它所管理的容器组件的首选大小。默认情况下,空 JPanel 的首选尺寸是 0x0,添加边框后会产生接近 2x2 的首选尺寸

使用布局管理器时,调用 setSize 是没有意义的,因为布局管理器将覆盖您在容器重新验证时指定的任何内容

已更新

看起来两个 BoxLayout 的组合似乎对你不利。如果我从 p1 中删除第二个 BoxLayout,它似乎可以正常工作。

此外,BoxLayout 似乎想要使用组件的最大尺寸...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class View extends JFrame {

public View() {
this.setPreferredSize(new Dimension(600, 600));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.pack();

JPanel panel = new JPanel();
panel.setBorder(new LineBorder(Color.BLUE));
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.RED, Color.BLACK);

JPanel p1 = new JPanel() {
public Dimension getMaximumSize() {
return new Dimension(200, 400);
}
};
p1.setBorder(border);
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));

panel.add(p1);

this.add(panel);
this.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new View();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

关于java - GUI、BoxLayout 添加面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838931/

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