java - 我的图形无法绘制

标签 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());
}
}

最佳答案

我会考虑使用 Swing 而不是 AWT。 AWT 已经过时了。如果使用 swing,您将执行类似以下代码的操作

  • 子类JPanel
  • 覆盖paintComponent(Graphics g)
  • 转换为 Graphics2D(可选)以获得更多功能
  • paintComponent 方法中绘制
  • 将面板类的实例添加到容器中。

了解有关图形的更多信息 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

没什么了不起的:)

关于java - 我的图形无法绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774928/

相关文章:

java - 如何将具有小数、负小数的字符串解析为整数?

java - SOLR配置问题

Java获取焦点

java - 当我将 X 推到关闭窗口时,为什么我的 AWT Java 窗口没有关闭?

java - ActionPerformed 和 ActionListener

java - 如何转义 Unicode 退格字符。在 Java 中用于 tomcat 日志

java - 如何从外部容器访问 JBoss 4.x 上的远程 EJB 2.1 bean

java - 如果屏幕最小化,如何防止Java删除内容?

java - 如何使用 setFocusable(false) 突出显示 JTextPane 中的文本?

java - setPreferredSize 不起作用