JButton background color AND image - java

I have read through and tried several approaches to changing the background color of a JButton with a buffered image, but I am consistently getting the same results. I am using a 2D array of ImageIcons, some with file names such as:
ImageIcon blackRook1 = new ImageIcon("ChessPiece/Chess_rdt60.png");
the png's I am using do not fill the entire square, just the actual chess piece
and others with BufferedImages such as:
ImageIcon space = new ImageIcon(new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
I am then looping through chessBoardSquares, which is an empty 8x8 2D array of JButtons, with:
Insets buttonMargin = new Insets(0, 0, 0, 0);
for(int i = 0; i < chessBoardSquares.length; i++) {
for(int j = 0; j < chessBoardSquares[i].length; j++) {
JButton b = new JButton();
b.setMargin(buttonMargin); // Insets object
ImageIcon icon = this.chessPieces[i][j]; // 2D array of ImageIcons
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);[![enter image description here][1]][1]
Graphics2D g = bi.createGraphics();
//determine color of graphic and jbutton background
int colorDeterminator = j + i;
if(colorDeterminator % 2 == 0) {
// System.out.println("Getting here and coloring white");
b.setBackground(Color.WHITE);
g.setColor(Color.WHITE); // I have also tried with this line commented out
} else {
// System.out.println("Getting here and coloring black");
b.setBackground(Color.BLACK);
g.setColor(Color.BLACK);
}
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
icon.paintIcon(null, g, 0, 0);
g.dispose();
b.setOpaque(true);
b.setIcon(icon);
the if statement using color determinator has definitely run as the print statements have executed
I cannot post images without enough reputation points, so my thought was to post the question in Game Development. I feel that it is more relevant to this channel however, so I will link to that post with the image here.
THE ISSUE
There is a square filling most of the JButton, which I believe is the BufferedImage, that is white regardless of what color I set the Graphics2D or the JButton itself. Because I want the whole square to be black in some cases (except for the piece on top of it), I need a way to color the rest of the square.
Same post with image

Related

Draw a rectangle around image

I want to draw a rectangle around BufferedImage so it will create a border like frame.
So I load 2 BufferedImage:
BufferedImage a = ImageIO.read(new File(aPath));
BufferedImage b = ImageIO.read(new File(bPath));
And send it for drawing:
private void drawImageBorder(BufferedImage imageWithoutBorder) {
Graphics2D graph = imageWithoutBorder.createGraphics();
graph.setColor(Color.BLACK);
//create a black Rectangle - 1px bigger the original image
graph.fill(new Rectangle(imageWithoutBorder.getMinX(), imageWithoutBorder.getMinY(), imageWithoutBorder.getWidth() + 1, imageWithoutBorder.getHeight() +1));
//draw the image inside it
graph.drawImage(imageWithoutBorder, 0, 0, null);
graph.dispose();
}
For some reason it does nothing, there are similer questions like drawing-filled-rectangle-over-a-bufferedimage but I could not finnd helpful answers.
Thanks.
Almost right, but for the enlarged size and positioning.
BufferedImage image = ImageIO.read(new File(imagePath));
int w = image.getWidth();
int h = Image.getHeight();
int border = 1;
BufferedImage framedImage = new BufferedImage(w + 2*border, h + 2*border, image.getType());
Graphics2D graph = framedImage.createGraphics();
graph.setColor(Color.BLACK);
graph.fill(new Rectangle(0, 0, w + 2*border, h + 2*border));
graph.drawImage(image, border, border, null);
graph.dispose();
Possible reason can be, that you don't persist the changes made to the image, for example writing them back into an image file with ImageIO.write.

Why am I getting a black image after replacing all the pixels of a BufferedImage object with magenta colored ones?

I am following a Java Game development tutorial, and I hit a roadblock because I am unable to figure out what is wrong with my code. I am supposed to render a new image by changing each pixel of the buffered image into the color I want. Then I copy that array over to the array in my Game class and I draw the rendered image. The relevant code is directly below. I discuss what I have tried directly after the code snippets.
This code snippet is from my Game class:
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Converts image into array of integers
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
screen = new Screen(width, height);
frame = new JFrame();
pixels = new int[width * height];
}
// Displays images to the screen
public void render() {
BufferStrategy bs = getBufferStrategy();
// Checks if the buffer strategy exists. If it doesn't create a triple buffer strategy
if(bs == null) {
// Triple buffering
createBufferStrategy(3);
return;
}
screen.render();
// Copies array in Screen class to pixels array in (this) class
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
// Must be in chronological order
Graphics g = bs.getDrawGraphics();
g.setColor(Color.CYAN);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
// Display next available buffer
bs.show();
}
This code snippet is from my Screen class:
private int width;
private int height;
public int[] pixels;
public Screen(int width, int height) {
this.width = width;
this.height = height;
// Size of the pixels array reserves one element for each pixel
pixels = new int[width * height];
}
public void render() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pixels[x + y * width] = 0xff00ff;
}
}
}
I have tried to "debug" by checking to see if both of my pixels arrays in the Game and the Screen class are being loaded with the magenta color. I simply did:
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
System.out.println(pixels[i]);
}
and I also tried:
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
System.out.println(screen.pixels[i]);
}
In both cases, the decimal representation of magenta (FF00FF in Hex) gets printed out until I close the window.
Another thing I tried is using the image.setRGBmethod to change the color of the image.
I added this line
image.setRGB(20, 20, 16711935); into the render method as follows:
// Displays images to the screen
public void render() {
BufferStrategy bs = getBufferStrategy();
// Checks if the buffer strategy exists. If it doesn't create a triple buffer strategy
if(bs == null) {
// Triple buffering
createBufferStrategy(3);
return;
}
screen.render();
// Copies array in Screen class to pixels array in Game (this) class
/* for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
*/
// Must be in chronological order
Graphics g = bs.getDrawGraphics();
g.setColor(Color.CYAN);
g.fillRect(0, 0, getWidth(), getHeight());
image.setRGB(20, 20, 16711935);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
// Display next available buffer
bs.show();
}
A magenta dot showed up in my frame, and I am also able to turn the entire frame into a solid magenta color by modifying the render method in the Screen class. Now, I am wondering why my "original" code isn't working. From what I understand, the setRGB method is much slower than what I originally intended on using to render images, so I don't want to just give up and settle with using setRGB.
I have spent practically the entire day going over all the spelling in my code, making sure those nested for loops in the Screen class are correct, and etc. I am at a loss here. I don't understand what the issue is.
If the code snippets I included are not enough, I have created a Gist of my code in its entirety here.
This code gets the color int for the input rgb colors
public static int getIRGB(int Red, int Green, int Blue){
Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
Blue = Blue & 0x000000FF; //Mask out anything not blue.
return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}
I suspect you are drawing a magenta color with 0% opacity

Java GlassPanel clear transparent background

I want to render something on my GlassPane. The problem is, that if i move the rendered lines around, the previously rendered pixels have still the same color.
I can not use g.clearRect because it doesn`t clears the transparency.
Thats my rendering code:
Graphics2D g2 = (Graphics2D) g;
for(LinePath line : lines)
{
for(int i = 0; i < line.points.length; i+=2)
{
if(i != 0)
{
g.drawLine((int)line.points[i-2],(int)line.points[i-1],(int)line.points[i],(int)line.points[i+1]);
}
}
}
//Clearing alpha
Area area = new Area();
// This is the area that will filled...
area.add(new Area(new Rectangle2D.Float(0, 0, getWidth(), getHeight())));
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.0f));
g2.fill(area);
And here is the result:
clearRect should work but you have to reset your alpha composite before using it.
Ex:
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f));

Convert JPanel to binary array

I programmed something like paint. I have JPanel and I can draw on it.I'm using only black line. I wanna convert it to binary array, where 1 is when pixel is black, 0 when is white (background). It's possible? How to do this?
In a nutshell, create a BufferedImage with the same dimensions as your JPanel and paint the panel to the image. Then you can iterate over the image raster to get the sequence of pixel color values corresponding to black and white. For example
// Paint the JPanel to a BufferedImage.
Dimension size = jpanel.getSize();
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = BufferedImage(size.width, size.height, imageType);
Graphics2D g2d = image.createGraphics();
jpanel.paint(g2);
// Now iterate the image in row-major order to test its pixel colors.
for (int y=0; y<size.height; y++) {
for (int x=0; ix<size.width; x++) {
int pixel = image.getRGB(x, y);
if (pixel == 0xFF000000) {
// Black (assuming no transparency).
} else if (pixel == 0xFFFFFFFF) {
// White (assuming no transparency).
} else {
// Some other color...
}
}
}

Display image from 2D array data in java

I have some data that is loaded from the text file that corresponds to my image file. this data is now in a 2D array. I want to show this image. apparently the image show be of format bufferedimage. but mine is just simple 2D double format.
Also how is possible to resize the image, meaning to make it twice bigger ( requiring interpolation in between of course)
In other words how can we do the "imshow" and " imresize" Matlab equilvalent in java?
There is no simple method for converting between an array based intensity matrix to a renderable image in Java, at least not that I am aware of. Nor is there any simple one line method for displaying an image on the screen etc.
It is however correct that a BufferedImage would be a viable solution in this case. What you would have to do is to create a BufferedImage of the desired size and then loop through your 2D intensity matrix and fill in the colors in the resulting image.
Once you have the data in form of a BufferedImage you can use it directly for rendering. For example you could create a JFrame with a custom JPanel component for displaying the image. The following sample code illustrates that procedure: (Note that this assumes that your image data in the 2D array is scaled to fit in the interval [0,1]. If it is not then it will have to be re-scaled prior to filling in the BufferedImage.)
public class ImageTest {
private static final int HEIGHT = 250;
private static final int WIDTH = 250;
public static void main(String[] args) {
double[][] data = new double[WIDTH][HEIGHT];
Random r = new Random();
for(int i = 0; i < WIDTH; i++) {
for(int j = 0; j < HEIGHT; j++) {
data[i][j] = r.nextDouble();
}
}
final BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)img.getGraphics();
for(int i = 0; i < WIDTH; i++) {
for(int j = 0; j < HEIGHT; j++) {
float c = (float) data[i][j];
g.setColor(new Color(c, c, c));
g.fillRect(i, j, 1, 1);
data[i][j] = r.nextDouble();
}
}
JFrame frame = new JFrame("Image test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// Or _BICUBIC
g2d.scale(2, 2);
g2d.drawImage(img, 0, 0, this);
}
};
panel.setPreferredSize(new Dimension(WIDTH*2, HEIGHT*2));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
If you are happy with resizing and interpolating in the resulting output image then you can achieve it by simply scaling the graphics context and enabling the interpolation rendering hint on it, as the above example shows when displaying/rendering the image. (This can of course be done directly in the BufferedImage as well in a similar fashion.
Have a look at MemoryImageSource. It might not do exactly what you want (because Java tends to use int / byte for image data) but it will at least send you down the right route.
http://www.javaworld.com/javatips/jw-javatip16.html

Categories

Resources