I really need some help with that.
I'm trying to crop an image into a circle and it's fine but the pixels outside the circle stay white. How can I put them transparent?
My code it's:
static ColorImage Circulo(ColorImage img, int radius) {
for (int x=0; x < img.getWidth(); x++ ) {
for(int y=0; y < img.getHeight(); y++) {
if((x - (img.getWidth()/2)) * (x - (img.getWidth()/2)) + (y - (img.getHeight()/2) )* (y - (img.getHeight()/2)) <= (radius*radius)) {
img.setColor(x, y, img.getColor(x, y));
}else {
Color c = new Color (255, 255, 255);
img.setColor(x, y, c );
}
}
}
return img;
}
Try this. This will paint the image on the screen inside a circle. If you want to create a new image, get the Graphics context from a BufferedImage and write the image to that instead of the graphics context in paintComponent. Any image format will work as this does not rely on any transparency mode of the graphics image.
The main idea behind this is setting the clip region to that of a circle. Then whatever you paint will only appear in that region.
In this example, I made the diameter of the circle the minimum of the width and height of the image. This way, the entire circle will fit in a rectangle.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ImageInCircle extends JPanel {
JFrame f = new JFrame();
Image img;
int width;
int height;
static String imgFile =
"location/of/image/img.gif";
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new ImageInCircle().start());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public ImageInCircle () {
f.add(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
try {
img = ImageIO.read(new File(imgFile));
} catch (IOException fne) {
fne.printStackTrace();
}
width = img.getWidth(null);
height = img.getHeight(null);
revalidate();
f.setVisible(true);
f.pack();
f.setLocationRelativeTo(null);
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.white);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int circleDiameter = Math.min(width,height);
Ellipse2D.Double circle = new Ellipse2D.Double(0,0,circleDiameter,circleDiameter);
g2.setClip(circle);
g2.drawImage(img,0,0,this);
}
}
Related
I'm creating a 2D topdown shooter game with Java Swing in which I want circular hitboxes for my player and enemies as well as projectiles. For hit detection I need to figure out if there is an intersection between a projtile and a Sprite (player or enemy). My issue is that Ellipse2D's intersect function (that takes a position a width and height) creates a Rectangle out of the arguments. In its description it advises using Area for high precision and I was hoping it had an intersect function for any shape but that also casts its argument to a Rectangle.
Here's the jist of my Sprite object:
public class Sprite {
protected float worldX;
protected float worldY;
protected float drawX;
protected float drawY;
protected int width;
protected int height;
protected Image image;
...
}
In essence I'm storing their x and y coordinates as well as their width and height.(drawX and drawY are only used for rendering)
Is there a build-in method (preferably in Swing) to intersect Ellipses with other shapes (specifically other Ellipses and Rectangles) or is there no better option then implementing these by hand?
With a simple modification to the answer form Detecting collision of two sprites that can rotate
You can end up with something like...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Ellipse2D rect01;
private Rectangle rect02;
private int angle = 0;
public TestPane() {
rect01 = new Ellipse2D.Double(0, 0, 200, 50);
rect02 = new Rectangle(0, 0, 100, 100);
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angle++;
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 250);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
AffineTransform at = new AffineTransform();
int center = width / 2;
int x = center + (center - rect01.getBounds().width) / 2;
int y = (height - rect01.getBounds().height) / 2;
at.translate(x, y);
at.rotate(Math.toRadians(angle), rect01.getBounds().width / 2, rect01.getBounds().height / 2);
GeneralPath path1 = new GeneralPath();
path1.append(rect01.getPathIterator(at), true);
g2d.fill(path1);
g2d.setColor(Color.BLUE);
g2d.draw(path1.getBounds());
at = new AffineTransform();
x = (center - rect02.width) / 2;
y = (height - rect02.height) / 2;
at.translate(x, y);
at.rotate(Math.toRadians(-angle), rect02.width / 2, rect02.height / 2);
GeneralPath path2 = new GeneralPath();
path2.append(rect02.getPathIterator(at), true);
g2d.fill(path2);
g2d.setColor(Color.BLUE);
g2d.draw(path2.getBounds());
Area a1 = new Area(path1);
Area a2 = new Area(path2);
a2.intersect(a1);
if (!a2.isEmpty()) {
g2d.setColor(Color.RED);
g2d.fill(a2);
}
g2d.dispose();
}
}
}
The code creates a JFrame with a JPanel onto which it draws an image loaded from a file. The objective is to make a rectangular area of the picture, such as for example the red square, appear darker than the rest. I'm assuming this may involve taking a subimage of the image, looping through an array of pixels, scaling them, and then painting that subimage onto the JPanel, but I don't know how to do this using the Java API.
package SpriteEditor_Tests;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ImageTestApp extends JFrame
{
public BufferedImage image;
int x1 = 50;
int x2 = 100;
int y1 = 50;
int y2 = 100;
public static void main (String [] args)
{
new ImageTestApp();
}
public ImageTestApp()
{
setTitle("Image Test App");
try
{
image = ImageIO.read(new File("C:/Users/Paul/Desktop/derp.png"));
}
catch (IOException io)
{
System.out.println("IO caught"); System.exit(0);
}
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(new ImageDisplay());
}
class ImageDisplay extends JPanel
{
public void paintComponent(Graphics g)
{
g.drawImage(image, -100, -100, getWidth(), getHeight(), Color.RED, null);
g.setColor(Color.RED);
g.drawRect(x1, y1, Math.abs(x2 - x1), Math.abs(y2 - y1));
}
}
}
A "simple" solution would be to just create a new instance of Color with the desired alpha applied to it and fill the area you want darkened.
This is great if you have a color you want to use, but when I want to use a predefined color, it's not as simple. Instead, I prefer to use an AlphaComposite as it gives me some advantages.
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage background;
public TestPane() {
try {
background = ImageIO.read(getClass().getResource("/images/background.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
if (background == null) {
return new Dimension(200, 200);
}
return new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background == null) {
return;
}
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(background, 0, 0, this);
int x = (getWidth() - 100) / 2;
int y = (getHeight() - 100) / 2;
Rectangle rect = new Rectangle(x, y, 200, 200);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.fill(rect);
g2d.dispose();
g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.drawRect(x, y, 200, 200);
g2d.dispose();
}
}
}
Now, if want to generate a new image with the are darkened, you can follow the same basic concept, but instead of painting to the components Graphics context, you'd paint directly to the BufferedImages Graphics content. This is the wonderful power of the abstract nature of the Graphics API.
Don't forget, when you override a method, you are obliged to either over take ALL of its responsibilities or call its super implementation.
paintComponent does some basic, but important work and you should make sure to call super.paintComponent before you start performing your custom painting, this will just reduce any possibility of issues.
Darken each pixel individually
Okay, if, instead, you want to darken each pixel in the rectangle individually, this becomes a "little" more complicated, but not hard.
After a lot of time and testing, I settled on using the follow algorithm to darken a given color. This will push the color towards "black" the more you darken it, which some algorithms don't do.
public static Color darken(Color color, double fraction) {
int red = (int) Math.round(Math.max(0, color.getRed() - 255 * fraction));
int green = (int) Math.round(Math.max(0, color.getGreen() - 255 * fraction));
int blue = (int) Math.round(Math.max(0, color.getBlue() - 255 * fraction));
int alpha = color.getAlpha();
return new Color(red, green, blue, alpha);
}
Then, all you have to do is get the the color of the pixel, darken it and reapply.
For this example, I actually use a separate sub image, but you can do it directly to the parent image
BufferedImage subImage = background.getSubimage(x, y, 200, 200);
for (int row = 0; row < subImage.getHeight(); row++) {
for (int col = 0; col < subImage.getWidth(); col++) {
int packedPixel = subImage.getRGB(col, row);
Color color = new Color(packedPixel, true);
color = darken(color, 0.5);
subImage.setRGB(col, row, color.getRGB());
}
}
Now, before someone jumps down my throat, no, this is not the most performant approach, but it gets over messing about with "packed" pixel values (because I can never remember how to unpack those :P) and most of my API code is based around the use of Color anyway
Runnable example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public static Color darken(Color color, double fraction) {
int red = (int) Math.round(Math.max(0, color.getRed() - 255 * fraction));
int green = (int) Math.round(Math.max(0, color.getGreen() - 255 * fraction));
int blue = (int) Math.round(Math.max(0, color.getBlue() - 255 * fraction));
int alpha = color.getAlpha();
return new Color(red, green, blue, alpha);
}
public class TestPane extends JPanel {
private BufferedImage background;
private BufferedImage darkended;
public TestPane() {
try {
background = ImageIO.read(getClass().getResource("/images/background.jpg"));
int x = (background.getWidth() - 100) / 2;
int y = (background.getHeight() - 100) / 2;
BufferedImage subImage = background.getSubimage(x, y, 200, 200);
for (int row = 0; row < subImage.getHeight(); row++) {
for (int col = 0; col < subImage.getWidth(); col++) {
int packedPixel = subImage.getRGB(col, row);
Color color = new Color(packedPixel, true);
color = darken(color, 0.5);
subImage.setRGB(col, row, color.getRGB());
}
}
darkended = subImage;
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
if (background == null) {
return new Dimension(200, 200);
}
return new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background == null) {
return;
}
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(background, 0, 0, this);
int x = (getWidth() - 100) / 2;
int y = (getHeight() - 100) / 2;
g2d.drawImage(darkended, x, y, this);
g2d.setColor(Color.RED);
g2d.drawRect(x, y, 200, 200);
g2d.dispose();
}
}
}
I have the image of a circle of size 256 x 256. The circle can be created by using a function B(i,j). By using a Java producer and consumer model, how can I create a java program to draw the circle?
The code in this image is using the octave code.
Here's the Java Swing GUI I created.
I created (or produced) the image in the CreateImage class. I used the code in your problem image, except I didn't take the square root. Comparing the squares of the numbers was faster.
I drew (or consumed) the image on a JPanel. I'm not going to explain the Swing code in great detail. I wrote what I needed to write to display the image.
Here's the code:
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawImage implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawImage());
}
#Override
public void run() {
Image image = new CreateImage(256, 256, 80).createImage();
JFrame frame = new JFrame("Image of a circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingPanel(256, 256, image));
frame.pack();
frame.setVisible(true);
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1584647402715684757L;
private Image image;
public DrawingPanel(int width, int height, Image image) {
this.image = image;
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public class CreateImage {
private int width;
private int height;
private int radius;
public CreateImage(int width, int height, int radius) {
this.width = width;
this.height = height;
this.radius = radius;
}
public Image createImage() {
int circleRadiusSquared = radius * radius;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
for (int i = 0; i < width; i++) {
int idist = i - width / 2;
for (int j = 0; j < height; j++) {
int jdist = j - height / 2;
int distSquared = idist * idist + jdist * jdist;
if (distSquared < circleRadiusSquared) {
g.setColor(Color.WHITE);
} else {
g.setColor(Color.BLACK);
}
g.drawLine(i, j, i, j);
}
}
g.dispose();
return image;
}
}
}
I Have 3 Questing Regarding My Code
1==> How to remove Selected Shape in my code; when i right click every shape is deleted,
2==> I TOTALLY don't know how to highlight the overlapped are
3==> right now when i click on my JPanel, shape drawn from the point where mouse clicked, where as it should be the in the center of the mouse pointer
Thanks In advance
actually i'm new to Java. this is my code,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import javax.swing.JPanel;
import javax.swing.JButton;
import Delete.Selection;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import java.util.ArrayList;
public class MyPanel extends JPanel {
ArrayList<MyRect> list = new ArrayList<MyRect>();
public MyPanel() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
MyRect r = new MyRect(e.getX(), e.getY());
list.add(r);
repaint();
}
else {
list.clear();
repaint();
}
}
}
);
setPreferredSize(new Dimension(600, 400));
setBackground(Color.CYAN);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for (int i = 0; i < list.size(); i++) {
MyRect r = list.get(i);
g.fillRect(r.x, r.y, r.w, r.h);
}
}
class MyRect {
int x, y, w=100, h=100;
Color c = Color.BLACK;
public MyRect(int x, int y, int w, int h, Color color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c = color;
}
public MyRect(int x, int y) {
this.x = x;
this.y = y;
}
}}
how to highlight the overlapped area
You can use the intersection(...) method of the Rectangle class to get a Rectangle to paint:
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class IntersectingRectangles extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Dimension d = getSize();
int width = d.width * 3 / 4;
int height = d.height * 3 / 4;
Rectangle r1 = new Rectangle(0, 0, width, height);
g2d.setColor( Color.BLUE );
g2d.fill( r1 );
Rectangle r2 = new Rectangle(d.width - width, d.height - height, width, height);
g2d.setColor( Color.YELLOW );
g2d.fill( r2 );
// Specific solution when using Rectangles only
Rectangle r3 = r1.intersection(r2);
g2d.setColor(Color.GREEN);
g2d.fill(r3);
/*
// For a more generic solution using any Shape
Area area = new Area(r1);
area.intersect( new Area(r2) );
g2d.setColor(Color.GREEN);
g2d.fill(area);
*/
g2d.dispose();
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(300, 300);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Intersecting Rectangles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new IntersectingRectangles());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
How to remove Selected Shape in my code; when i right click every shape is deleted,
You need to iterate through the ArrayList containing the Rectangles. Then you can use the Rectangle.contains( yourMousePoint ) method to determine which Rectangle you clicked on. You will need to save the reference to the Rectangle. Then when the loop finishes executing you can remove the Rectangle from the ArrayList.
shape drawn from the point where mouse clicked, where as it should be the in the center of the mouse pointer
Then you need to change the x/y location of the Rectangle. It should be:
int x = mousePoint.x - (width / 2);
int y = mousePoint.y - (height / 2);
where width/height represent the size of the Rectangle you want to draw.
After scouring the internet for days, I found a Question that seemed to address my goal. (I'm trying to draw/edit an individual pixel in an image, and render it.) In said question, The ask-er requested code for a Black BufferedImage. The top Answer provided that code, and appears to work beautifully, until you try to change it to something other than black. Here's the Code:
package myProjectPackage;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.*;
public class Copypasta {
public static JFrame frame;
BufferedImage img;
public static int WIDTH = 500;
public static int HEIGHT = 500;
public Copypasta() {
}
public static void main(String[] a){
Copypasta t=new Copypasta();
frame = new JFrame("WINDOW");
frame.setVisible(true);
t.start();
frame.add(new JLabel(new ImageIcon(t.getImage())));
frame.pack();
// Better to DISPOSE than EXIT
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public Image getImage() {
return img;
}
public void start(){
img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
boolean running=true;
while(running){
BufferStrategy bs=frame.getBufferStrategy();
if(bs==null){
frame.createBufferStrategy(4);
return;
}
for (int i = 0; i < WIDTH * HEIGHT; i++)
pixels[i] = 0; //This is what i've been trying to change.
Graphics g= bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
}
}
I Apologize for the indentation errors. I promise it looks right in the editor.
When set to BufferedImage type ARGB, the black background disappears, causing me to believe that the start function isn't drawing to the Image at all, or the drawn image is not being drawn on the screen. Either way, There is something that I don't understand. If you have the time, I would appreciate some help Identifying What is going wrong, if not an explanation of why. Thank you all,
-Navi.
Link to Original Question: drawing your own buffered image on frame
Several things jump out, the use of BufferStrategy is probably overkill. Unless you absolutely must have control over the paint process, you really don't need it. Using a BufferStrategy also precludes the use of Swing based components which might or might not be an issue.
Trying to manipulate the pixel data directly is probably also a little overkill, instead you can use BufferedImage.setRGB(int, int, int), which allows you to set the color of the pixel at the specified x/y position, for example...
img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
img.setRGB(x, y, Color.RED.getRGB());
}
}
But, even this is a little overkill, the same thing can be achieved by using the provided 2D Graphics API...
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, img.getWidth(), img.getHeight());
g2d.dispose();
Which you will probably find is faster (not just from a coding point of view).
Take a look at:
Performing Custom Painting
Painting in AWT and Swing
2D Graphics
For more details...
Working example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestImage1 {
public static void main(String[] args) {
new TestImage1();
}
public TestImage1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
public TestPane() {
img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
//for (int x = 0; x < img.getWidth(); x++) {
// for (int y = 0; y < img.getHeight(); y++) {
// img.setRGB(x, y, Color.RED.getRGB());
// }
//}
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, img.getWidth(), img.getHeight());
g2d.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(img, 0, 0, this);
g2d.dispose();
}
}
}