我试图从静态main()移动到名为paintComponent()的非静态方法,但我遇到的问题是我不能以我的方式从静态移动到非静态。这个类是一个跟随,猎人和猎人是外部类:
import javax.swing.JFrame;
import java.awt.Graphics;
public class Main extends JFrame{ //Public class: Available for all other classes to refer to
private static final long serialVersionUID = -4511248732627763442L;
public static void main(String[] args){
frame();
repaint();
move(); //Passes to the method move() in the class Main()
}
public static JFrame frame(){
JFrame frame = new JFrame("Hunter VS Hunted"); //Sets the window title
frame.setExtendedState(JFrame.MAXIMIZED_BOTH); //Sets the size of the window
frame.setVisible(true); //Says to display the window
frame.setResizable(false); //Sets it so the screen cannot be adjusted
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Closes the window when the x is pushed
System.out.println("Frame works.");
return frame;
}
public void paintComponent(Graphics g){
super.paintComponents(g); //Assigns a graphics value to g, so that it can be passed to other methods
Hunted.paint(g);
Hunter.paint(g);
System.out.println("Main.paintComponent works.");
}
public static void move(){
Hunter.move(); //Passes to move() in the Hunter class
Hunted.move(); //Passes to move() in the Hunter class
}
}
请记住我是初学者,所以请尽量保持简单!
答案 0 :(得分:0)
您需要使用对象调用repaint和paintComponents。
JFrame frame = frame();
frame.repaint();
move();
需要从对象调用每个非静态方法。静态方法属于该类,因此您可以在没有对象的情况下调用它们。
repaint和paintComponents属于JFrame对象。它们不是静态的,因此需要使用对象调用它们(重绘将调用paintComponents)。 你的框架()'方法将返回一个JFrame对象。因此,您可以使用从' frame()'返回的JFrame对象调用repaint()方法。方法。
话虽如此,我不确定你要在代码中尝试完成什么,即使我的解释将解决编译错误,但没有进一步详细说明,它可能无法实现你想要实现的目标
答案 1 :(得分:0)
顺便说一下,我对闹鬼和闹鬼一无所知。
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args){
myFrame x = new myFrame("Hunter VS Hunted");
x.ui(x.getContentPane());
}
}
class myFrame extends JFrame {
public myFrame(String name){
// constractor
super(name); //Sets the window title
setExtendedState(JFrame.MAXIMIZED_BOTH); //Sets the size of the window
setVisible(true); //Says to display the window
setResizable(false); //Sets it so the screen cannot be adjusted
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Closes the window when the x is pushed
}
public void ui(final Container pane){
JLabel test = new JLabel("test frame");
pane.add(test);
System.out.println("Frame works.");
}
}
现在如果在这个类中包含图形,每次调用repaint()时,它都会调用paintComponent(Graphics g)函数。祝你好运:)