How to display an image to JPanel or to JLabel using the BufferedImage?
I load an Image using FileChooser and I need to display what I've loaded.
I don't extend my class to any container.
Override paintComponents(g) paintComponent(g) method of JPanel or JLabel and draw image in it. Something like follow:
JPanel panel = new JPanel(){
#Override
public void paintComponent(Graphics g) {
BufferedImage image = null; // get your buffered image.
Graphics2D graphics2d = (Graphics2D) g;
graphics2d.drawImage(image, 0, 0, null);
super.paintComponents(g);
}
};
Same thing for JLabel. Or in another way:
BufferedImage image = null; // get your buffered image.
ImageIcon icon = new ImageIcon((Image)image);
JLabel label = new JLabel();
label.setIcon(icon);
As you are saying that you are loading image from FileChooser it can be done in following
way:
ImageIcon icon = new ImageIcon(
fileChooser.getCurrentDirectory().toString()
+"/"+fileChooser.getSelectedFile().getName());
Now you can use ImageIcon in JLabel or add it in JPanel.
Above code is sample code and not tested so not necessary to run without error. You might need to change it as per your need.
Related
we just started using java. we want to use an image from the internet and make it the background of our Jpanel. can somebody help us please? we tried using the code below :
public class Achtergrond3 extends JPanel {
private ImageIcon img;
private JLabel label;
public Achtergrond3() {
img = new ImageIcon("res/textures/newbackground.jpg");
label= new JLabel(img);
this.add(label);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
}
}
I think this link will help you...
Simplest way to set image as JPanel background
It talks about how to set image as JPanel background
I need to create an application with interface scaling. I have a button with icon inside and jpanel, that hold this button. The problem is that when scale is on - an icon is blurred and to fix this, I use downscaling in paintComponent. When system scale is on, I have normal image, as a result. But JPanel still have a scaled size. I tryed to override JPanel paintComponent too, but as a result I had too small buttons, because downscale on button and donwscale on JPanel work togeather. I can't use scale only from JPanel, when I click a button, it take a scaled size and image blurred again.
This is a simple example.
And the code is:
public class Test{
public static void main(String[] args) throws Exception{
System.setProperty("sun.java2d.uiScale", "1.5");
JFrame j = new JFrame();
Image img = ImageIO.read(new File("D:\\1.png"));
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setPreferredSize(new Dimension(300, 150));
j.setVisible(true);
j.setLocationRelativeTo(null);
j.setLayout(new BorderLayout());
img = img.getScaledInstance((int) (60 * 1.5),(int) (60 * 1.5),Image.SCALE_DEFAULT);
JToggleButton tb = new JToggleButton(){
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.scale(0.67,0.67);
super.paintComponent(g2);
}
};
tb.setIcon(new ImageIcon(img));
JToggleButton tb2 = new JToggleButton(){
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.scale(0.67,0.67);
super.paintComponent(g2);
}
};
tb2.setIcon(new ImageIcon(img));
JPanel jPanel = new JPanel(){
};
jPanel.setLayout(new GridLayout(1,1));
jPanel.add(tb);
jPanel.setBackground(Color.RED);
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(jPanel);
j.setContentPane(content);
j.pack();
}
}
I use java10.
Thank you.
You render your UI with scaling factor of 1.5: all UI including icons and images is scaled so that it displays correctly on a High DPI display. If image does not scale, it would be too small for a higher DPI setting.
If your application supports High DPI displays, i.e. UI scaling, you should provide images of different resolutions. See MultiResolutionImage in Java 9.
You can find sample code in this answer to a related question.
I need to reduce the size of a JCheckBox item, which has no text. So far I tried to override the methods getPreferredSize() and getMaximumSize(). Also setting the Font size or the size of the JCheckBox itself doesn't evoke any changes. Is there a way to achieve this?
If you're talking about an Icon that is added to the JCheckBox, then best would be to create a new Icon from a new Image that is a resize of the original image. You can do this with a Image by calling the yourImage.getScaledInstance(...); method. Once you get the new image, create a new ImageIcon(newImage) and use it with your JCheckBox.
e.g.
Image oldImage = oldIcon.getImage();
Image newImage = oldImage.getScaledInstance(newWidth, newHeight,
Image.SCALE_DEFAULT);
Icon newIcon = new ImageIcon(newImage);
checkBox.setIcon(newIcon);
getPreferredSize and getMaximumSize only return the values assigned to preferredSize and maximumSize, respectively, for the JCheckBox object. If you want to change these values, use setPreferredSize and setMaximumSize instead:
jCheckBox.setPreferredSize(new Dimension(100, 300));
and/or:
jCheckBox.setMaximumSize(new Dimension(200, 600));
You can override the paint function like this:
final JCheckBox cb = new JCheckBox("",autoChangeTab) {
#Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.scale(.9, .9);
super.paint(g);
}
};
I want to re-size my ImageIcon to fit my jLabel. Using the answer from this post Scale the ImageIcon automatically to label size I am using
public jfrmHome() {
initComponents();
this.setLocationRelativeTo(null);
ImageIcon iconimage;
iconimage = new ImageIcon(getClass().getResource("/org/me/musiconweb/resources/Music-icon.png"));
BufferedImage bi = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
iconimage.paintIcon(null, g, 0,0);
g.dispose();
BufferedImage resizedimage=resize(bi,jlblPicture.getWidth(), jlblPicture.getHeight());
ImageIcon resizedicon=new ImageIcon(resizedimage);
jlblPicture.setIcon(resizedicon);
}
This re-sizes the Image but i have a little problem. The background of the image becomes black instead of white that it was
This
turns to
Please what am i doing wrong?
That image has transparency. So change BufferedImage.TYPE_INT_RGB to BufferedImage.TYPE_INT_ARGB
It is not obvious at SO on a white BG, but try this SSCCE & it becomes more clear..
import java.net.URL;
import javax.swing.*;
class ShowImage {
public static void main(String[] args) throws Exception {
final URL url = new URL("http://i.stack.imgur.com/1yeUy.png");
Runnable r = new Runnable() {
#Override
public void run() {
JLabel l = new JLabel(new ImageIcon(url));
JOptionPane.showMessageDialog(null, l);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Your image has a transparent background. Therefore it shows as black when drawn on a newly created opaque image. Use
g.setColor(Color.WHITE);
g.fillRect(0, 0, jlblPicture.getWidth(), jlblPicture.getHeight());
if you want a white background. For transparent background, draw on TYPE_INT_ARGB image instead.
Try out these codes
ImageIcon icon1 = new
ImageIcon(getClass().getResource("\\image\\"+f1.getName()));
BufferedImage bi = new
BufferedImage(icon1.getIconWidth(),icon1.getIconHeight()
, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
icon1.paintIcon(null, g, 0,0);
g.dispose();`
//image resizing code...............>
ImageIcon resizedicon=new ImageIcon(bi.getScaledInstance(imglbl.getWidth(),
imglbl.getHeight(),1 ));
imglbl.setBackground(new java.awt.Color(255, 255, 255));
imglbl.setIcon(resizedicon);
I have a JFrame which has 4 different Panels. The Black box on right in the image below is the Image Panel. I am trying to write a Class that will allow me to load an image into any Panel within any other class in my program.
http://sdrv.ms/14TEq2T
LoadImage.java
package sf;
import java.awt.*;
import java.awt.image.*;
import javax.swing.ImageIcon;
public class LoadImage extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public LoadImage(String filename) {
try {
System.out.println(filename);
img = new ImgUtils().scaleImage(380, 360, filename);
} catch (Exception e) {
System.out.println("File not found");
}
}
class ImgUtils {
public BufferedImage scaleImage(int WIDTH, int HEIGHT, String filename) {
BufferedImage bi = null;
try {
ImageIcon ii = new ImageIcon(filename);
bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(ii.getImage(), 0, 0, WIDTH, HEIGHT, null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bi;
}
}
}
Code that I use to load in the Image in my other Classes.
private void getProductImage() {
try {
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
String newPath = decodedPath.replace("build/classes/", "src/productImages/");
productImagePanel.add(new LoadImage(newPath + imageCode + ".jpg"));
revalidate();
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
The 'imageCode' is the code that is retrieved from database once the Window is visible and I have checked the Path to images several times.
The LoadImage.java works on its own and load the images if a 'main runnable' method is added to it, however I can't seem to display the image in the panel I want. Please advice on how to fix my problem, any help is appreciated!
Your problem could very well be you're trying to load the image as a component to the JPanel. Problems include:
the preferredSize of the Component could well be [0, 0], and so it can be trying it's little heart out to display an image but just be too small to do so.
There could be other components already added to the JPanel
The JPanel's layout may not play nice with newly added components.
You shouldn't mix heavy weight (Component) with light weight (most all other non-top level Window Swing components) without a definite need.
I suggest:
Add a JLabel to your image displaying JPanel just once on JPanel creation.
Give your productImagePanel a method that accepts an Image or an ImageIcon and then either creates the ImageIcon from the Image or uses the ImageIcon provided to set the Icon of the JLabel.
Be sure that the JPanel uses a layout that allows the JLabel to display itself fully. The layout manager tutorials can help with this.
Either that or all the image displaying JPanel is for is to show the image and nothing else, get rid of it and instead use a JLabel by itself, and add your Icons directly to it.
Also as an aside: you should be disposing any Graphics and Graphics2D objects that you create (but not any given to you by the JVM). That means that when you're done drawing with g2d in your ImageUtilities, dispose of it.