gpt4 book ai didi

Java:在 JFrame 上添加背景图像

转载 作者:行者123 更新时间:2023-11-30 08:09:31 25 4
gpt4 key购买 nike

我正在制作一个 gui 程序,一切正常,但在框架中添加背景图像,因此我采用 jpanel 私有(private)变量。此外,我在 src 中添加图像,即

但如何使用这个 jpanel 变量在框架中添加背景图像。
代码:

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);



}

}

主要方法:

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);
}


}

最佳答案

您已将布局设置为 null,这会产生问题。每当我们将布局设为 null 时,我们都必须为其设置边界。

按照这个方法:

  1. 首先复制背景图片并粘贴到代码的 src 中

  2. 将布局设置为 borderlayout,如下所示:

    setLayout(new BorderLayout());

  3. 现在添加此代码:

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

注意:在此处添加您的图像名称“image.jpg”

关于Java:在 JFrame 上添加背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30597000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com