画布不会用java绘制

时间:2017-12-25 03:08:47

标签: java canvas

似乎有一些我想念的东西。或者我没有完全理解canvas如何在java中工作。问题是画布没有创造任何东西。在下面的代码中,我知道画布正在工作和显示,因为背景颜色已变为淡蓝色,但它应该在该画布内添加一个小红色框。我现在的目标是让画布显示那个小盒子。

//框架     私有静态JFrame框架;

private static BufferStrategy bs;
private static Graphics g; 
private static JPanel jp;
private static Canvas canvas;
private static int width = 1000;
private static int height = 1000;

public static void main(String[] args)  {
    // TODO Auto-generated method stub

    locX.clear();
    locY.clear();

    loadData();


    createFrame();

}   

public static void createFrame() {
    frame = new JFrame("Title");
    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(true);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(width,height));
    canvas.setMaximumSize(new Dimension(width,height));
    canvas.setMinimumSize(new Dimension(width,height));
    canvas.setBackground(Color.cyan);
    //jp.setSize(new Dimension(width,height));

    //frame.add(jp);
    frame.add(canvas);
    frame.pack();

    bs = canvas.getBufferStrategy();
    if(bs == null) {
        canvas.createBufferStrategy(1);
        return;
    }

    g =  bs.getDrawGraphics();
    // clear screen
    //g.clearRect(0, 0, width, height);

    g.setColor(Color.red);
    g.fillRect(400, 50, 100, 100);
    bs.show();
    g.dispose();
}

0 个答案:

没有答案