gpt4 book ai didi

java - 添加图像作为 jframe 背景 - 其他 jcomponent 消失

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:17 25 4
gpt4 key购买 nike

我正在尝试添加图像作为 jframe 的背景。但是,当我运行下面的代码时,其余面板不会显示,只显示图像。我需要将图像放在后面,而其余的 jcomponents 显示在前面。另外,图像的大小不会调整为 jframes 大小,但会保持原样。有没有什么办法解决这一问题?为了更容易阅读,我只演示了其中一个带有 jbutton init 的 jpanels。使用的图像是这样的:

http://wallpoper.com/wallpaper/black-background-metal-hole-444015

提前致谢

    public class bcquery extends JPanel implements ActionListener {



public bcquery() {


setLayout(new BorderLayout());

JPanel imagepnl = new JPanel(new BorderLayout());

File file = new File(".jpg");
JLabel labelimg;
try {
labelimg = new JLabel(new ImageIcon(ImageIO.read(file)));
imagepnl.add(labelimg, BorderLayout.CENTER);

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

add(imagepnl, BorderLayout.CENTER);


JPanel mainpanel = new JPanel();
mainpanel.setLayout(new BoxLayout(mainpanel, BoxLayout.PAGE_AXIS));

JButton button1 = new JButton("OK");
JPanel btnpanel = new JPanel(new FlowLayout());
btnpanel.add(button1);

btnpanel.setOpaque(false);
mainpanel.setOpaque(false);

mainpanel.add(btnpanel);
imagepnl.add(mainpanel, BorderLayout.NORTH);
add(imagepnl, BorderLayout.CENTER);



private static void createAndShowGUI() throws IOException {
//Create and set up the window.

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(800, 800);
JFrame.setDefaultLookAndFeelDecorated(true);
//Add content to the window.
frame.add(new bcquery());
frame.setResizable(true);

//Display the window.

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.TRUE);


try {
createAndShowGUI();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub

}
}

最佳答案

the rest of the panels wont show up, only the image.

不正确,因为你将苹果和香蕉混合

  • JFrame 在 API 中实现了 BorderLayout(JPanel 具有 FlowLayout),那么最后将 JComponent 添加到 JFrame 的是 frame.add(new bcquery());

  • (在此代码行之前)将 JFrame.CENTER 添加到 frame.setContentPane(label);

<小时/>
  • 有两种方法

    1. JPanel 放入 JFrame.CENTER (frame.add(myVariable)) 覆盖 paintComponent ,将 Image 添加到 JPanel,(因为在这种情况下 JFrame 不可调整大小)您也可以停止重新修复 JPanel

    2. Icon/ImageIcon 放入 JFrame,为 JLabel 设置 LayoutManager(看起来像 BorderLayout),然后放置其余的 Swing JComponents

    3. 在这两种情况下,您都必须使用 setOpaque(false)JComponent 添加到 JPanel 中,并使用 paintComponent/JLabelIcon/ImageIcon

关于java - 添加图像作为 jframe 背景 - 其他 jcomponent 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20328478/

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