I have coded a MazeClass that paints a grid and has a method to change the color of a block on the grid. I would like to display this grid in a separate class on a jframe in the position I want to. Here is the class:
package mazemania;
import java.awt.*;
public class MazeClass extends javax.swing.JFrame{
private Color[][] colorArr = new Color[20][20];
public MazeClass(){
setVisible(true);
}
public void paint(Graphics g)
{
for(int row = 0; row < 20; row++)
{
for(int column = 0; column < 20; column++)
{
g.setColor(colorArr[row][column]);
g.fillRect(row*15, column*15, 15, 15);
g.setColor(Color.BLACK);
g.drawRect(row*15, column*15, 15, 15);
}
}
} //End of paint method
public void colorBlock(Color c, int row, int col)
{
colorArr[row][col] = c;
repaint();
}
}
I have tried instantiating the MazeClass from another class but it created separate jpanel instead of placing it on the one in the class.
package mazemania;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Graphics;
/**
*
* @author jin06
*/
public class CampaignGUI extends javax.swing.JFrame {
//PauseGUI pauseScreen = new PauseGUI();
/**
* Creates new form CampaignGUI
*/
public CampaignGUI() {
initComponents();
MazeClass maze = new MazeClass();
maze.colorBlock(Color.RED, 1, 1);
maze.setVisible(true);
}
How would I place this grid inside the GUI I have already designed, in the position I would like to? I would appreciate any help. Thank you.
Your class extends javax.swing.JFrame. So if you instantiate an object of it, this will always be a (new) JFrame.
You need to split up your code for the Maze and the GUI.
Make a class "GameWindow
extends JFrame". In this GameWindow class you can overwrite the paint() method and inside of it you call your maze.paint() method. The GameWindow's constructor might have a parameter to feed the maze object into it.
The GameWindow instantiation can then be integrated in your CampaignGUI
class.
(and don't forget to remove the extends JFrame
from your Maze class ;) (and maybe also from the CampaignGUI class, if you only want to have one window, I suggest use GameWindow for this purpose).
To change the position of the Maze in your GameWindow, you need to check two things:
GridLayout
for example or a FlowLayout
which can be added to the Frame (Window). Then you can add the Panel to LayoutManager and arrange your components that way.One more advice:
You can also try to just add the Panel to the ContentPane of your GameWindow, which is a swing.Frame
. This will provide a method call like getContentPane().addComponent(myPanel);
or similar). Then you also have to setPosition() and setDimension() (or setWidth() and setHeight()) of the panel. This way you have more pixel-accurate control of the size and positioning of your panel, but it won't scale automatically if you resize the Window. This would be the benefit of using a LayoutManager.