gpt4 book ai didi

Java 组件隐藏在 JPanel 中

转载 作者:行者123 更新时间:2023-12-01 22:40:49 24 4
gpt4 key购买 nike

我有两个 JPanel,每个中都有一堆 JButton。包含另外两个的 JPanel 有一个 BoxLayout,另外两个 JPanelFlowLayout。问题是,当调整窗口大小以使按钮换行时,第一个和第二个面板中的按钮 (p0,p2) 被其对应面板的边缘覆盖面板。有什么想法吗?

enter image description here

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.border.TitledBorder;

public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p0 = new JPanel();
p0.setLayout(new FlowLayout());
p0.setBorder(new TitledBorder("p0"));
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.setBorder(new TitledBorder("p1"));
CustomPanel panel = new CustomPanel();
JScrollPane sp = new JScrollPane(panel);
panel.add(p0);
panel.add(p1);
frame.add(sp);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
frame.setVisible(true);
}

}

class CustomPanel extends JPanel implements Scrollable {

@Override
public Dimension getPreferredScrollableViewportSize() {
return null;
}

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

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

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

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

}

最佳答案

当组件换行时,FlowLayout 不会重新计算首选大小。

您可以使用 Wrap Layout .

您需要更改的是:

//p0.setLayout(new FlowLayout());
p0.setLayout(new WrapLayout());

关于Java 组件隐藏在 JPanel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26183024/

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