Image reading error - java

I am trying to make an image writer that will read a template image and then write text on it, then create a new image with the new text. For some reason I am getting errors when my code seems fine to me. Here is the code below:
public class GUI extends JFrame{
private JPanel p1 = new JPanel();//Puts tiles in, and organizes them for you
private JPanel p2 = new JPanel();//Holds trash tiles
JLabel ll = new JLabel();
//private JPanel p3 = new JPanel();//Holds trash tiles
public GUI(){
this.setTitle("Tile Game");
this.setSize(600,600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try {
createTile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.add(ll);
}
public void createTile() throws IOException{
final BufferedImage image = ImageIO.read(getClass().getResource("/src/tile.png"));
//File outPut = new File("saved.png");
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(30f));
g.drawString("Hello World!", 100, 100);
g.dispose();
ImageIO.write(image, "png", new File("/src/test2.png"));
final BufferedImage image2 = ImageIO.read(new File("/src/test2.png"));
ImageIcon icon1 = new ImageIcon(image2);
ll.setIcon(icon1);
p1.add(ll); }
}
When I run the code above, I end up getting theses errors:
GUI.<init>() line: 36
Start.main(String[]) line: 7
I don't understand why I am also asked to debug the GUI constructor...It all seems to work perfectly fine to me.

your image location is not suitable! (ignore the other classes, it's just a test project ^^)
make an folder in your eclipse project BUT NOT IN YOUR SOURCE dir (!!!) and then refer to the image like this:
Image img1 = Toolkit.getDefaultToolkit().getImage("img/index.png");

Related

Gif no long animated after replacing with JLabel's setIcon method

I am still very new to Java and programming in general. I am trying to display a GIF using Swing and the following code:
JPanel contentPane;
JLabel imageLabel = new JLabel();
public FrostyCanvas(String imageName) {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
contentPane = (JPanel) getContentPane();
contentPane.setLayout(new BorderLayout());
setSize(new Dimension(1600, 900));
setTitle("FrostySpirit v1.1.1 (Beta) - FrostyCanvas");
// add the image label
ImageIcon ii = new ImageIcon(this.getClass().getResource(imageName));
imageLabel.setIcon(ii);
contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);
// display target GIF
this.setLocationRelativeTo(null);
this.setVisible(true);
} catch (Exception exception) {
exception.printStackTrace();
}
}
The method call is the following: (in a different class)
FrostyCanvas FC = new FrostyCanvas("old.gif");
The GIF is animated at this point. I then try to replace the GIF with another one using the following method: (in the same class as ForstyCanvas(String imageName))
public void changeGif(String imageName) throws IOException
{
Icon icon; File file;
file = new File(imageName);
icon = new ImageIcon(ImageIO.read(file));
imageLabel.setIcon(icon);
}
I call the method above in a different class using the following code:
FC.changeGif("D:\\new.gif")
The image is successfully replaced. However, now it only shows the very first frame of new.gif and is no longer animated. How can I make the new GIF move?
The way ImageIO reads the image is creating a static image. The thing to do is to use ImageIcon's loader.
ImageIcon replacement = new ImageIcon(file.toURI().toURL());
That way you are using the same method to construct the image icon as you do with the resource / url.

Converting Jpanel to image using OOP

i have been extensively researching on stackoverflow and other platforms to find out the solution to my problem.I do understand that this is a duplicate question and I totally understand how to convert JPanel to an image based on Java tutorial and other existing post on stackoverflow . However, i'm trying to do it in OOP as i don't want to chunk all my codes within the same method. The result i keep getting is blank and it doesn't show my component in PNG file that ive exported.
File 2, imageOutput.java
public class imageOutput {
public JPanel panel() {
JPanel panel = new JPanel();
JButton btn = new JButton("Click");
JLabel label = new JLabel("Exporting image example");
// -----Add to panel ---
panel.add(label);
panel.add(btn);
panel.setSize(200,200);
btn.addActionListener(new saveImageListener());
return panel;
}
public void frame() {
JFrame frame = new JFrame();
JPanel panel = panel();
// --- Add to frame ---
frame.add(panel);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
class saveImageListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel panel = new imageOutput().panel();
System.out.println("Step 1.. ");
BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
System.out.println("Step 2.. ");
Graphics2D g = image.createGraphics();
panel.printAll(g);
g.dispose();
try {
ImageIO.write(image, "jpg", new File("Paint2.jpg"));
ImageIO.write(image, "png", new File("Paint2.png"));
System.out.println("save");
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
Main class, main.java
public class main{
public static void main(String[] args) {
new imageOutput().frame();
}
}
When i run the program, it results blank as mentioned above. ive been trying to figure out whats the cause of it for the past week and i have not come out with any solution. Has anyone encounter this problem and able to solve ?
BUT when i do it this way , it's perfectly fine. However, it's not oop for me.
public void frame() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Click");
JLabel label = new JLabel("Exporting image example");
//-----Add to panel ---
panel.add(label);
panel.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
panel.printAll(g);
g.dispose();
try {
ImageIO.write(image, "jpg", new File("Paint2.jpg"));
ImageIO.write(image, "png", new File("Paint2.png"));
System.out.println("save");
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
//--- Add to frame ---
frame.add(panel);
frame.setSize(200, 200);
frame.setVisible(true);
//btn.addActionListener(new saveImageListener());
}
Thank you in advance. :)
The problem is a compounding one.
When you call panel() on an instance of imageOutput, it's create another instance of the JPanel, in of itself, this isn't a bad thing, but you need to remember that this new instance has nothing to do with what's on the screen.
In the example you've provided, this means that no layout pass has been done on the component, so all the components are at there default position/size (which is 0x0x0x0), so nothing gets rendered
If you're going to continue creating a new instance of the panel each time you call panel(), then you're going to have to force a layout pass, maybe something like...
JPanel panel = new imageOutput().panel();
panel.setSize(panel.getPreferredSize());
panel.doLayout();
Now, personally, I'd avoid setSize and passing it "magic" numbers and instead use the components preferredSize, but that's me

Swing Intellij GUIDesigner image disappears if placed in JScrollPane

I'm using IntelliJ GUIDesigner.
I have JScrollPanel which contains JPanel.
The idea is that I want to add image to JPanel and to have it load at full size so I can use scrollers to move around and see whole image.
And My problem is that it paints itself alright if I won't change the size of JPanel. But the moment I'm chaning JPanel size it just repaints itself to orginal state (I suppose, IntelliJ hides a lot of code from me).
The code is:
private JPanel panel1;
private JButton button1;
private JPanel drawingPanel;
public MainPanel(){
button1.addActionListener(e -> {
JFileChooser openFile = new JFileChooser();
File chosenFile;
if(openFile.showSaveDialog(panel1) == JFileChooser.APPROVE_OPTION){
chosenFile = openFile.getSelectedFile();
drawImage(chosenFile);
}
});
}
private void drawImage(File file){
try {
BufferedImage image = ImageIO.read(file);
//Works OK if line belowed is removed, but doesn't adjust size so I can't scroll.
drawingPanel.setSize(image.getWidth(), image.getHeight());
Graphics g = drawingPanel.getGraphics();
g.drawImage(image, 0, 0, null);
drawingPanel.paintComponents(g);
}
catch (IOException e) {
e.printStackTrace();
}
}
As I wrote in comment, if the line below the comment is removed then I can load the image and it shows OK but it's too big and I can't see whole image.
If I add the line then it just clears everything and I can't see nothing.
This is important - I need to get the image to show in full size.
How do I do it?
I have JScrollPanel which contains JPanel.
Don't do custom painting.
Just create a JLabel and add the label to the viewport of the scroll pane. Then when you want to change the image you use the setIcon(...) method of the JLabel and the label will automatically repaint itself and scrollbars will appear if necessary.
Maybe you can share your IntelliJ GUI forms? Otherwise it's difficult to reproduce the scrolling problem that you're facing. Without the custom painting and using a label as camickr suggested, you can get scrolling working like this:
public class MainPanel {
private static JFrame frame;
private JPanel panel1;
private JButton button1;
private JPanel drawingPanel;
private JLabel drawingLabel;
public static void main(String[] args) {
MainPanel.test();
}
private static void test() {
frame = new JFrame("");
frame.setBounds(100, 100, 640, 480);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
new MainPanel();
frame.setVisible(true);
}
public MainPanel() {
initializeGui();
button1.addActionListener(e -> {
JFileChooser openFile = new JFileChooser("[...]");
File chosenFile;
if (openFile.showSaveDialog(panel1) == JFileChooser.APPROVE_OPTION) {
chosenFile = openFile.getSelectedFile();
System.out.println("chosenFile: " + chosenFile);
drawImage(chosenFile);
}
});
}
private void initializeGui() {
panel1 = new JPanel(new BorderLayout());
frame.getContentPane().add(panel1);
button1 = new JButton("Open image");
panel1.add(button1, BorderLayout.NORTH);
drawingPanel = new JPanel(new BorderLayout());
panel1.add(drawingPanel, BorderLayout.CENTER);
drawingLabel = new JLabel();
drawingPanel.add(new JScrollPane(drawingLabel), BorderLayout.CENTER);
}
private void drawImage(File file){
try {
BufferedImage image = ImageIO.read(file);
//Works OK if line below is removed, but doesn't adjust size so I can't scroll.
// drawingPanel.setSize(image.getWidth(), image.getHeight());
// Graphics g = drawingPanel.getGraphics();
// g.drawImage(image, 0, 0, null);
// drawingPanel.paintComponents(g);
drawingLabel.setIcon(new ImageIcon(image));
drawingPanel.validate();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Not sure how easy it is to do something similar with the IntelliJ GUI designer; I do prefer IntelliJ (over Eclipse and NetBeans) but I also prefer to create my Java GUIs in code... ;-)

Java BufferedImage not work

public class image {
JFrame pen = new JFrame();
public image () {
pen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pen.setBounds(150, 100, 613, 231);
pen.setVisible(true);
try {
URL url = new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg");
BufferedImage bI = ImageIO.read(url);
ImageIO.write(bI, "jpg", new File("C:\\kibAr.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
I dont have error but dont work why?(I want to use BufferedImage)
And how i can set the window background this graphic?
Sory for my bad english
If by work you mean display the BufferedImage on the frame, then that's because there's no code where you're actually adding it to the frame at all!
You may wish to have a look here for some examples of how to do this.
The quickest way would probably be something along the lines of:
JLabel picLabel = new JLabel(new ImageIcon(bI));
pen.add(picLabel);

Loading animated GIF in JLabel weirdness

I'm trying to load an animated GIF in a JLabel.
While this works:
URL urlsd;
try {
urlsd = new URL("http://pscode.org/media/starzoom-thumb.gif");
ImageIcon imageIcon = new ImageIcon(urlsd);
JLabel progress = new JLabel(imageIcon);
progress.setBounds(5, 20, 66, 66);
contentPane.add(progress);
} catch (MalformedURLException e) {
e.printStackTrace();
}
This, on the other hand, does not, and I don't want to get the GIF from an URL, since I already have the GIF. Result of loading this shows only the first frame of the GIF:
try {
ImageIcon imageIcon = new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("res/images/progress_indicator.gif")));
JLabel progress = new JLabel(imageIcon);
imageIcon.setImageObserver(progress);
progress.setBounds(5, 20, 66, 66);
contentPane.add(progress);
} catch (MalformedURLException e) {
e.printStackTrace();
}
I guess there must be a reason for this, but I cannot find it.
Thanks!
Alex
You can try loading your GIF file like that:
public class Test extends JPanel {
public Test() {
ImageIcon imageIcon =
new ImageIcon(Test.this.getClass().getResource("starzoom-thumb.gif"));
}
}
Or using Test.class.getResouce() if your context is static.
Below code worked for me, it will show the animation instead of first frame of the image.
public class Test extends JPanel {
public Test() {
ImageIcon yyyyIcon = new ImageIcon(xxx.class.getClassLoader().getResource("yyyy.gif"));
connectionLabel.setIcon(yyyy);
}
}
So there is also a simpler way of doing it. The following line is how I did it.
this.setContentPane(new JLabel(new ImageIcon("Path To Gif File")));

Categories

Resources