+--------------------------------------------+
| +-------+ +----------+|
| | +---+ | | +-----+ ||
| | | A | | | | B | ||
| | +---+ | | +-----+ ||
| +-------+ +----------+|
+--------------------------------------------+
^
|
|
Center
背景:我有
所需结果:我想要
我试过了:这些对我不起作用
我不想放置一个不可见的组件WEST来撤消转移
+--------------------------------------------+
| +-------+ +----------+|
| | +---+ | | +-----+ ||
| | | A | | | | B | ||
| | +---+ | | +-----+ ||
| +-------+ +----------+|
+--------------------------------------------+
^ ^
| |
| |
| Center
|
Shifted Left
GridLayout不起作用,因为我不希望扩展“A”和“B”
感谢任何建议!
P.S。
JButton / JLabel每个都在自己的JPanel中,因为没有Jpanel,BorderLayout.CENTER会在主要面板的整个宽度(直到JLabel的左边缘)上扩展JButton。 JPanels对于问题陈述不是必需的/关键的
结论:
答案 0 :(得分:5)
您应嵌套JPanel并使用布局组合。将包含JButtons的面板放置到使用GridLayout(1,0)(1行,可变列数)的另一个JPanel中可以工作,并将该JPanel放入BorderLayout的BorderLayout.NORTH位置 - 使用JPanel可以工作。
例如
import java.awt.*;
import javax.swing.*;
public class Foo003 {
private static void createAndShowGui() {
JButton btnA = new JButton("A");
JButton btnB = new JButton("B");
btnA.setPreferredSize(new Dimension(50, 25));
btnB.setPreferredSize(new Dimension(100, 25));
JPanel btnAPanel = new JPanel(); // uses default FlowLayout.CENTER
JPanel btnBPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btnAPanel.add(btnA);
btnBPanel.add(btnB);
JPanel topPanel = new JPanel(new GridLayout(1, 0));
topPanel.add(new JLabel("")); // empty placeholder label
topPanel.add(btnAPanel);
topPanel.add(btnBPanel);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.setPreferredSize(new Dimension(400, 300));
JFrame frame = new JFrame("Foo003");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}