我正在尝试使用 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();
}
});
}
}
没什么了不起的:)
关于java - 我的图形无法绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774928/