gpt4 book ai didi

java - Java 中的图标 - 如何在面板中添加图标

转载 作者:行者123 更新时间:2023-11-29 05:29:13 31 4
gpt4 key购买 nike

请引用此链接查看图片: 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);

最佳答案

看这个:

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


提示

  1. 不要使用 NULL 布局(正如@camickr 所建议的)
  2. 使用正确的 Layout Manager
  3. 使用此代码我不认为你需要 ScrollPane

关于java - Java 中的图标 - 如何在面板中添加图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21704779/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com