Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner and am trying to program a small game. Unfortunately, I am currently failing to insert an image file on the JFrame.
I got this version from the internet, but unfortunately nothing is displayed when I run it.
import java.awt.*;
import javax.swing.*;
public class Draw extends JLabel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D Graphic1 = (Graphics2D) g;
Graphic1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(0, 191, 255)); // farbe hintergrund einstellen
g.fillRect(0, 0, Var.Framebreite, Var.Framehöhe);
g.setColor(Color.yellow);
Font currentFont = g.getFont(); // schriftgröße von Leben bestimmen
Font newFont = currentFont.deriveFont(currentFont.getSize() * 8F);
g.setFont(newFont);
double b = Math.round(0.125 * Var.Framebreite);
int h = (int) b;
g.drawString("" + Var.LebenSpieler1, Var.Framebreite / 2 - h - 100, 90); // Leben anzeige spieler
// !muss "" + variable geschriebeen
// werden
g.drawString("" + Var.LebenSpieler2, Var.Framebreite / 2 + h, 90); // Lebven anzeigen gegnerspieler
ImageIcon icon = new ImageIcon("C:\\Users\\justi\\OneDrive\\Desktop\\OnlineSchule\\Englisch\\Test.PNG");
JLabel l1 = new JLabel(icon);
JPanel feld = new JPanel();
feld.add(l1);
feld.setBounds(30, 30, 110, 110);
repaint();
}
}
Do not create components in a painting method. A painting method is used to do painting with a Graphics object.
Do not invoke repaint() in a painting method. This will cause a loop. If you need animation use a Swing Timer.
Do not do I/O in a painting method. The method will be called frequently and you want the painting to be efficient.
Read the section from the Swing tutorial on Custom Painting for examples of how to do painting. Download the working code and modify it for your requirments.
To paint an image you use the drawImage(...) method of the Graphics object.
You would read the image in your constructor and keep an instance variable to reference the image.
Related
I'm writing a simple game for studying purposes. Everything goes fine except one little thing...
I cant figure out how to rotate square without this ugly jumping
here a simplified version of my program illustrating an issue, here i use one timer, but in original program i have 2 timers one for handle game state and second for repaint:
public class soQuestion extends JLabel {
double r;
#Override
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.clearRect(0,0, getWidth(), getHeight());
g.translate(getWidth()/2, getHeight()/2);
g.rotate(r);
g.translate(-20, -20);
g.fillRect(0, 0, 40, 40);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
soQuestion question = new soQuestion();
frame.add(question);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new javax.swing.Timer(10, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
r += 0.005;
question.repaint();
}
}).start();
}
}
jumping is more visible if rotation delta values is small, for fast rotated objects is less visible..
all rendering hints i used has no effect
PS: Sorry for my english
PPS: i can provide more details if needed, how it looks in full version:
Thanks for all participants!
It is fully my mistake and inattention. I was copied this code section from some source :
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
And before ask a question here i couldn't saw that i used hint related to text rendering.
Special thanks to mr #Pshemo for suggesting of using this rendering hint:
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
I was know about it before asking, but i'm a human and could not figure out where a mistake for an a hour and asked.
PS: sorry for my english
I'm a new contributor, so if its not the best help, sry but i am trying :)
have you tried a solution where you are using Math.toRadiants() in your g.rotate() function? in this video: Java: Rotating and scaling images
the image rotates without jumping, it's at 6:42 in the video.
So in your solution, it would look like that: g.rotate(Math.toRadiants(r += 0.005));
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?
i have a problem with drawing in my JFrame app. I have these two functions:
Im quite new to such graphics in Java, i was wondering if someone would be kind and help me. I need to add the line on the JLabel called areaImage. I tried using some done code i found here but none worked for me. Is my code usable with some bugs? Or is it completely bad?
Please dont just post a link with some code, Im not skilled enough to understand it and then change it so it fits my app...
This one just makes the window, adds the components:
public void game (int difficulty)
{
getContentPane().removeAll();
areaImage = new JLabel ();
areaImage.setBounds (50,100,650,500);
areaImage.setForeground(Color.WHITE);
areaImage.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
add(areaImage);
paint (100,120,500,500, null);
info = new JLabel (" Write your answer into the text field");
info.setBounds(730,180,250,50);
info.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
info.setFont(new Font ("Arial", Font.PLAIN, 15));
areaImage.setForeground(Color.red);
add(info);
inputField = new JTextField("");
inputField.setBounds(810, 240, 80, 50);
add(inputField);
checkAnswer = new JButton ("Check");
checkAnswer.setBounds(750, 330, 200, 50);
checkAnswer.setContentAreaFilled(false);
checkAnswer.setOpaque(false);
checkAnswer.addActionListener(this);
checkAnswer.setFont (new Font("Arial",Font.PLAIN, 30));
add(checkAnswer);
next = new JButton ("Next");
next.setBounds(750,440,200,50);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(this);
next.setFont (new Font("Arial",Font.PLAIN, 30));
add(next);
end= new JButton ("Exit");
end.setBounds (750,550,200,50);
end.setFont(new Font("Arial", Font.PLAIN, 30));
end.addActionListener(this);
end.setOpaque(false);
end.setContentAreaFilled(false);
add(end);
revalidate();
repaint();
}
This one is the drawing function:
private void paint (int x, int xx, int y, int yy, Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g.drawLine(x,y,xx,yy);
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}
Please dont just post a link with some code, Im not skilled enough to understand it
Well that is how you learn. You can't expect us to debug your code and rewrite it every time you have a little problem. If you are not willing to learn by playing with working examples, then I'm not sure how we can help you.
I need to add the line on the JLabel
Then you need to override the painting code for the JLabel. You should never invoke a painting method directly because the painting will be lost the next time Swing determines the component needs to be repainted.
So start by learning how to do painting properly. There is a working example in the Swing tutorial on Custom Painting. The first example just draws a string on a panel but it will be easy enough for you do just draw a line on the label. It is a single statement you add to the paintComponent() method.
The real question is why are you trying to draw this line on a label? I'm sure there is a better solution if we understand the real requirement. You should not be hardcoding the location/size of the line since you don't know how big the label will be.
I am attempting to draw sprites out of a sprite sheet.
I have the following class
public class GTComponent extends JComponent {
Graphics2D g2;
#Override
public void paintComponent(Graphics g){
g2 = (Graphics2D)g;
}
public void drawSpriteFrame(Image source, int x, int y, int frame) {
int frameX = (frame % 12) * 32;
int frameY = (frame / 12) * 32;
g2.drawImage(source, x, y, x + 32, y + 32,
frameX, frameY, frameX + 32, frameY + 32, this);
}
}
That is created as an object in the main class as so
JFrame f = new JFrame();
GTComponent img = new GTComponent();
f.add(img);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize((int)(i.length * 8.1), (int)(i[0].length * 8.5));
f.setVisible(true);
f.setLocationRelativeTo(null);
BufferedImage test = null;
try {
test = ImageIO.read(new File( /*Image File path*/));
}
catch (IOException e) {
System.out.println("error");
System.exit(0);
}
img.drawSpriteFrame(test, (u * 32 + 1), (z * 32 + 1), c);
The problem im facing is that the following error gets thrown
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
After doing several debugs, setting breakpoints at paintComponent and drawSpriteFrame, i found out that the drawSpriteFrame method gets called before the paintComponent method, thus meaning that g2 = null resulting in that error being thrown.
The question here is what triggers the paintComponent method which allows me to initialise the g2 variable?
You seem to have a broad misconception how drawing in Swing works.
You do not call any rendering methods when you want to. You perform rendering when Swing demands it. When Swing calls paintComponent() thats where you perform all your rendering. The graphics passed to paintComponent should be treated as valid only while you're still in the paintComponent method. What happens to it after the method exits is Swings buisness.
You might want to consult the tutorial on Swing custom painting http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html for example code.
paintComponent() is called automatically from the event dispatch thread. If you want your custom component to be painted as part of the ordinary Swing painting process, you should override paintComponent() to call your drawSpriteFrame() method, not call drawSpriteFrame() directly.
If you want to control the drawing operation yourself, you need to use "active rendering" as described in the Full-Screen Exclusive Mode tutorial -- note that the technique described there also works for windowed applications. Basically you need to ask the window for a Graphics instance (instead of waiting for one to be passed into paintComponent() and then draw to that.
A basic example using double buffering:
// Initial setup
Frame mainFrame = new Frame();
mainFrame.setVisible(true); // you'll also want to set size, location, etc.
mainFrame.createBufferStrategy(2);
BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
//....
// Inside your draw loop (call once for each frame)
Graphics2D g2 = (Graphics2D) bufferStrategy.getDrawGraphics();
g2.drawImage(...) // etc.
g2.dispose();
bufferStrategy.show();
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?