我看到您正在使用 GUI 设计器。我强烈建议“手动”构建您的 GUI,而不是在这种情况下,您的代码在 IMO 上更清晰(我并不是说所有 GUI 设计人员都会产生糟糕的代码,但它几乎总是更难阅读,如果不使用它,编辑它会很困难完全相同的 GUI 设计器)。一旦您对手工 GUI 设计感到满意,然后尝试 GUI 设计器,看看是什么让您更舒服。
见:http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
在您的情况下,您可以创建一个BorderLayout,并且在面板/框架的“南”,您可以放置一个带有FlowLayout 的面板,将其组件向左对齐。然后使用 FlowLayout 将您的按钮添加到面板中。
一个小演示:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
public class LayoutDemo extends JFrame {
LayoutDemo() {
super("LayoutDemo");
super.setSize(400, 200);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGUI();
super.setVisible(true);
}
private void createGUI() {
// set the layout of this frame
super.setLayout(new BorderLayout());
// create a panel to put the button on
final JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// create a text area to put in the center
final JTextArea textArea = new JTextArea();
// create the search button
final JButton searchButton = new JButton("search");
// add a listener to the button that add some text to the text area
searchButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText(textArea.getText() + "pressed search on " + (new Date()) + "\n");
}
});
// add the button to the bottom panel
bottomPanel.add(searchButton);
// wrap a scroll-pane around the text area and place it on the center of this frame
super.add(new JScrollPane(textArea), BorderLayout.CENTER);
// put the bottom panel (containing the button) on the 'south' of this frame
super.add(bottomPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LayoutDemo();
}
});
}
}
产生:
alt text http://img689.imageshack.us/img689/5874/guiq.png
编辑
要将按钮向上移动一点,请使用构造函数new FlowLayout(FlowLayout.LEFT, int hgap, int vgap)
其中hgap 是左右组件之间的间隙(以像素为单位),vgap 是上下组件之间的间隙(以像素为单位)。
试试:
final JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 10));
请注意,按钮和文本区域之间的空间也略有增加!