我的图形不是绘图

时间:2013-12-25 16:50:48

标签: java swing awt

我正在尝试使用Java图形制作GUI,但由于某种原因它不起作用。这是代码:

public class ScreenCap extends Canvas {

/**
 * @param args the command line arguments
 */
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String[] args) {
    new ScreenCap();
}

public ScreenCap() {
    Window window = new Window(this);
    window.setVisible(true);
    this.addMouseListener(new MouseHandler());
    drawComponents();
}

private void drawComponents() {
    System.out.println("in draw");
    createBufferStrategy(3);
    BufferStrategy bs = getBufferStrategy();

    Graphics g = bs.getDrawGraphics();

    g.setColor(Colors.BG);
    g.fillRect(0, 0, getWidth(), getHeight());
}
}

1 个答案:

答案 0 :(得分:2)

我会考虑使用Swing而不是AWT。 AWT过时了。如果使用swing,你会做类似下面的代码

  • 子类JPanel
  • 覆盖paintComponent(Graphics g)
  • 投放到Graphics2D(可选)以获得更多通用性
  • 使用paintComponent方法
  • 绘制
  • 将面板类的实例添加到容器中。

阅读有关Graphics here的更多信息。加载教程。更多关于Swing here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class SwingDemo extends JPanel {
    private static final int DIM_WIDTH = 500;
    private static final int DIM_HEIGHT = 500;


    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        g2.setColor(Color.BLUE);
        g2.fillRect(100, 100, 200, 200);
    }

    public static void createAndShowGui(){
        JFrame frame = new JFrame();
        frame.add(new SwingDemo());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);

    }

    public Dimension getPreferredSize(){
        return new Dimension(DIM_WIDTH, DIM_HEIGHT);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                createAndShowGui();
            }
        });
    }
}

enter image description here

没什么了不起的:)