Reputation: 3065
I am attempting to draw a grid of lines on a JPanel
placed insided JFrame
using a BufferedImage
.
So far I have got the vertical lines working (sort of) but my query is in relation to the Color
of the lines and background.
When I run the application the JFrame
and JPanel
appears but the Color
of the background is black and the lines are White
. It's as though the Colors are inverted. (see image below)
I haven't set any Color
in my Main class and my source code for the JPanel
is as follows-
public class MyPanel extends JPanel {
boolean[][] grid;
BufferedImage image;
Graphics2D imageG;
public MyPanel(boolean[][] newGrid) {
grid = newGrid;
image = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_RGB);
imageG = image.createGraphics();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Integer cellWidth = this.getWidth() / grid.length;
for (Integer i = 0; i < grid.length + 1; i++) {
imageG.drawLine(i * cellWidth, 0, i * cellWidth, this.getHeight());
}
Graphics2D tempg = (Graphics2D) g;
tempg.fillRect(0, 0, this.getWidth(), this.getHeight());
//Draw BufferedImage
tempg.drawImage(image, 0, 0, this);
//this.getGraphics().drawImage(lineImage, 0, 0, this);
}
}
Upvotes: 1
Views: 240
Reputation: 4935
Use BufferedImage.TYPE_INT_ARGB
which Represents an image with 8-bit RGBA color components packed into integer pixels.
and earlier using BufferedImage.TYPE_INT_RGB
which Represents an image with 8-bit RGB color components packed into integer pixels. also it lacks with transparent
Colors
as well as undefined
Colors
and thus it illustrates those with Color.BLACK
.
rectified source code from above -
public MyPanel(boolean[][] newGrid) {
grid = newGrid;
//Represents an image with 8-bit RGBA color components packed into integer pixels.
image = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_ARGB);
imageG = image.createGraphics();
//Set the single pixel line color to YELLOW using BufferedImage instance
imageG.setColor(Color.YELLOW);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Integer cellWidth = this.getWidth() / grid.length;
Graphics2D tempg = (Graphics2D) g;
//Set the blocks and rest of it part to color RED
tempg.setColor(Color.RED);
for (Integer i = 0; i < grid.length + 1; i++) {
imageG.drawLine(i * cellWidth, 0, i * cellWidth, this.getHeight());
}
tempg.fillRect(0, 0, this.getWidth(), this.getHeight());
//Draw BufferedImage
tempg.drawImage(image, 0, 0, this);
//this.getGraphics().drawImage(lineImage, 0, 0, this);
}
hope this will help you, thanks.
Upvotes: 3