Java组件隐藏在JPanel中

时间:2014-10-03 16:33:18

标签: java swing layout layout-manager

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

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;
    }

}

1 个答案:

答案 0 :(得分:3)

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

相反,您可以使用Wrap Layout

您需要改变的是:

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