Java JFrame - 添加标签图像

问题描述 投票:1回答:1

所以我正在尝试将图像添加到我的JFrame中,我正在使用BorderLayout.PAGE_START,但我不想要灰色背景。有没有办法“删除”该背景或使用其他布局执行此操作并获得我想要的结果?

*我还要在画面底部添加一些图像,所以我也不想在那里有灰色背景。

编辑:这是我的代码:

private JFrame getCreatedFrame(){
    JFrame frame = new JFrame("test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(screenSize);
    frame.setLocationRelativeTo(null);
    JFrame.setDefaultLookAndFeelDecorated(true);

    //set icon image
    String imgName = "images/domino.png";
    URL imageURL = getClass().getResource(imgName);
    if (imageURL != null) {
        icon = new ImageIcon(imageURL);
    }
    frame.setIconImage(icon.getImage());

    //set background image
    imgName = "images/background.jpg";
    imageURL = getClass().getResource(imgName);
    if (imageURL != null) {
        icon = new ImageIcon(imageURL);
    }
    JLabel background=new JLabel(icon);

    frame.add(background);
    return frame;
}

public void start() {
    short version=0,choice=0;
    JFrame frame=getCreatedFrame();

    //set welcome image
    String imgName = "images/welcome.png";
    URL imageURL = getClass().getResource(imgName);
    if (imageURL != null) {
        icon = new ImageIcon(imageURL);
    }
    JLabel welcome=new JLabel(icon);

    frame.add(welcome,BorderLayout.PAGE_START);

    frame.setVisible(true);
}
java image swing jframe jlabel
1个回答
1
投票

建议:

  • 使您的代码更符合OOP标准
  • 考虑为需要由类的方法共享的对象创建非静态字段。要么是这样,要么用同一种方法得到两个图像
  • 我将Swing GUI设置为使JPanel具有灵活性,因为它们可以放在JFrames或JDialogs或JTabbedPanes中,或者在需要时通过CardLayouts交换。您的窗口看起来像是一个介绍性窗口,通常是一个对话框(如JDialog),而不是一个应用程序窗口(例如,JFrame)。
  • 您希望将一个图像显示在另一个图像之上,并且有多种方法可以执行此操作,包括在JPanel qazxsw poi方法覆盖中绘制两个图像。
  • 或者如果你想使用JLabel,只需给底层的JLabel一个布局管理器,比如FlowLayout,然后将较小的JLabel添加到底部。

例如,类似于:

paintComponent(...)
© www.soinside.com 2019 - 2024. All rights reserved.