Updating an image in Java Swing shows strange behaviour - java

I want to update an image in Java Swing and tried two different methods of rendering these images.
Define a JLabel and set the icon of it
Override the paintComponent(Graphics g) function in a custom JPanel and call g.drawImage(img, 0, 0, null)
Rendering the first image works as expected in both ways, but if I'm trying to update the image, it doesn't replace but renders one layer above which is a problem, because the images I want to render are semi-transparent, so you can see the others through.
I'm already using the repaint() method.
Method 1
public void setImage(Image img) {
this.backgroundLabel.setIcon(new ImageIcon(img));
this.repaint();
}
Method 2
public void setImage(Image img) {
this.img = img;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
I'm thankful for any tips! <3

The first thing line in paintComponent(Graphics g) should be
super.paintComponent(g);
This clears the panel, does any background painting if necessary, and any other support functions from the overridden paintComponent method. Otherwise, you will keep drawing images over the previous ones without first clearing them.

For anyone in the future with the same problem, here is the answer I came up with.
I didn't repainted the full frame, but only the JPanel.
I had to add
frame.repaint();
in setImage().

Related

Java (re)painting mechanism [duplicate]

In java awt or swing when you want to change painting of some component you usually have to override the method paint(Graphics g) (in awt) or paintComponent(Graphics g) (in swing).
This is usually (maybe allways - I'm not sure) done when you are creating the component for example:
JPanel jPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
//... my implementation of paint, some transfromations, rotation, etc
}
};
Imagine that you have container of components which could for example consists of some JLabels, some JTextFields, some image. Which will be all put on one component.
By container I mean you have some list or map with ids or some similar structure in which are all components you will put on one JFrame.
The question is if I can change the painting method after creating with all of the components which are in this list in the moment when all of them are already created. For example I want do the rotation action (rotate), which is defined in Graphisc2D, with all of them.
So basicaly what I want is that I throught the list of componets I have and say:
"All of you (components) which are in the list will be rotated by some angle". Is that possible? If yes how?
Edit:
This is my not correctly working solution:
graphicalDisplayPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g2d = (Graphics2D) g;
g2d.rotate(Math.PI, anchorx, anchory);
}
#Override
public void paintChildren(Graphics g) {
super.paintChildren(g);
Graphics2D g2d2 = (Graphics2D) g;
g2d2.rotate(Math.PI, anchorx, anchory);
}
};
JFrame jFrame = JFrame();
// ... setting dimension, position, visible etc for JFrame, it works correctly nonrotated
jFrame.setContentPane(graphicalDisplayPanel);
I have not tested this, but it seems like it would work. A JComponent's paint() method calls:
paintComponent(co);
paintBorder(co);
paintChildren(co);
where co is a Graphics object. In theory you create an image, retrieve the graphics object and then pass that into paintChildren(). you will have to call paintComponent() and paintBorder() yourself, if you do this. Then, just rotate the image and draw it into your component. You may have to crop the image or resize your component accordingly for this to work. It might look something like this:
BufferedImage myImage;
#Override
public void paint(Graphics g){
myImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TRANSLUCENT);
//using a transparent BufferedImage might not be efficient in your case
Graphics myGraphics = myImage.getGraphics();
super.paintComponent(g);
super.paintBorder(g);
super.paintChildren(myGraphics);
//rotation code here
// ...
//draw children onto your component
g.drawImage(myImage, 0, 0,getWidth(), getHeight(), null);
}
I hope I didn't make any mistakes, please let me know if this works.
So basicaly what I want is that I throught the list of componets I have and say: "All of you (components) which are in the list will be rotated by some angle".
If you want to rotate panel and therefore all the components on the panel as a single using then you need to do the custom painting in the paintComponent() method.
If you want to rotate, for example, individual images that each have a different angle of rotation then you can again do this in the paintComponent(...) method and change the angle for each component.
Or, in this second case you can use the Rotated Icon class. In this case the Icon is just added to a JLabel. Then you can change the degrees of rotation and repaint the label, so there is no custom painting (except in the Icon itself).

Getting wrong output in adding an image in JFrame

My problem is that when I create or draw an image in JFrame by using
public void paint(Graphics g)
{}
Method I am getting a black screen instead of the image the problem code snippet is
ImageIcon i=new ImageIcon("logo.png);
Image im=i.getImage();
public void paint(Graphics g)
{
g=getGraphics();
}
Please suggest me an alternative method or solution to my problem
Thanks in advance
Would you consider using a JPanel and overriding the paintComponent method? Something like this:
BufferedImage image = ... //i'll leave this blank since there are several ways to get a bufferedimage. I'll leave an eg: ImageIO.read(new File("/path/to/image"));
JPanel pane = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}};
and then adding the panel to your frame. You can do the same with the container in the JFrame. The logic is simillar.

Overlay images Java

I'm trying to overlay a background picture with a .png sample, and I don't know how it works.
I tried to create 2 JPanels, but didn't find out how to overlay them, then I tried to create 2 JLabels and once again, they just stay separated.
Have you any idea ?
Thanks !
You can use one jPanel.Override paint or paintComponent method and draw your picture with graphic object.
public class MyCustomPanel extends JPanel{
private Image img;
public MyCustomPanel(// use constructor to get img or load it directly from below){
//load image
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, this);
}
}
Then you can go to your main class and use this JPanel
MyCustomPanel mcp=new MyCustomPanel(//img path);
mcp.add(new JLabel("Hello"),BorderLayout.CENTER);
add(mcp),BorderLayout.CENTER);
//etc
I hope you understand
Next time post some code if you want to have answr faster and more complex/better suited for your case.

ImageIcons not displayed - JAVA

My problem is that background image covers all ImageIcons I use in my JPanel. For example, in this code snippet, I'm trying to setIcon to one of the labels I have in my Panel. But the background image covers it. How can I fix this? It doesn't matter if I use label.setIcon() outside of paint method or inside of it.
public void paint(Graphics g) {
super.paint(g);
g.drawImage(backgroundImage, 0, 0, this);
label1.setIcon(iconImage);
}
Thanks in advance!
Set the layout of your base panel to BorderLayout
Add a JLabel to the base pane, setting its icon to the background image
Set the layout if the JLabel to what ever you need
Add the remaining components to this label
Try placing the label.seticon outside the overridden method.
Refer to:
How to set JFrame or JPanel Background Image in Eclipse Helios
you can implement it as;
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
OR
public void paint(Graphics g) {
if (img!=null) g.drawImage(img, 0, 0, null);
super.paint(g);
}

JButton Transparency on an BufferedImage

I have a Problem:
I'm rendering a BufferedImage in a JFrame. Then i add a JButton to the same frame.
when i try to make the button transparent, the button becomes transparent, but disregarding its actual position, its always transparent like it is stuck in the top left corner of the frame.
I testet some different methods to make the button transparent, always with the same result.
any ideas?
thanks
public class TestPanel extends JPanel {
public TestPanel(){
JButton foo = new JButton("test");
foo.setBackground(new Color(0, 0, 0, 0));
foo.setBounds(20, 100, 300, 50);
this.add(foo);
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(ImageFactory.getImg(), 0, 0, null); //get a BufferedImage
g2.dispose();
}
}
I see several problems, even if I'm not sure on which of them cause your problem.I try to list them in order:
Your TestPanel doesn't specify a LayoutManager (I hope you are specifying it somewhere else in your code).
You are extending a JPanel without call super paintComponent method (don't use paint). You should do this before anything else in your paintComponent method:
public void paintComponent(Graphics g){
super.paintComponent(g);
}
remove the dispose method call. You must not destroy your graphic object.
EDIT:
this is a problem:
foo.setBounds(20, 100, 300, 50);
you are trying to explicitly set the bounds of your JButton. You shouldn't do that. If you are using a LayoutManager it probably ignore this directive. If you are using a null layout this could be a problem too.
Several problems
it's wrong to override paint, instead override paintComponent
the button has a fully transparent background but returns true for opaque, thus fooling the paint mechanism
it's wrong to dispose the Graphics passed in as parameter
working code (Edit: accidentally removed the transparent color-setting line, fixed)
public TestPanel(){
JButton foo = new JButton("test");
foo.setBackground(new Color(0, 0, 0, 0));
foo.setOpaque(false);
foo.setBorder(BorderFactory.createLineBorder(Color.RED));
this.add(foo);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(ImageFactory.getImg(), 0, 0, null); //get a BufferedImage
// g2.dispose();
}
As others already noted: LayoutManagers are a must in Swing/AWT - not using them makes the ui code brittle and hard to maintain.
setBound() will work only if you have set your layout to null. Your code does not say anything like that.
Now, the default layout manager of JPanel is FlowLayout. By default, this layout manager will arrange your components from left to right then top to bottom.
Now, to make your code work as expected. Add this line inside your constructor: setLayout(null).
But remember, setting the layout to null is a very poor practice.
Also, the points Heisenbug has mentioned are very worthy. Try to follow them.

Categories