gpt4 book ai didi

java - FlowLayout 还是 BoxLayout?在JAVA中

转载 作者:行者123 更新时间:2023-12-01 11:44:23 26 4
gpt4 key购买 nike

我尝试这样做:

Mokump

但是如果我使用GridLayout,高度会很小

PanelPost.setLayout(new GridLayout(20, 1, 0, 12));
for(int y=0;y<15;y++){
JPanel p=new JPanel();
p.setBackground(Color.RED);
p.setLayout(null);
p.setSize(PanelPost.getWidth(),150);
PanelPost.add(p);

}

GridLayout如果我使用 FlowLayout,只显示一些点使用 BoxLayout

setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

面板位于中心,不考虑宽度和高度如果我使用 setLayout(null) 则滚动不起作用做这个的最好方式是什么? :C

最佳答案

你的问题从这里开始 -> p.setLayout(null);。 GridLayout将使用组件的preferredSize来确定它想要使用的单元格大小。该值由面板的布局管理器确定...您现在已放弃...

避免使用 null 布局,像素完美布局是现代 UI 设计中的一种幻觉。影响组件个体尺寸的因素太多,您无法控制其中任何一个。 Swing 的设计初衷是与布局管理器一起工作,放弃它们将导致无穷无尽的问题,您将花费越来越多的时间来尝试纠正

Boo

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(new ListOfStuffPane()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class ListOfStuffPane extends JPanel implements Scrollable {

public ListOfStuffPane() {
setLayout(new GridLayout(20, 1, 0, 12));
for (int y = 0; y < 15; y++) {
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
p.setBackground(Color.RED);
p.add(new JLabel("Boo"));
add(p);
}
}

@Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(100, 200);
}

@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 128;
}

@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 128;
}

@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}

@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}


}

}

参见Laying Out Components Within a Container了解更多详情

关于java - FlowLayout 还是 BoxLayout?在JAVA中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29272352/

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