【训练10】自定义缩放
通过在文本框中输入宽度和高度缩放比例(数值是能被10整除的整数),对窗体上显示的图片进行缩放。
/*【训练10】自定义缩放
* 通过在文本框中输入宽度和高度缩放比例(数值是
* 能被10整除的整数),对窗体上显示的图片进行
* 缩放。
* */
package draw;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Graphics;
import java.awt.Image;
public class Xl102 extends JFrame {
private JPanel imgPanel, zoomScalePanel;
private JLabel lbl_height, lbl_heightPercent, lbl_width, lbl_widthPercent;
private JTextField tf_height, tf_width;
private Image img;
private int imgWidth, imgHeight;
private int widthScale, heightScale;
private int newWidth, newHeight;
class DrawPanel extends JPanel {
@Override
public void paint(Graphics g) {
try {
img = ImageIO.read(new File("src/img.jpg"));
}catch(IOException e) {
e.printStackTrace();
}
g.clearRect(0, 0, this.getWidth(), this.getHeight());
imgWidth = img.getWidth(this);
imgHeight = img.getHeight(this);
widthScale = Integer.parseInt(tf_width.getText());
heightScale = Integer.parseInt(tf_height.getText());
newWidth = (int)(imgWidth * widthScale / 100);
newHeight = (int)(imgHeight * heightScale / 100);
g.drawImage(img, 0, 0, newWidth, newHeight, this);
}
}
public Xl102() {
super();
this.setTitle("根据输入的宽、高缩放比例对图片进行修改");
this.setBounds(100, 100, 355, 275);
setDefaultCloseOperation(EXIT_ON_CLOSE);
imgPanel = new DrawPanel();
getContentPane().add(imgPanel, java.awt.BorderLayout.CENTER);
zoomScalePanel = new JPanel();
getContentPane().add(zoomScalePanel, java.awt.BorderLayout.SOUTH);
lbl_height = new JLabel("高度(H):");
zoomScalePanel.add(lbl_height);
tf_height = new JTextField();
tf_height.setText("100");
zoomScalePanel.add(tf_height);
tf_height.setColumns(4);
lbl_heightPercent = new JLabel("%");
zoomScalePanel.add(lbl_heightPercent);
lbl_width = new JLabel("宽度(W):");
zoomScalePanel.add(lbl_width);
tf_width = new JTextField();
tf_width.setText("40");
zoomScalePanel.add(tf_width);
tf_width.setColumns(4);
lbl_widthPercent = new JLabel("%");
zoomScalePanel.add(lbl_widthPercent);
JButton btn_zoom = new JButton("缩放");
zoomScalePanel.add(btn_zoom);
btn_zoom.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent g) {
try {
widthScale = Integer.parseInt(tf_width.getText());
heightScale = Integer.parseInt(tf_height.getText());
}catch(NumberFormatException e) {
JOptionPane.showMessageDialog(null, "请在文本框中输入数字……", "警告", JOptionPane.WARNING_MESSAGE);
return;
}
if(widthScale % 10 != 0 || heightScale % 10 != 0) {
JOptionPane.showMessageDialog(null, "文本框中输入的数值必须是10的倍数……", "警告", JOptionPane.WARNING_MESSAGE);
return;
}
imgPanel.repaint();
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Xl102().setVisible(true);
}
}