how to place last component of a jPanel on the right edge, even if the panel has a flowLayout Left

本秂侑毒 提交于 2019-12-13 02:57:18

问题


I have in my code :

a jPanel with LEFT FlowLayout. It contains various components. see img:

what i'm trying to implement: I'm trying to stick last component on the right edge of its panel container. See img:

i tried:

to add a Box.createHorizontalGlue before my last component, but it doesn't work as expected.

The Code:

Code has been created on purpose for the question and mirrors the original code logic:

public class TheMotherPuckerGlue {
    public static void main(String [] a) {
        final JFrame frame = new JFrame();
        frame.setSize(500, 90);
        frame.setTitle("myCode");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JPanel motherPucker = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        JPanel panel3 = new JPanel();

        panel1.setBackground(Color.green);
        panel2.setBackground(Color.yellow);
        panel3.setBackground(Color.red);

        panel1.setPreferredSize(new Dimension(100,40));
        panel2.setPreferredSize(new Dimension(100,40));
        panel3.setPreferredSize(new Dimension(100,40));

        motherPucker.add(panel1);
        motherPucker.add(panel2);
//        motherPucker.add(Box.createHorizontalGlue());
        motherPucker.add(panel3);
        motherPucker.setBackground(Color.white);

        frame.add(motherPucker,BorderLayout.CENTER);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
   }
}

Thank for any suggestion you'll leave! :D

来源:https://stackoverflow.com/questions/33255891/how-to-place-last-component-of-a-jpanel-on-the-right-edge-even-if-the-panel-has

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