编写一个界面,包括1个按钮和1个JLabel控件,当点击按钮时,将从D盘读取图片cat.jpg,显示在JLabel控件中。
要求:对图片不存在,读取失败等情况做处理
只能写出来显示文字,不知道咋显示图片
package lecture25_2;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class FrameDemo extends JFrame implements ActionListener {
JLabel label1;
JButton btn1;
public FrameDemo(String title) {
super(title);
btn1 = new JButton("显示图片");
label1 = new JLabel();
add(label1);
add(btn1);
btn1.addActionListener(this);
setLayout(new FlowLayout());
setSize(400, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn1) {
label1.setText("1234");
}
// TODO Auto-generated method stub
}
}
public class Test {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("F:\\test.jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FrameDemo frame = new FrameDemo("显示图片");
}
}