简体   繁体   English

Java:在JFrame上添加背景图片

[英]Java:Background Image add on JFrame

I'm making a gui program everything going right but add background image in frame so i take jpanel private variable.Also i add image in src which is 我正在做一个gui程序,一切正常,但是在框架中添加了背景图像,所以我将jpanel私有变量也添加到src中,这是

but how to use this jpanel variable to add background image in frame. 但是如何使用此jpanel变量在框架中添加背景图像。
Code: 码:

public class App extends JFrame{

private JPanel panel;
private JTextField field1;
private JTextField print;
private JLabel label;
private JLabel label2;
private JButton button;




public App(){
    super();
getContentPane().setLayout(null);



label = new JLabel("Value");
label.setForeground(Color.RED);
label.setFont(new Font("SansSerif", Font.PLAIN, 18));
label.setBounds(178, 46, 51, 26);
getContentPane().add(label);


label2 = new JLabel("Print");
label2.setForeground(Color.RED);
label2.setFont(new Font("SansSerif", Font.PLAIN, 18));
label2.setBounds(178, 143, 42, 26);


getContentPane().add(label2);






field1 = new JTextField();
field1.setBounds(178, 72, 76, 26);


getContentPane().add(field1);



print = new JTextField();
print.setBounds(178, 181, 77, 26);
getContentPane().add(print);



button = new JButton("Click");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        String w= field1.getText();
        print.setText(w);



    }
});
button.setBounds(178, 219, 77, 26);
getContentPane().add(button);



}

} }

Main Method: 主要方法:

public class Main {

public static void main(String[] args) {



    App object = new App();
    object.setSize(450, 400);   
    object.setDefaultCloseOperation(object.EXIT_ON_CLOSE);
    object.setLocationRelativeTo(null);
    object.setVisible(true);        
       }


}

You have set Layout to null which is making a problem. 您已将Layout设置为null,这会造成问题。 Whenever we make layout null we have to set bounds for it. 每当我们使布局为空时,我们都必须为其设置边界。

Folow this method: 请遵循以下方法:

  1. first of all copy your background image and paste in src of code 首先复制您的背景图片并粘贴代码的src

  2. than set layout to borderlayout like this: 而不是像这样将布局设置为borderlayout:

    setLayout(new BorderLayout()); setLayout(new BorderLayout());

  3. now add this code: 现在添加此代码:

    setContentPane(new JLabel new ImageIcon(getClass().getResource("image.jpg")))); setContentPane(new JLabel new ImageIcon(getClass()。getResource(“ image.jpg”)))));

Note: add your image name here "image.jpg" 注意:在此处添加您的图片名称“ image.jpg”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM