[英]Static to non static method
我正在尝试从静态main()转移到称为paintComponent()的非静态方法,但是我遇到的问题是我无法以自己的方式从“静态”转移到“非静态”。 该类是以下类,其中hunter和hunted是外部类:
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
}
}
请记住,我是初学者,所以请尽量保持简单!
您需要使用一个对象来调用repaint和paintComponents。
JFrame frame = frame();
frame.repaint();
move();
每个非静态方法都需要从一个对象中调用。 静态方法属于该类,因此您可以在没有对象的情况下调用它们。
repaint和paintComponents属于JFrame对象。 它们不是静态的,因此需要使用一个对象来调用它们(重新绘制将调用paintComponents)。 您的'frame()'方法将返回JFrame对象。 因此,您可以使用从'frame()'方法返回的JFrame对象调用repaint()方法。
话虽如此,但我不确定您要在代码中尝试完成的工作,即使我的解释能够解决Compilation-Error(编译错误),而无需进一步详细说明,它也可能无法完成您要实现的目标。
您有一些混乱的代码! 但让我整理一下,使其更美观。 但是,这取决于您现在使其开始工作。 我为您的jframe创建了另一个类,并在承包商中调整了您的额外/重复代码。
顺便说一句,我对鬼屋和鬼屋一无所知。
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)。 祝好运 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.