有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

隐藏在JPanel中的swing Java组件

我有两个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) 个答案

  1. # 1 楼答案

    组件包裹时,FlowLayout不会重新计算首选尺寸

    相反,您可以使用Wrap Layout

    你需要改变的是:

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