我在Swing中编写了一个Java程序来显示帧中的图像。但它没有用。
我是否必须在Netbeans中添加图像包?
这是我的代码:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
//import java.awt.Image.*;
public class Images extends JFrame implements ActionListener {
JButton b;
JLabel l;
Images()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
ImageIcon i=new ImageIcon("stone.jpg");
b=new JButton("Click Me",i);
b.setBackground(Color.yellow);
b.setForeground(Color.red);
b.setFont(new Font("Arial",Font.BOLD,30));
Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED);
b.setBorder(bd);
b.setToolTipText("Buttons");
b.setMnemonic('C');
c.add(b);
b.addActionListener(this);
l=new JLabel();
c.add(l);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
ImageIcon i=new ImageIcon("stone.jpg");
l.setIcon(i);
}
public static void main(String args[])
{
Images d=new Images();
d.setTitle("Hello");
d.setSize(700,700);
d.setVisible(true);
}
}
答案 0 :(得分:1)
如果stone.jpg存储在项目根目录中,则此ImageIcon i=new ImageIcon("stone.jpg");
应该有效。
如果它在别处,你需要修改路径。
例如,如果资源不足,请使用ImageIcon i=new ImageIcon("resources/stone.jpg")
为了确保找到图像,您可以使用System.out.println(i.getIconWidth());
,如果不是,则打印输出-1。
最佳做法是使用here所述的getResource
。