我正在尝试制作一个带有图像和2个按钮(即放大和缩小)的程序,该按钮将放大和缩小图像。 我正在尝试使用JLabel添加图像,但无法这样做。 我尝试使用ImageIcon创建图标,并在JLabel方法setIcon()中使用它,但图像未显示。我还提到了StackOverflow上的一些代码,但是它们都不适合我。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Car extends JFrame
{
JButton zoomIn, zoomOut;
JLabel img;
String url = "C:\\Users\\Misomaniac\\eclipse-workspace\\Chegg\\Desert.jpeg"; // url of image
public Car() {
super("Car"); // title bar text
setLayout(null);
zoomIn = new JButton("Zoom in");
zoomIn.setBounds(150, 250, 100, 30); // location in Frame
add(zoomIn);
zoomOut = new JButton("Zoom out");
zoomOut.setBounds(280,250,100,30); // location in Frame
add(zoomOut);
img = new JLabel();
ImageIcon icon = new ImageIcon(url);
img.setIcon(icon);
img.setBounds(200, 50, 300, 200); // location in Frame
add(img);
zoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// image will zoom in when this button is clicked
}
});
setVisible(true);
setSize(550,400); // size of window
setLocation(100,150); // location of window on monitor
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Car();
}
}