JPanel size setting

I have a class that extends JPanel called Row. I have a Row group added to JLabel , the code is as follows:

JFrame f=new JFrame();

JPanel rowPanel = new JPanel();
//southReviewPanel.setPreferredSize(new Dimension(400,130));
rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS));
rowPanel.add(test1);
rowPanel.add(test1);
rowPanel.add(test2);
rowPanel.add(test3);
rowPanel.add(test4);
rowPanel.setPreferredSize(new Dimension(600, 400));
rowPanel.setMaximumSize(rowPanel.getPreferredSize()); 
rowPanel.setMinimumSize(rowPanel.getPreferredSize());

f.setSize(new Dimension(300,600));

JScrollPane sp = new JScrollPane(rowPanel);
sp.setSize(new Dimension(300,600));
f.add(sp);

f.setVisible(true);

where test1 ... etc. is a string. However, when I resize the window, the Row layout somehow becomes messy (it also changes) ... how can I prevent this?

+3
source share
2 answers

Read the Swing tutorial on Using Layout Managers . Each layout manager has its own rules about what happens when the size of the container changes. Experiment and play.

BoxLayout , , :

childPanel.setMaximumSize( childPanel.getPreferredSize() );

, SSCCE, .

+3

http://download.oracle.com/javase/tutorial/uiswing/examples/layout/BoxLayoutDemoProject/src/layout/BoxLayoutDemo.java , , JPanels:

public class BoxLayoutDemo {
    public static void addComponentsToPane(Container pane) {
        JPanel rowPanel = new JPanel();
        pane.add(rowPanel);

        rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS));
        rowPanel.add(addAButton("Button 1"));
        rowPanel.add(addAButton("Button 2"));
        rowPanel.add(addAButton("Button 3"));
        rowPanel.add(addAButton("Button 4"));
        rowPanel.add(addAButton("5"));
        rowPanel.setPreferredSize(new Dimension(600, 400));
        rowPanel.setMaximumSize(rowPanel.getPreferredSize()); 
        rowPanel.setMinimumSize(rowPanel.getPreferredSize());
    }

    private static JButton addAButton(String text) {
        JButton button = new JButton(text);
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        return button;
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("BoxLayoutDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane.
        addComponentsToPane(frame.getContentPane());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

: alt text

, . JFrame, . , ?

+1

Source: https://habr.com/ru/post/1775778/


All Articles