java- FlowLayout 从右到左

java- FlowLayout from right to left

FlowLayout 在最后一个组件的右侧添加新组件。我的意思是它从左到右排列组件 (>>>>),但我需要从右到左排列 (<<<<)。可能吗?

FlowLayout 不提供此功能,仅提供各种理由选项。您能以相反的顺序添加组件吗?

JFrame frame = new JFrame();
frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
frame.add(new JButton("3"));
frame.add(new JButton("2"));
frame.add(new JButton("1"));
frame.setSize(200, 200);
frame.setVisible(true);

FlowLayout 仅遵循添加组件的位置(或 z 顺序)。您可以使用 JContainer 提供的 add 方法来指定组件应添加的位置,对于没有约束的 FlowLayout,您可以简单地使用 add(Component, int),例如...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class JavaApplication252 {

    public static void main(String[] args) {
        new JavaApplication252();
    }

    public JavaApplication252() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JPanel mainPane = new JPanel();
                JButton btn = new JButton("Add");
                btn.addActionListener(new ActionListener() {
                    int count;
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        mainPane.add(new JLabel(Integer.toString(count++)), 0);
                        mainPane.revalidate();
                        mainPane.repaint();
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(mainPane);
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

您唯一的选择是创建自己的布局管理器(可能基于 FlowLayout),它以相反的顺序布置组件

将组件添加到面板的开头:

panel.add(component, 0);

或者,设置组件方向,然后正常添加按钮:

panel.setLayout( new FlowLayout(FlowLayout.RIGHT) );
panel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

panel.add( new JButton("1") );
panel.add( new JButton("2") );
panel.add( new JButton("3") );
panel.add( new JButton("4") );