如何从右到左添加按钮和其他组件到JPanel
?我曾使用BorderLayout
经理来做到这一点,但它不起作用,它们被插入到屏幕中间!
我该怎么做?
答案 0 :(得分:2)
以正确的对齐方式添加其他JPanel
和FlowLayout
。
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT), 0, 5); // 0 for horizontal gap
答案 1 :(得分:2)
重要的是要澄清这个问题,因为与右边对齐的内容和从右到左添加的内容之间存在差异......
您可以通过多种方式将组件对齐到右侧,您可以使用GridBagLayout
,但最简单的方法可能是使用FlowLayout
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(new JLabel("Aligned"));
add(new JLabel("to"));
add(new JLabel("the"));
add(new JLabel("right"));
}
}
}
这只是使用Component#setComponentOrientation
并将其设置为ComponentOrientation.RIGHT_TO_LEFT
以更改组件的布局方向
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(new JLabel("Starting"));
add(new JLabel("from"));
add(new JLabel("the"));
add(new JLabel("right"));
}
}
}