实现背景图片的第二种方式,重写JPanel,再重写JPanel的paintComponent(Graphics g)方法,JPanel会调用paintComponent画出自身,在这之后我们再将自己需要的背景画出来就实现了添加背景图片的方法
MyFrame.java:
package Back;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MyFrame extends JFrame{
private MyPanel contentPanel;
private JButton button;
private JTextField text;
public MyFrame() {
contentPanel = new MyPanel();
contentPanel.setLayout(new BorderLayout());
button = new JButton("button");
contentPanel.add(button, BorderLayout.NORTH);
text = new JTextField();
contentPanel.add(text, BorderLayout.SOUTH);
addListener();
this.setContentPane(contentPanel);
this.setSize(contentPanel.getWidth(), contentPanel.getHeight());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public void addListener() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("hello, world!" + text.getText());
}
});
}
public static void main(String[] args) {
new MyFrame();
}
}
MyPanel.java
package Back;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyPanel extends JPanel{
private ImageIcon imageIcon;
private int width;
private int height;
public MyPanel() {
imageIcon = new ImageIcon("resource\\冬天3.jpg");
width = imageIcon.getIconWidth();
height = imageIcon.getIconHeight();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//这个只能出现在super.paintComponent(g)方法之后,否则将不会画出背景图片
g.drawImage(imageIcon.getImage(), 0, 0, width, height, null);
}
/**
* 返回面板的宽度
*/
public int getWidth() {
return width;
}
/**
* 返回面板的高度
*/
public int getHeight() {
return height;
}
}