Java 如何添加图像作为JPanel背景?
我想使用不同的背景制作四个面板,并使用Java 如何添加图像作为JPanel背景?,java,swing,background,jpanel,border-layout,Java,Swing,Background,Jpanel,Border Layout,我想使用不同的背景制作四个面板,并使用边框布局将它们合并在一起。我使用了JLabel,但我无法向JLabel添加任何组件,因此我需要将其作为背景 我搜索了一些代码,但它只告诉如何在JFrame中添加背景 import javax.swing.*; import java.awt.*; public class LoginPanel extends JFrame{ private ImageIcon top = new ImageIcon("C:/Users/user/Desktop/top.p
边框布局将它们合并在一起。我使用了JLabel
,但我无法向JLabel
添加任何组件,因此我需要将其作为背景
我搜索了一些代码,但它只告诉如何在JFrame
中添加背景
import javax.swing.*;
import java.awt.*;
public class LoginPanel extends JFrame{
private ImageIcon top = new ImageIcon("C:/Users/user/Desktop/top.png");
private ImageIcon mid = new ImageIcon("C:/Users/user/Desktop/mid.png");
private ImageIcon center = new ImageIcon("C:/Users/user/Desktop/center.png");
private ImageIcon bottom = new ImageIcon("C:/Users/user/Desktop/bottom.png");
public LoginPanel(){
JPanel topp = new JPanel();
topp.setLayout(new BorderLayout(0,0));
topp.add(new JLabel(top),BorderLayout.NORTH);
JPanel centerp = new JPanel();
centerp.setLayout(new BorderLayout(0,0));
centerp.add(new JLabel(mid),BorderLayout.NORTH);
centerp.add(new JLabel(center),BorderLayout.SOUTH);
topp.add(new JLabel(bottom),BorderLayout.SOUTH);
topp.add(centerp,BorderLayout.CENTER);
add(topp);
}
public static void main(String[] args) {
LoginPanel frame = new LoginPanel();
frame.setTitle("Test");
frame.setSize(812, 640);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
我将创建一个名为JImagePanel
的新类,然后使用该类:
class JImagePanel extends JComponent {
private static final long serialVersionUID = 1L;
public BufferedImage image;
public JImagePanel(BufferedImage image)
{
this.image = image;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// scale image
BufferedImage before = image;
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);
// center image and draw
Graphics2D g2d = (Graphics2D) g;
int x = (getWidth() - 1 - image.getWidth(this)) / 2;
int y = (getHeight() - 1 - image.getHeight(this)) / 2;
g2d.drawImage(image, x, y, this);
g2d.dispose();
}
}
退房
退房
虽然这个想法很好,但我还是希望在这种情况下做两个改变。1.)由于我使用图像作为背景,因此我将覆盖该方法,以便JComponent
将达到图像的大小。2.paintComponent(…)
方法的访问说明符将保持受保护
,而不是公共
:-)相关示例: