Reputation: 265
I want to show Image on Panel by press Button. I create some code
JButton btnNewButton = new JButton("next");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(i<files1.length){
BufferedImage bi;
try {
bi = ImageIO.read(new File(""+files1[i]));
System.out.println(files1[i]);
JLabel label = new JLabel(new ImageIcon(bi));
panel_1.add(label);
panel_1.repaint();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
System.out.println("end of picture");
i++;
}
});
But after click button image doesn't show.
Upvotes: 1
Views: 563
Reputation: 324108
But after click button image doesn't show.
Looks like you are missing the revalidate(). The basic code when adding a component to a visible GUI is:
panel.add(....);
panel.revalidate(); // to invoke the layout manager
panel.repaint();
Upvotes: 1
Reputation: 43
My Java is not the best. But obviously I would say something like:
if(button.isPressed()) {
Panel.visible;
}
I don't know the exact methods. That's more of a suggestion.
Upvotes: 1
Reputation: 13407
You gave only part of your code in a non-working state. Try to include all the relevant code (in this case include the definition of your panel and i) or strip is down to show the point of what's not working. For me this works:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel label = new JLabel();
JButton button = new JButton("next");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
BufferedImage bi = null;
try {
bi = ImageIO.read(new File("pathtofile"));
} catch (IOException e) {
e.printStackTrace();
}
label.setIcon(new ImageIcon(bi));
}
});
frame.setContentPane(new JPanel());
frame.getContentPane().add(button);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
However, consider that JLabel is not designed to display images a la gallery style. Consider JScrollPane as shown here.
Upvotes: -1