I want to make a programm in java that dropps a square at the position of your mouse. For that I wanted to draw a grid as background and then add the squares but as soon as I add a new component to the JFrame the background disappers. This also happens the other way around so if I add a Square and then add the Background the square disappers. The following is the code. My Question is now how I can add the second Graphic without the first one disapiring. I’m also sorry if my english isn’t that great it is not my native language.
import java.awt.BorderLayout;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
//Mainmethod
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello World");
MainFrame myFrame = new MainFrame();
myFrame.init();
}
}
//Window
public class MainFrame extends JFrame{
public void init(){
Image Logo; // Image for the window icon
JPanel contentPane;
Background background = new Background();
Sand sand = new Sand();
try {//sets the WidnowIcon
Logo = ImageIO.read(new File("Logo.jpg"));
setIconImage(Logo);
} catch (IOException e) {
e.printStackTrace();
}
//JFrameconfiguratio
setTitle("Sandsim");
setSize(600, 600);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
//contentPaneconfiguration
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.setVisible(true);
setContentPane(contentPane);
//adds Background and sand but you can only see the one that was added last
contentPane.add(background);
contentPane.add(sand);
}
}
//draws the Bakground as grid of 10 by 10 squares
class Background extends JComponent {
public void paintComponent(Graphics g) {
int positionX = 0;
int positionY = 0;
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
for (int i = 0; i < getBounds().width / 10; i++) {
g2d.drawLine(positionX, 0, positionX, getBounds().height);
positionX += 10;
}
for (int i = 0; i < getBounds().height / 10; i++) {
g2d.drawLine(0, positionY, getBounds().width, positionY);
positionY += 10;
}
}
}
//draws a Sandcorn as 10 by 10 Rectangle
public class Sand extends JComponent{
public void paintComponent(Graphics g){
Graphics2D g2d =(Graphics2D)g;
g2d.setColor(Color.YELLOW);
g2d.fillRect(10, 10, 10, 10);
}
}
I tryed to get it to work for to hours now but I couldn’t find a solution for it. I looked on Oracel and searched for some tutorials on the internet but they always worked without making any special ajustments or something like that. I would really appriciate any kind of help.
Wurstbrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.