请参阅此链接以查看图像: https://www.dropbox.com/s/byeah81vg1cck5m/output.jpg 我想要一个如上图所示的面板。 您好,我是Java的初学者,我想知道如何使用滚动条在面板中添加此图标。我试过JLabel,这是我的代码:
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);
答案 0 :(得分:2)
见:
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);
}
});
}
}
<强>输出强>
<强>提示强>
NULL
布局(如@camickr建议的那样)ScrollPane
答案 1 :(得分:1)
不要使用空布局!!!
滚动窗格仅在添加到视口的组件的首选大小大于视口大小时才有效。
您可以直接将标签添加到滚动窗格,您无需先将其添加到面板中。