How do I make this FlowLayout wrap within its JSplitPane?

老子叫甜甜 提交于 2019-12-01 12:16:15

问题


I wrote this code sample to illustrate a problem I'm having with my program.

I expect to be able to slide the JSplitPane's slider bar to the left, beyond the edge of the buttons, compressing that JPanel, and have the FlowLayout wrap the buttons to a second row.

Instead, the JSplitPane does not allow me to move the slider past the rightmost button on the screen, and if I resize the entire JFrame to force the compression, the buttons (I presume) are just running off the righthand side of the JPanel, underneath the slider bar (I guess, because I obviously cannot see them).

What am I doing wrong?

import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Driver implements Runnable {
    public static void main(String[] args) {
        (new Driver()).run();
    }
    public void run() {
        try {
            go();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
    private void go() throws Exception {
        JFrame jframe = new JFrame("FlowLayoutTest");
        JPanel left = new JPanel();
        left.setBackground(Color.RED);
        left.setLayout(new BorderLayout());
        JPanel right = new JPanel();
        right.setBackground(Color.BLUE);
        right.setLayout(new BorderLayout());
        JSplitPane topmost =
            new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
        jframe.setContentPane(topmost);
        JPanel bottomleft = new JPanel();
        bottomleft.setBackground(Color.GREEN);
        bottomleft.setLayout(new FlowLayout());
        left.add(bottomleft, BorderLayout.PAGE_END);
        for (int i = 0; i < 10; i++) {
            bottomleft.add(new JButton("" + i));
        }
        jframe.pack();
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

回答1:


Is there another layout manager besides FlowLayout that will do what I'm looking for?

Wrap Layout should work.




回答2:


If you add this

bottomleft.setMinimumSize(new Dimension(0, 0));

before the pack() then it'll reflow. BUT, it won't re-pack the border layout, so instead of two lines you'll get one with the rest cut off. So after a resize you'll have to repack the border layout. If you omit the border layout then it'll reflow like you want.

That said, you should avoid FlowLayout like the plague. Most of the layouts that come with Swing are poor, but FlowLayout is one of the worst offenders.



来源:https://stackoverflow.com/questions/5709690/how-do-i-make-this-flowlayout-wrap-within-its-jsplitpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!