java-从右到左的FlowLayout

时间:2015-03-11 20:44:04

标签: java swing flowlayout

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

3 个答案:

答案 0 :(得分:6)

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

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") );

答案 1 :(得分:3)

FlowLayout只是尊重添加组件的位置(或z顺序)。您可以使用add提供的JContainer方法来指定应添加组件的位置,对于FlowLayout没有任何约束,您只需使用add(Component, int),例如......

Layout Order

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),以相反的顺序放置组件

答案 2 :(得分:2)

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);

Example