私がそのようなコードを持っている場合:
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?
}
};
私がそのようなコードを持っている場合:
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?
}
};
これは垂直方向と水平方向に中央に配置されます
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();
}
}
私が知っているように、以前のすべてのセルを埋める必要があります。したがって、中心コンポーネントを追加する前に、4 つのコンポーネントを追加する必要があります。うーん、それはより良いレイアウトマネージャーかもしれません。
あなたは何をしようとしているのですか?多分BorderLayoutはあなたが探しているものですか?
GridBag レイアウトをご覧になることをお勧めします。