如何在JFrame中显示由正方形组成的网格中的JButton?

时间:2016-07-25 12:13:08

标签: java jframe jbutton

如何在正方形形成的网格中显示按钮?我一直试图通过自己的方式来做,但似乎没有用,因为JButton没有正确显示在网格中。

import javax.swing.*;
import java.awt.*;
import java.util.*;
public class panel extends JFrame{
    public panel() {
        super();
        setSize(600,600);
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void paint(Graphics g) {
        /*
         * Grid
         */
        g.drawRect(200,0,0,600);
        g.drawRect(400,0,0,600);
        g.drawRect(0,200,600,0);
        g.drawRect(0,400,600,0);

        JPanel p = new JPanel();
        Dimension d = new Dimension (100,100);
        JButton b = new JButton("Button");
        b.setPreferredSize(d);

        p.add(b);
        add(p, BorderLayout.NORTH);
    }
}

1 个答案:

答案 0 :(得分:-1)

使用GridLayout而非BorderLayout使jbutton以网格形式出现, - http://www.tutorialspoint.com/swing/swing_gridlayout.htm