答案 0 :(得分:0)
尝试使用边框布局,其中按钮位于东边,标题位于中心。
希望有所帮助。
- 更新----
以下是我试图分享的片段代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class TestSwing {
public static void main(String...s) {
JFrame jframe = new JFrame();
JPanel heading = new JPanel();
JPanel buttons = new JPanel();
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
button1.setPreferredSize(new Dimension(40, 40));
button2.setPreferredSize(new Dimension(40, 40));
button3.setPreferredSize(new Dimension(40, 40));
buttons.setLayout(new GridLayout(1,3));
buttons.add(button1);
buttons.add(button2);
buttons.add(button3);
heading.setLayout(new BorderLayout());
JLabel title = new JLabel("Title",SwingConstants.CENTER);
title.setVerticalAlignment(SwingConstants.CENTER);
heading.add(buttons,BorderLayout.EAST);
jframe.setLayout(new BorderLayout());
jframe.add(heading,BorderLayout.NORTH);
JPanel blankPanel = new JPanel();
blankPanel.setPreferredSize(new Dimension(120,40));
heading.add(blankPanel,BorderLayout.WEST);
heading.add(title,BorderLayout.CENTER);
jframe.setVisible(true);
}
}
输出截图:
答案 1 :(得分:0)
免责声明:这是一次巨大的欺骗......
所以,这个例子基本上利用了GridBagLayout
,这将允许“title”标签占据容器中可用空间的整个宽度,并允许按钮同时沿右边缘布局
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
// This is a space to force the buttons
// to the right edge.
// You might be able to play around with the constraints
// for b1 to basically get the same affect
add(new JLabel(), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
JLabel label = new JLabel("This is the title");
label.setHorizontalAlignment(JLabel.CENTER);
add(label, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
add(new JButton("B1"), gbc);
gbc.gridx++;
add(new JButton("B2"), gbc);
gbc.gridx++;
add(new JButton("B3"), gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 44);
}
}
}