如果我有代碼,像這樣:如何添加JButton到GridLayout?
class X extends JFrame
{
X()
{
setLayout(new GridLayout(3,3));
JButton b = new JButton("A-ha");
/*I would like to add this button in the center of this grid (2,2)*/
//How can I do it?
}
};
如果我有代碼,像這樣:如何添加JButton到GridLayout?
class X extends JFrame
{
X()
{
setLayout(new GridLayout(3,3));
JButton b = new JButton("A-ha");
/*I would like to add this button in the center of this grid (2,2)*/
//How can I do it?
}
};
正如我所知道的,你以前來填補以前所有的細胞。所以你需要添加4個組件,然後才能添加中心組件。嗯,它可能是一個更好的佈局管理者。
你想做什麼?也許BorderLayout是你在找什麼?
你可能想看看GridBag Layout
GridBagLayout讓我做到這一點嗎? – 2010-05-12 10:19:36
根據該教程, 「您可以設置以下GridBagConstraints實例變量: gridx,gridy 指定組件的左上角的行和列。最左邊的列的地址爲gridx = 0,頂行的地址爲gridy = 0。使用GridBagConstraints.RELATIVE(默認值)來指定該組件被放置在恰好在(對於gridx)的右側或正好在gridy以下的組件被添加到該組件被添加之前。「 按照鏈接瞭解更多詳情:) – npinti 2010-05-12 10:49:16
這種垂直和水平
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class centerbutton extends JFrame{
public centerbutton(){
setLayout(new BorderLayout());
JPanel panel = new JPanel();
JButton button = new JButton("A-ha!");
button.setAlignmentX(
Component.CENTER_ALIGNMENT);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createVerticalGlue());
panel.add(button);
panel.add(Box.createVerticalGlue());
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new centerbutton();
}
}
我基本上從http://answers.yahoo.com/question/index?qid=20090729150118AAHGvrI偷了它 – colinjwebb 2010-05-12 12:37:26
中心是,基本上只是一個帶有大邊框按鈕? – colinjwebb 2010-05-12 10:15:43
@colinjameswebb面板中央的一個按鈕。 – 2010-05-12 10:22:07