I have a class called survival that contains the main method, an initializes the program. Instead of putting the code for graphics int this class, how can I move it into a new class which is separate from survival?
Here is Survival.java:
package survival;
import javax.swing.*;
public class Survival extends JFrame {
private static int applicationWidth = 1024;
private static int applicationHeight = 768;
public Survival() {
setTitle("Survival");
setResizable(false);
setSize(applicationWidth, applicationHeight);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Survival();
}
}
Here is GraphicsDisplay.java:
package survival;
import java.awt.*;
import javax.swing.*;
public class GraphicsDisplay extends JPanel {
@Override public void paintComponent(Graphics g) {
g.fillOval(50, 50, 100, 100);
}
}
It seems like you can just
add()an instance ofGraphicsDisplayin theSurvivalconstructor.In this case,
GraphicsDisplayacts as a view of your implicit, circular model. You might look at how this example separates classes in the Model–View–Controller pattern.Because
GraphicsDisplayis a custom component that is rendered entirely by your program, consider overridinggetPreferredSize()to define the panel’s geometry. Then the enclosing frame can just usepack()without knowing anything about other display panels used in the game. ThisLissajousPanelis an example.