所以我尝试在按下按钮后将图像添加到我的程序中,并在文本字段中输入特定值。我希望图像为空白,直到按下按钮并使用正确的值。我似乎唯一的问题是让照片出现,我知道输出应该正常工作。这是我添加标签的代码。
photo = new JLabel();
photo.setBounds(425, 170, 400, 360);
contentPane.add(photo);
ImageIcon icon = new ImageIcon("AwsomeSauce.jpg");
这里是正确输入值的代码
if (error) {
photo.setIcon(image);
}
现在我仍然很新,所以对我很轻松。
答案 0 :(得分:0)
以下是您的简单示例:
public class Frame extends JFrame {
private JLabel label;
public Frame() {
getContentPane().add(label = new JLabel(),BorderLayout.SOUTH);
JButton b = new JButton("show Icon");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
URL resource = getClass().getResource("/res/3_disc.png");
ImageIcon ico = new ImageIcon(resource);
label.setIcon(ico);
}
});
getContentPane().add(b,BorderLayout.NORTH);
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setTitle("This is a test");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
“/ res / 3_disc.png” - 是我的图标,放在res文件夹中的项目中。