[英]How do I call a function with a graphics object from another class?
我想从main()
调用paint()
但我需要一个参数。我不知道要传递哪个参数,并且在参数外定义g
时似乎无法使用Graphics
对象,因为它不可能初始化。
我尝试在main()
创建Graphics类的对象,然后将其作为参数传递,但是每当我尝试使用g时,它都会向我抛出nullException
import java.util.*;
import java.awt.*;
import javax.swing.JFrame;
class Boards extends Canvas
{
JFrame frame;
void frame()
{
JFrame frame = new JFrame("SNAKES AND LADDERS");
Canvas canvas= new Boards();
canvas.setSize(1000,1000);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
frame.getGraphics();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics g;
}
public void paint(Graphics g)
{
g.fillRect(0,0,100,1000);
}
}
class snakes_and_ladders
{
Scanner s= new Scanner (System.in);
Boards board= new Boards();
void main()
{
board.frame();
board.paint();
}
}
要重绘图形区域,请勿直接调用paint
方法,而应使用invalidate
方法。
您将需要致电repaint 。 从文档:
public void repaint(long tm, int x, int y, int width, int height)
如果正在显示组件,则将指定的区域添加到脏区域列表中。 分派了所有当前暂挂的事件后,该组件将重新绘制。
编辑
间接参数化的示例:
protected String test = "foo";
public void myRepaint(long tm, int x, int y, int width, int height, test) {
this.test = test;
repaint(tm, x, y, width, height);
}
public void paint(Graphics g) {
//do something with this.test
}
我建议您使用Swing
扩展JPanel
并覆盖paintComponent
。 Canvas
是AWT
类,您不应混合使用Swing
和AWT
功能。
并确保您将super.paintComponent()作为第一条语句。 要重新粉刷面板,您只需调用repaint()
。
永远不要直接调用Paint方法,因为它应该在事件调度线程(EDT)中完成绘制。 您也不需要保护图形上下文。
这是一个非常简单的示例,演示了运动。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MovementDemo extends JPanel implements ActionListener {
JFrame frame = new JFrame("Movement Demo");
int size = 500;
int x = 50;
int y = 200;
int diameter = 50;
int yinc = 2;
int xinc = 2;
int xdirection = 1;
int ydirection = 1;
public MovementDemo() {
setPreferredSize(new Dimension(size, size));
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MovementDemo().start());
}
public void start() {
Timer timer = new Timer(100, this);
timer.setDelay(5);
timer.start();
}
public void actionPerformed(ActionEvent ae) {
if (x < 0) {
xdirection = 1;
}
else if (x > size - diameter) {
xdirection = -1;
}
if (y < 0) {
ydirection = 1;
}
else if (y > size - diameter) {
ydirection = -1;
}
x = x + xdirection * xinc;
y = y + ydirection * yinc;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.BLUE);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, diameter, diameter);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.