Calling repaint() without loosing previous graphic - java

Im making a small program that needs previous graphics to stay "put" and visible, even after a repaint causes a variable location to change.
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.red);
g.fillOval(mouseLocX,mouseLocY,30,30);
}
this is all i have in the paint class, and i want to change the mouseLocX and mouseLocY values, and call repaint without having the previous location there. Ive done this before, and most people want the opposite, but i forgot how. Im calling repaint from a MouseMotionListener using mouseDragged();

If you want to preserve what's already been painted so that you get a trail of red ovals instead of a single red oval as the mouse moves, then you shouldn't paint directly on the Graphics object provided by paint(). Instead, use a BufferedImage to store your state. Then render the BufferedImage onto the Graphic provided by paint().
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
public void paint(Graphics g) {
super.paint(g);
Graphics imageGraphics = image.getGraphics();
imageGraphics.setColor(Color.red);
imageGraphics.fillOval(mouseLocX,mouseLocY,30,30);
g.drawImage(image, 0, 0, null);
}
The BufferedImage provides the persistence for the previous draw operations.

Related

Java Graphics2D Image Moving

So in this block of code, a 40x40 square can move across a window by calling directional methods, and I'm trying to get a spaceship to appear instead of the square. No matter what I try, it just isn't working.
public void paintComponent (Graphics g) {
ImageIcon wallpaper = new ImageIcon("images/JGalagawallpaper.png");
image = wallpaper.getImage();
g.drawImage(image, 400, 400, null);
ImageIcon ship = new ImageIcon("images/galaga.png");
galaga = ship.getImage();
super.paintComponent(g);
Graphics2D graphic = (Graphics2D) g;
graphic.fill(new Rectangle.Double(x, y, 40, 40));
//graphic.drawImage(galaga, x, y, 40, 40);
}
My question is, how do I get that thing to appear? I already tried tinkering with graphic.drawImage, however that didn't really work out as well as I hoped. That's what the commented out code is.
g.drawImage(image, 400, 400, null);
First you draw the image.
super.paintComponent(g);
Then you invoke the above code which is used to pint the background color of the panel, thus overwriting the image. The above statement should be the first statement of the painting method.
ImageIcon wallpaper = new ImageIcon("images/JGalagawallpaper.png");
A painting method is for painting only. Don't do I/O in the method. The image should be read in the constructor of your class so that it is only read once, not every time the component is repainted.
You also need to look at the coordinates of where you paint the image. Maybe the panel is not that big?
Did you verify that the image was read properly by display its size?

Save a drawn picture on a JPanel in a file [java]

I've made a code to draw on a Jpanel
frame1.add( new JPanel() {
public void paintComponent( Graphics g ) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.white);
g2.fillRect(0, 0, width, height);
//Drawnig Part
});
Every thing is OK
Now My question is how to save what I've drawn on my JPanel in a file a.PNG or any other type
I have spent a lot of time to write the Drawing Part, So it will be helpful if you can suggest a solution by changing the required parts of my code, instead of rewriting the whole code.
I suggest that you buffer your drawing operations with a BufferedImage, like so:
// This should not be done in the draw method, but rather when
// the frame is created. You should also make a new buffer image when
// the frame is resized. `frameWidth` and `frameHeight` are the
// frame's dimensions.
BufferedImage bufferImage = new BufferedImage(frameWidth, frameHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D bufferGraphics = bufferImage.createGraphics();
// In your draw method, do the following steps:
// 1. Clear the buffer:
bufferGraphics.clearRect(0, 0, width, height);
// 2. Draw things to bufferGraphics...
// 3. Copy the buffer:
g2.drawImage(bufferImage, null, 0, 0);
// When you want to save your image presented in the frame, call the following:
ImageIO.write(bufferImage, "png", new File("frameImage.png"));
The Java Tutorial on Creating and Drawing to an Image, along with the ImageIO API reference might be helpful should you require more information.
Have a look at Writing/Saving an Image for more details, but essentially you can do something like...
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
// Draw what ever you want to to the graphics context
g2d.dispose();
ImageIO.write(img, "png", new File("My Awesome Drawing.png"));
If you can't separate the drawing logic from your panel, you could simply use the Graphics context from the BufferedImage to paint the the component with.
Have a look at Exporting a JPanel to an image and Print the whole program layout for examples

Move a rectangle in a JPanel using the keys

I have a class called "DisplayPanel" (which extends JPanel) and I draw a square there that comes from a class called "Square" (which extends JComponent). How to move a rectangle in a JPanel using the keys?
The Square class has the usual painting method:
public void paintComponent(Graphics g) {
Dimension dimension = getSize();
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D) g;
g.setColor(Color.black);
graphics2D.fill(squarishThing);
}
And the "squarishThing" is a normal rectangle:
Rectangle squarishThing = new Rectangle (0, 0, 50, 50);
The thing is: Unlike "game libraries", trying to do such a thing "manually" is quite confusing. I don't know where the "while loop" goes. I tried to put a KeyListener in the DisplayPanel and I failed miserably to update the rectangle. There's no loop, and I can't repaint the rectangle because the method paintComponent takes that unpleasant argument. OBS: Everytime I try to insert a loop, the software crashes dramatically, so I gave up of doing so.
What can I do to repaint the object according to inputs?
can't repaint the rectangle because the method paintComponent takes that unpleasant argument.
Never ever call paintComponent, instead use repaint().
Using KeyBindings simply update "squarishThing" to the appropriate value, then call repaint().

I am having problems setting graphics2D

I am making a simple game where there are two rectangles drawn on the screen and with user input from the keyboard arrow keys one of the rectangles (the player) will move. I have made a Main class and a Play class which consists of all my game code, this code includes methods such as init(), update() and render(), the init() deals with all the initial conditions, the update() deals with the movement and key inputs from the input and the render() method deals with drawing the stuff onto the screen such as the background and rectangles.
The problem I am having is drawing my rectangles (which are set up with my variables) on my screen by putting them in my render class, my method is set up with Graphics and I have been told I require Graphics2D so I am attempting to change my graphics to Graphics2D so that I can draw my rectangles.
Here are my Rectangles which have been set up with my variables at the top of my ode:
Rectangle rectOne = new Rectangle(shiftX, shiftY,90,90);
Rectangle rectTwo = new Rectangle(500 + buckyPositionX, 330 + buckyPositionY, 210, 150);
and here is my render method where I am trying to draw my rectangles using the graphics2D:
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
if(rectOne.intersects(rectTwo)){
g.drawString("Intersect", 100, 100);}
if(g instanceof Graphics2D){//error: Incompatible conditional operand type Graphics and Graphics2D
Graphics2D g2 = (Graphics2D)g;}//cannot cast from Graphics to Graphics2D
((Graphics2D)g).fill(rectOne);//cannot cast from Graphics to Graphics2D
((Graphics2D)g).fill(rectTwo);//cannot cast from Graphics to Graphics2D
}
The comments next to my code shows the errors that are appearing when I try to use this code. If any more code or information is required from my Play class please tell me and I will post it.

Jlabel with Image Fade Out Strange Effect

Hope this question could emphasize more about the fading out effect of Jlabel (swing).
Certainly, yes... I already follow some guide and some answers given from This Link Thread, but mine is quite a bit different. It's not just only A text inside the JLabel, there's an image i put on.
I proceed to follow on the Thread Located out of stackoverflow. And yet, it gives me a fade out effect. But there's horrible thing occured; the white background.
How to solve this out?
I share the interface here...
The First screenshot taken here is the earlier phase when the fade out have not occured yet. While,
The Second screenshot taken here is the unwanted result i mentioned.
Tobe honest, I used the Trident Library to do animatiing;
So, whenever the user click over the image it will execute this code;
Timeline tm = new Timeline(jll_btnProceed);
tm.addPropertyToInterpolate("intensity", 1.0f, 0.0f);
tm.setDuration(1000);
tm.play();
and... the JLabel itself, I used to override it using this source code;
/**
*
* #author Gumuruh
*/
public class JLabelFader extends JLabel {
private float intensity = 1.0f;
public void setIntensity(float intensity) {
this.intensity = intensity;
this.setOpaque(false);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
final Composite oldComposite = g2.getComposite();
g2.setComposite(AlphaComposite.SrcOver);
final Color c = getBackground();
final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (255 * (1.0f - intensity)));
g2.setColor(color);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setComposite(oldComposite);
}
}
My hand and my head can't stop for making this trully solved. Thus I tried to follow up some example from the Java Filthy Rich Client ebook and then applying the source code given below, but first I need to COMMENT the protected void paint(Graphic g) method written above, and simply adding this source code;
private BufferedImage buttonImage = null;
public void paint(Graphics g) {
// Create an image for the button graphics if necessary
if (buttonImage == null || buttonImage.getWidth() != getWidth()
|| buttonImage.getHeight() != getHeight()) {
buttonImage = getGraphicsConfiguration().
createCompatibleImage(getWidth(), getHeight());
}
Graphics gButton = buttonImage.getGraphics();
gButton.setClip(g.getClip());
// Have the superclass render the button for us
super.paint(gButton);
// Make the graphics object sent to this paint() method translucent
Graphics2D g2d = (Graphics2D) g;
AlphaComposite newComposite =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, intensity);
g2d.setComposite(newComposite);
// Copy the button's image to the destination graphics, translucently
g2d.drawImage(buttonImage, 0, 0, null);
}
in which at the end... giving me nice fade out effect. But At first, it gave me the 2nd horrible effect which is BLACK BACKGROUND rendered first. Can't believe me?? Okay, Here is First screen shot AFTER applying code from ebook. and here is the nice fade out effect result.
If there's somebody telling me;
"YOUR PNG IS NOT TRANSPARENT!".
Please, dont say like that. Because, I followed the creation of PNG inside the Photoshop nicely using this Tut.
Now, My head's spinned, but my heart laughed and can't handle it over. OMG. Geeezzz....!
And the New Stories begun...
* UPDATED FROM HERE AND BELOW *
Ehm, depply thank you very much to our friend called... MKorbel,
from his thread given at this link. Providing a clear example of fading out effect the Swing JButton and I tried to implement it into my JLabel, and violaaa...!!
IT works.
Let's give a big clap for MKorbel. :D
SO anyway, how could I fix the earlier code? Pretty simple, just COMMENT the Paint() method, and use again the paintComponent() method and it should be overriden with the new source code below;
#Override
public void paintComponent(java.awt.Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, intensity));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
g2.dispose();
}
Now the JLabel become easy to be changed with its intensity -variable.
Fading out and Fading in is accomplished.
Okay. Now everything seems "OKAY". BUt hold a moment, there's something strangely occured again here. Have you noticed it? Hmmm....
I tried to give a Mouse Event (Hover On) into the JLabel that we override the paintComponent() method discussed earlier.With this line of code;
myJLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Logically, it should change the Cursor when Hover ON. But, Here comes another strange effect. (Really sorry, but this is stil the continue of the main case). The strange effect now is the Mouse Cursor can't be changed when we Hover On the Jlabel. It still can't change the Cursor. Seems the paintComponent() method effecting the way Cursor react. Is that true?

Categories