【问题标题】:Java Swing - Background Image Not ShowingJava Swing - 背景图像不显示
【发布时间】:2023-03-14 10:43:01
【问题描述】:

我对 Java 还是很陌生,正在尝试在 Swing 中创建一个程序。除了背景图像不显示外,一切正常。添加背景图像的代码似乎很好(我得到了帮助)。我主要关心的是我放置 BackgroundPanel 类和我调用的类的实例(在 main 中,这是主文档中唯一引用 BackgroundPanel 的地方)。我还为 BackgroundPanel 类本身提供了一个单独的文档(两个文档都粘贴在下面)。

有人可以指导我正确的方向吗?我取消了导入和包装信息,因为它们在这里占用了大量空间。谢谢!

这是我的主要代码:

public class InvitationCard extends JFrame {

private JPanel contentPane;
private JTextField txtMood;
private JPanel panel;
private JTextPane textPaneBody;
private JTextPane textPaneNames;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                InvitationCard frame = new InvitationCard();
                frame.setVisible(true);
                BackgroundPanel BP = new BackgroundPanel();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */

public InvitationCard() {
    setBackground(Color.WHITE);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 637, 490);
    contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GridBagLayout gbl_contentPane = new GridBagLayout();
    gbl_contentPane.columnWidths = new int[] { 0, 0, 0, 0 };
    gbl_contentPane.rowHeights = new int[] { 0, 0, 0, 0, 0, 0 };
    gbl_contentPane.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0 };
    gbl_contentPane.rowWeights = new double[] { 1.0, 0.0, 1.0, 0.0, 0.0, 
Double.MIN_VALUE };
    contentPane.setLayout(gbl_contentPane);

    panel = new JPanel();
    GridBagConstraints gbc_panel = new GridBagConstraints();
    gbc_panel.fill = GridBagConstraints.VERTICAL;
    gbc_panel.anchor = GridBagConstraints.WEST;
    gbc_panel.gridwidth = 2;
    gbc_panel.gridheight = 5;
    gbc_panel.insets = new Insets(0, 0, 0, 5);
    gbc_panel.gridx = 0;
    gbc_panel.gridy = 0;
    contentPane.add(panel, gbc_panel);
    GridBagLayout gbl_panel = new GridBagLayout();
    gbl_panel.columnWidths = new int[] { 130, 0 };
    gbl_panel.rowHeights = new int[] { 26, 0, 0, 0 };
    gbl_panel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
    gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
    panel.setLayout(gbl_panel);

    Font font1 = new Font("Helvetica", Font.BOLD, 12);
    Font font2 = new Font("Courier", Font.BOLD, 12);
    Font font3 = new Font("nouradilla.regular", Font.BOLD, 12);
    Font font4 = new Font("GearedSlab-Bold", Font.PLAIN, 12);

    txtMood = new JTextField();
    GridBagConstraints gbc_txtMood = new GridBagConstraints();
    gbc_txtMood.insets = new Insets(0, 0, 5, 0);
    gbc_txtMood.anchor = GridBagConstraints.NORTHWEST;
    gbc_txtMood.gridx = 0;
    gbc_txtMood.gridy = 1;
    panel.add(txtMood, gbc_txtMood);
    txtMood.setEditable(false);
    txtMood.setText("Mood: ");
    txtMood.setColumns(10);

    JComboBox comboBox = new JComboBox();
    GridBagConstraints gbc_comboBox = new GridBagConstraints();
    gbc_comboBox.gridx = 0;
    gbc_comboBox.gridy = 2;
    panel.add(comboBox, gbc_comboBox);
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // get item from dropdown
            String item = (String) comboBox.getSelectedItem();
            if (item == "Whimsical") {
                textPaneNames.setFont(font1);
                textPaneBody.setFont(font1);
            } else if (item == "Traditional") {
                textPaneNames.setFont(font2);
                textPaneBody.setFont(font2);
            } else if (item == "Modern") {
                textPaneNames.setFont(font3);
                textPaneBody.setFont(font3);

            } else if (item == "Crazy") {
                textPaneNames.setFont(font4);
                textPaneBody.setFont(font4);

            }

        }

    });

    comboBox.setModel(
            new DefaultComboBoxModel(new String[] { "Select", "Whimsical",      
"Traditional", "Modern", "Crazy" }));

    textPaneNames = new JTextPane();
    textPaneNames.setText("FIRST1 LAST1\n&\nFIRST2 LAST2");
    GridBagConstraints gbc_textPaneNames = new GridBagConstraints();
    gbc_textPaneNames.insets = new Insets(0, 0, 5, 0);
    gbc_textPaneNames.fill = GridBagConstraints.HORIZONTAL;
    gbc_textPaneNames.gridx = 3;
    gbc_textPaneNames.gridy = 0;
    contentPane.add(textPaneNames, gbc_textPaneNames);

    textPaneBody = new JTextPane();
    textPaneBody.setText(
            "REQUEST THE HONOR OF YOUR PRESENCE \nAT THEIR WEDDING 
CEREMONY\n\nFRIDAY, JANUARY SECOND\nTWO-THOUSAND AND SEVENTEEN\nSIX-THIRTY IN 
THE EVENING\n\nADDRESS GOES HERE\n903 ADDRESS LANE\nCITY, STATE\n\n\nRECEPTION 
TO FOLLOW");
    GridBagConstraints gbc_textPaneBody = new GridBagConstraints();
    gbc_textPaneBody.anchor = GridBagConstraints.NORTH;
    gbc_textPaneBody.insets = new Insets(0, 0, 5, 0);
    gbc_textPaneBody.fill = GridBagConstraints.HORIZONTAL;
    gbc_textPaneBody.gridx = 3;
    gbc_textPaneBody.gridy = 1;
    contentPane.add(textPaneBody, gbc_textPaneBody);

    // centers the names and body text
    StyledDocument doc = textPaneBody.getStyledDocument();
    StyledDocument doc2 = textPaneNames.getStyledDocument();

    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);

    doc.setParagraphAttributes(0, doc.getLength(), center, false);
    doc2.setParagraphAttributes(0, doc2.getLength(), center, false);
 }

}

//这里是BackgroundPanel.java:

public class BackgroundPanel extends JPanel {

  Image image;
  public BackgroundPanel()
  {
    try
    {
      image = javax.imageio.ImageIO.read(new  
java.net.URL(getClass().getResource("/satin.jpg"), "/satin.jpg"));
    }
    catch (Exception e) { /*handled in paintComponent()*/ }
  }

  @Override
  protected void paintComponent(Graphics g)
  {
    super.paintComponent(g); 
    if (image != null)
      g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
  }

}

【问题讨论】:

  • 你对你创建的BackgroundPanel 什么都不做......至少,将它添加到 GUI 层次结构中!
  • new java.net.URL(getClass().getResource("/satin.jpg"), "/satin.jpg") 图片位于/satin.jpg/satin.jpg?!?我问是因为satin.jpg 是一个奇怪的目录名称..
  • @jean-baptisteyunes 我对 Java 有点陌生。我在 main.js 中添加了一些 BackgroundPanel 信息。我会在“public InvitationCard()”构造函数下添加更多或其他代码吗? (我假设它是一个构造函数)。
  • @AndrewThompson 是的 satin.jpg 是我现在尝试设置为背景的文件。完整目录将是 img/satin/jpg 但我注意到只有图像的名称似乎可以在我的另一个程序中使用。
  • @Jean-BaptisteYunès 好吧,我现在明白了,我必须将信息添加到框架中。谢谢!

标签: java swing class windowbuilder


【解决方案1】:

在你的 main() 中的 BackgroundPanel BP = new BackgroundPanel(); 之后添加这个:

frame.add(BP);

您需要将组件添加到框架中。否则不会调用paint() 等方法。

【讨论】:

  • 谢谢,我会尝试这两件事!
【解决方案2】:

嗯...让我们看看 重写BackgroundPanel,只做一些修改,我应该有这个

public class BackgroundPanel extends JComponent {
    //every code you put in this class
}

如果我是正确的,这应该能让你这样做

setContentPane(new BackgroundPanel());

如果这不起作用,请告诉我,以便我能提供更好的服务。

编辑

再次检查您的代码,我认为这是您必须要做的事情

public InvitationCard(){
    setContentPane(new BackgroundPanel());
    /* then every other code follows,
       except the "setContentPane(contentPane)"
       you can comment that out
    */

    this.add(contentPane);
}

而且你的 BackgroundPanel 类仍然可以是 JPanel 的子类,这样会更好

不再需要frame.add(BP);

由于我现在没有办法运行它,我仍然不知道这是否解决了你的问题......你告诉我

【讨论】:

  • 我在(构造函数?) InvitationCard() 下将它添加到我的代码中,但它只会让一切变灰。我在注释掉“setContentPane(contentPane);”时都试过了虽然它没有被评论。我还添加了“frame.add(BP);”主要的是,没有发生任何事情:-/。如果您还有其他想法,请告诉我。谢谢。
  • 哦,“扩展 JComponent”也是故意的吗?如果我把它从 JPanel 改成 JComponent 会带来很多错误。
  • 不幸的是,背景图像仍然无法正常工作。我什至更改了我认为可能有问题的 BackgroundPanel 类中的一行(image = javax.imageio.ImageIO.read(getClass().getResource("/satin.jpg"));)但图像仍然没有显示。不知道我还缺少什么。
【解决方案3】:

这可能有点太晚了,但我认为您可能需要将 BackgroundPanel Opaque 布尔值设置为 true。

    BackgroundPanel BP = new BackgroundPanel();
    BP.setOpaque(true);

您可能需要对任何想要具有“背景”颜色或图像的区域执行此操作。

【讨论】: