Reputation: 81
I'm writing a game in Java swing, and have a few layers of classes that I need to implement.
Here are the classes:
Main class:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Main extends JFrame {
public static void main (String [] args) {
new Main ();
}
public Main () {
// Window setup
setSize (700, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container content = getContentPane();
content.setLayout(new BorderLayout());
// Put a Game in
Game myGame=new Game ();
myGame.setBorder(new LineBorder(Color.black, 9));
content.add(myGame, BorderLayout.CENTER);
setVisible (true);
}
This is my Game class. From here I want to add the Board and Panels, and I want the Board to add the Rooms, etc. I don't know how to encapsulate classes and still add them and setVisible. I know how to do it within main, but is there a way to add stuff to Game using a similar content.add() type of thing?
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Game extends JComponent {
public void paintComponent (Graphics g) {
JPanel ControlPanel=new JPanel();
ControlPanel.setLayout(new FlowLayout());
ControlPanel.setBorder(new LineBorder(Color.red, 9));
}
}
TL;DR- how do I encapsulate and display different classes? New to JavaSwing...
Upvotes: 2
Views: 722
Reputation: 347314
To start with...DON'T DO THIS!! EVER!!
public void paintComponent (Graphics g) {
JPanel ControlPanel=new JPanel();
ControlPanel.setLayout(new FlowLayout());
ControlPanel.setBorder(new LineBorder(Color.red, 9));
}
Also you MUST call super.paintComponent
as well, unless you have a REALLY, REALLY good reason not to. These methods do a lot of important background work.
Never modify any component from within the context of the any paintXxx
method. This will put you into an infinite loop and eventually consuming all you CPU.
I would start by having a read through
Upvotes: 3