I am trying to make small program that shows pic on JLabel when user click on Next Button.The Problem is when i click on next button it shows nothing.but if i resize frame it shows all pics from directory. instead of one picture at a time. Please excuse my English. here is my code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.image.BufferedImage;
class test {
public static void main(String args[]) {
frame f = new frame();
f.gui();
f.actions();
}
}
class frame {
BufferedImage file;
File img;
ImageIcon icon;
JLabel image;
JFrame frame;
JPanel panel;
String[] path = { "juice.jpg", "gal.jpg", "truck.jpg", "Drive.jpg" };
JButton next = new JButton("NEXT");
JButton pre = new JButton("PREVOIUS");
JTextField field = new JTextField(10);
static int num = 0;
public void gui() {
frame = new JFrame("pic gallery");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
FlowLayout flow = new FlowLayout();
frame.setLayout(flow);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(next);
panel.add(pre);
panel.add(field);
JLabel piclabel = new JLabel();
frame.getContentPane().add(panel);
}
void actions() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
img = new File(path[num]);
System.out.println(num);
try {
file = ImageIO.read(img);
icon = new ImageIcon(file);
image = new JLabel("", icon, JLabel.CENTER);
image.setVisible(true);
frame.getContentPane().add(image);
} catch (IOException g) {
}
if (num < path.length - 1) {
num++;
field.setText(num + "");
} else {
num = 0;
}
}
});
}
}
Add
frame.revalidate()
andframe.repaint()
afterframe.getContentPane().add(image);
Swing is lazy when it comes to performing updates to the layout hierarchy, which is good thing, imagine adding a few dozen components and having the entire component hierarchy been updated for each one.
So, instead, you need to update the container manually when you've made changes
Then remove the first image, or better yet, instead of creating a new
JLabel
each time, create a singleJLabel
and simply change it'sicon
property, which should invalidate the container automatically