1

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);
   }
}
Conner Ruhl
  • 1,693
  • 4
  • 20
  • 31

3 Answers3

3

It seems like you can just add() an instance of GraphicsDisplay in the Survival constructor.

...
setResizable(false);
add(new GraphicsDisplay());
setSize(applicationWidth, applicationHeight);
...

In this case, GraphicsDisplay acts as a view of your implicit, circular model. You might look at how this example separates classes in the Model–View–Controller pattern.

Because GraphicsDisplay is a custom component that is rendered entirely by your program, consider overriding getPreferredSize() to define the panel's geometry. Then the enclosing frame can just use pack() without knowing anything about other display panels used in the game. This LissajousPanel is an example.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

You have to extend the JPanel (JComponent) and override a paintComponent(Graphics g) method.

For instance,

public class MyPanel extends JPanel
{ 
   @Override
   public void paintComponent(Graphics g) {
       super.paintComponent(g); // suggestion of @kleopatra
   }
}
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0

In the Constructor add the component (JPanel) to the container (JFrame):

public Survival() {
    setTitle("Survival");
    setResizable(false);
    setSize(applicationWidth, applicationHeight);

    this.getContentPane().add( new GraphicsDisplay() );

    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}
  • 1
    "As a conveniance `add` and its variants, `remove` and `setLayout` have been overridden to forward to the `contentPane` as necessary."—[`JFrame`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html) – trashgod Dec 15 '11 at 06:22