java实现(1)实现以下窗口,单击显示图像1-图像4按纽分别用不同的方法显示1.jpg-4.jpg对应的图像在左边区域,单击另存为可将当前显示的图像保存为与源文件同目录curimage.jpg文件,单击”刷新清除”可将显示的图像清除。
时间: 2024-02-24 17:57:03 浏览: 21
下面是一个实现上述需求的Java代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ImageDisplay extends JFrame implements ActionListener {
private JLabel imageLabel;
private JButton[] buttons;
private JButton saveButton, refreshButton;
public ImageDisplay() {
setTitle("Image Display");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
// 创建图像标签
imageLabel = new JLabel();
add(imageLabel, BorderLayout.CENTER);
// 创建按钮
buttons = new JButton[4];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("图像" + (i + 1));
buttons[i].setPreferredSize(new Dimension(100, 30));
buttons[i].addActionListener(this);
}
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
for (JButton button : buttons) {
buttonPanel.add(button);
}
add(buttonPanel, BorderLayout.NORTH);
// 创建保存和刷新按钮
saveButton = new JButton("另存为");
saveButton.setPreferredSize(new Dimension(100, 30));
saveButton.addActionListener(this);
refreshButton = new JButton("刷新清除");
refreshButton.setPreferredSize(new Dimension(100, 30));
refreshButton.addActionListener(this);
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
controlPanel.add(saveButton);
controlPanel.add(refreshButton);
add(controlPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveButton) {
// 另存为
try {
BufferedImage image = (BufferedImage) imageLabel.getIcon().getImage();
File outputFile = new File("curimage.jpg");
ImageIO.write(image, "jpg", outputFile);
JOptionPane.showMessageDialog(this, "保存成功!");
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "保存失败:" + ex.getMessage());
}
} else if (e.getSource() == refreshButton) {
// 刷新清除
imageLabel.setIcon(null);
} else {
// 显示图像
String imageName = e.getActionCommand() + ".jpg";
try {
BufferedImage image = ImageIO.read(new File(imageName));
ImageIcon icon = new ImageIcon(image);
imageLabel.setIcon(icon);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "读取文件失败:" + ex.getMessage());
}
}
}
public static void main(String[] args) {
new ImageDisplay();
}
}
```
在这个例子中,我们使用了Swing图形库来创建窗口和组件。其中,`JLabel`组件用于显示图像,`JButton`组件用于实现按钮。我们在窗口的北部放置了4个用于显示不同图像的按钮,并为它们添加了`ActionListener`。当用户单击这些按钮时,我们通过`ImageIO`类读取相应的图像文件,并将它们显示在图像标签中。
在窗口的南部,我们放置了“另存为”和“刷新清除”两个按钮。当用户单击“另存为”按钮时,我们将当前显示的图像保存为`curimage.jpg`文件。当用户单击“刷新清除”按钮时,我们清除图像标签中的图像。注意,在保存图像时,我们使用了`JOptionPane`类来显示保存成功或失败的消息框。
你可以将上述代码复制到Java文件中,并将 `1.jpg` 到 `4.jpg` 放置在项目根目录下。