Answer the question
In order to leave comments, you need to log in
How to draw objects from another class in JPanel?
I'm trying to make a small game and ran into a problem with drawing objects.
Main class.
public class Main {
public static Frame frame = new Frame();
public static JPanel[] panels = {new Game(), new Menu()};
public static void main(String[] args) {
frame = new Frame();
frame.add(panels[0]);
frame.add(panels[1]);
if(panels[1].isVisible()) {
frame.remove(panels[0]);
panels[0].setVisible(false);
}
if(panels[0].isVisible()) {
frame.remove(panels[1]);
panels[1].setVisible(false);
((Game) panels[0]).start();
}
}
}
public class Menu extends JPanel {
public Menu() {
JButton btn = new JButton("Start");
add(btn);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Main.frame.add(Main.panels[0]);
Main.frame.remove(Main.panels[1]);
Main.panels[0].setVisible(true);
}
});
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g.setColor(Color.BLUE);
g.fillRect(0, 0, Frame.frameW, Frame.frameH);
}
}
public class Game extends JPanel implements Runnable {
public static int WIDTH = Frame.frameW, HEIGHT = Frame.frameH;
public Thread thread;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);;
private Graphics2D g = (Graphics2D) image.getGraphics();
public static GameBack background;
public static Player player;
public Game() {
super();
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void run() {
background = new GameBack();
player = new Player();
while(true) {
gameUpdate();
gameRender();
gameDraw();
try {
Thread.sleep(33);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
public void gameUpdate() {
background.update();
player.update();
}
public void gameRender() {
background.draw(g);
player.draw(g);
}
public void gameDraw() {
Graphics g2 = this.getGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
}
}
public class GameBack {
private Color color;
public GameBack() {
color = Color.BLUE;
}
public void update() {
}
public void draw(Graphics2D g) {
g.setColor(color);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question