Reputation: 57
Refer to this link to see the image: https://www.dropbox.com/s/byeah81vg1cck5m/output.jpg I want a panel like the picture above. hello , i am a beginner on Java , i would like to know how is it possible to add this icon within a panel with the scrollbar . I have tried with JLabel, here is my code:
JPanel panel = new JPanel();
panel.setLayout(null);
JScrollPane txtstmtPane = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
ImageIcon icon=new ImageIcon ( "icon/filter.jpg" );
JLabel label = new JLabel();
label.setIcon(icon);
label.setBounds(600, 600, 40, 30);
panel.add(label);
txtstmtPane.setViewportView(panel);
add(txtstmtPane);
Upvotes: 1
Views: 1367
Reputation: 20755
See this:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImagePanel extends JPanel{
private BufferedImage bi;
public ImagePanel() {
try {
bi = ImageIO.read(new File("Your Image Path"));
} catch (IOException ex) {
Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex);
}
final JPanel panel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
g2.dispose();
}
@Override
public Dimension getPreferredSize(){
return new Dimension(bi.getWidth()/2, bi.getHeight()/2);
//return new Dimension(200, 200);
}
};
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ImagePanel imgPanel=new ImagePanel();
JOptionPane.showMessageDialog(
null, imgPanel, "Image Panel", JOptionPane.PLAIN_MESSAGE);
}
});
}
}
Output
Tips
NULL
layout (as @camickr suggested)ScrollPane
Upvotes: 2
Reputation: 324078
Don't use null layouts!!!
A scrollpane will only work when the preferred size of the component added to the viewport is greater than the size of the viewport.
You can just add the label directly to the scrollpane, you don't need to add it to the panel first.
Upvotes: 1