使用swing绘制网格

时间:2015-04-12 22:29:38

标签: java swing

试图在我的面板中显示一个4 x 4格的草图,代码在下面,我错过了一些明显的东西?任何帮助非常感谢。面板显示空白没有错误。我尝试添加包装,但它所做的就是让框架看起来很小。

public class frame extends JFrame {

private JPanel contentPane;
private JPanel panel;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                frame frame = new frame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public frame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    contentPane.add(getPanel());


}
private JPanel getPanel() {
    if (panel == null) {
        panel = new JPanel();
        panel.setBounds(49, 43, 252, 129);
        ImageIcon grassIcon = new ImageIcon("images/grass.gif");
        int size = 4;

        JPanel panel = new JPanel(new GridLayout(size,size,0,0));

        JLabel labels[] = new JLabel[(size*size)];

        for (int i =  0; i < size*size; i++)
        {
              labels[i] = new JLabel(grassIcon);
              panel.add(labels[i]);
        }

    }
    return panel;
}
}

0 个答案:

没有答案