📄 imagepanel.java~11~
字号:
package chat;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.awt.image.*;/* the class is for painting background image to a panel */public class ImagePanel extends JPanel { private String imageFilename = null; private Image image = null; private Toolkit toolkit = null; public ImagePanel() { super(); toolkit = Toolkit.getDefaultToolkit(); } public ImagePanel(String filename) { super(); toolkit = Toolkit.getDefaultToolkit(); setImageFilename(filename); } public void setImageFilename(String filename) { imageFilename = filename; try { image = toolkit.createImage(imageFilename); setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this))); repaint(); } catch (Exception e) { e.printStackTrace(); imageFilename = null; image = null; } } public void setImage(Image image) { this.image = image; try { setPreferredSize(new Dimension(this.image.getWidth(this), this.image.getHeight(this))); repaint(); System.out.println(image.getHeight(this)); } catch (Exception e) { e.printStackTrace(); this.image = null; } } public void clearImage() { image = null; repaint(); } public Dimension getPreferredSize() { if (image == null) return new Dimension(0, 0); else return new Dimension(image.getWidth(this), image.getHeight(this)); } protected void paintComponent(Graphics g) { Insets insets = getInsets(); g.setColor(Color.white); g.fillRect(0, 0, insets.left + getWidth(), insets.top + getHeight()); super.paintComponent(g); if (image != null) { g.drawImage(image, insets.top, insets.left, this); } } public void reloadImage() { if (imageFilename != null) { try { image = toolkit.createImage(imageFilename); repaint(); } catch (Exception e) { imageFilename = null; image = null; } } } public static void main(String[] args){ JFrame frame=new JFrame(); ImagePanel imagePanel=new ImagePanel(); Image image = Toolkit.getDefaultToolkit().getImage("one.jpg"); imagePanel.setImage(image); JButton button=new JButton("ooooooooooooookkkkkkkkkkk"); imagePanel.add(button); frame.getContentPane().add(imagePanel); frame.setVisible(true); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -