【问题标题】:Trouble Figuring Out How To Set Background Image [duplicate]麻烦弄清楚如何设置背景图像[重复]
【发布时间】:2012-12-06 08:34:22
【问题描述】:

可能重复:
How to set an image as a background for Frame in Swing GUI of java?

我无法弄清楚如何在我的窗口上设置背景图像。我不确定我的代码有什么问题。图片名为 Background.jpg
有谁知道我的代码有什么问题以及如何修复它

//apples code  

import javax.swing.JFrame;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;

class  Apples{

public static void main(String[] args) {
  gui go = new gui();
  go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  go.setSize(200,290);
  go.setVisible(true);



 }
}



 //Gui Code

    import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class gui extends JFrame{
     private JButton A;
     private JButton B;
     private JButton C;
     private JButton D;
     private JButton E;
     private JButton F;
     private JButton G;
     private JButton H;
     private JButton I;
     private JButton J;
     private JButton K;
     private JButton L;
     private JButton M;
     private JButton N;
     private JButton O;
     private JButton P;
     private JButton Q;
     private JButton R;
     private JButton S;
     private JButton T;
     private JButton U;
     private JButton V;
     private JButton W;
     private JButton X;
     private JButton Y;
     private JButton Z;

     public gui(){
        super("APUSH ABCs");
        setLayout(new FlowLayout());

        A = new JButton("A");
        add(A);
        B = new JButton("B");
        add(B);
        C = new JButton("C");
        add(C);
        D = new JButton("D");
        add(D);
        E = new JButton("E");
        add(E);
        F = new JButton("F");
        add(F);
        G = new JButton("G");
        add(G);
        H = new JButton("H");
        add(H);
        I = new JButton("I");
        add(I);
        J = new JButton("J");
        add(J);
        K = new JButton("K");
        add(K);
        L = new JButton("L");
        add(L);
        M = new JButton("M");
        add(M);
        N = new JButton("N");
        add(N);
        O = new JButton("O");
        add(O);
        P = new JButton("P");
        add(P);
        Q = new JButton("Q");
        add(Q);
        R = new JButton("R");
        add(R);
        S = new JButton("S");
        add(S);
        T = new JButton("T");
        add(T);
        U = new JButton("U");
        add(U);
        V = new JButton("V");
        add(V);
        W = new JButton("W");
        add(W);
        X = new JButton("X");
        add(X);
        Y = new JButton("Y");
        add(Y);
        Z = new JButton("Z");
        add(Z);

        HandlerClass handler = new HandlerClass();
        A.addActionListener(handler);
        B.addActionListener(handler);
        C.addActionListener(handler);
        D.addActionListener(handler);
        E.addActionListener(handler);
        F.addActionListener(handler);
        G.addActionListener(handler);
        H.addActionListener(handler);
        I.addActionListener(handler);
        J.addActionListener(handler);
        K.addActionListener(handler);
        L.addActionListener(handler);
        M.addActionListener(handler);
        N.addActionListener(handler);
        O.addActionListener(handler);
        P.addActionListener(handler);
        Q.addActionListener(handler);
        R.addActionListener(handler);
        S.addActionListener(handler);
        T.addActionListener(handler);
        U.addActionListener(handler);
        V.addActionListener(handler);
        W.addActionListener(handler);
        X.addActionListener(handler);
        Y.addActionListener(handler);
        Z.addActionListener(handler);
    }
      private class HandlerClass implements ActionListener{
  public void actionPerformed(ActionEvent event){

     Object button = event.getSource();

     if(button == A){
String text = "asaasas ";
  JTextArea textArea = new JTextArea(text);

  textArea.setColumns(30);
  textArea.setLineWrap( true );
  textArea.setWrapStyleWord( true );
  textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
  JOptionPane.showMessageDialog(
   null, textArea, "Appomattox Court House", JOptionPane.PLAIN_MESSAGE);

     }else if(button == B){
     String text = "Duriing the last days of the Civil War, Robert E. Lee had abandoned the Confederate capital of Richmond and city of Petersburg, hoping to escape with the remnants of his Army of Northern Virginia to meet up with additional Confederate forces in North Carolina and resume fighting. Union Forces cut him off and finally the Continental army had to surrender. The Appomattox Courthouse is the locaiton where General Robert E. Lee of the Confederate Army surrendered his approximately 28,000 troops to Ulysses S. Grant and the Union Army on April 9, 1865, ending the American Civil War. ";
  JTextArea textArea = new JTextArea(text);

  textArea.setColumns(30);
  textArea.setLineWrap( true );
  textArea.setWrapStyleWord( true );
  textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
  JOptionPane.showMessageDialog(
   null, textArea, "Appomattox Court House", JOptionPane.PLAIN_MESSAGE);
     } else if(button == C){

String text = "Duriing the last days of the Civil War, Robert E. Lee had abandoned the Confederate capital of Richmond and city of Petersburg, hoping to escape with the remnants of his Army of Northern Virginia to meet up with additional Confederate forces in North Carolina and resume fighting. Union Forces cut him off and finally the Continental army had to surrender. The Appomattox Courthouse is the locaiton where General Robert E. Lee of the Confederate Army surrendered his approximately 28,000 troops to Ulysses S. Grant and the Union Army on April 9, 1865, ending the American Civil War. ";
  JTextArea textArea = new JTextArea(text);

  textArea.setColumns(30);
  textArea.setLineWrap( true );
  textArea.setWrapStyleWord( true );
  textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
  JOptionPane.showMessageDialog(
   null, textArea, "Appomattox Court House", JOptionPane.PLAIN_MESSAGE);     
       }

      }
}

【问题讨论】:

  • 我没有看到您在 GUI 上放置 BackgroundPanel 的位置?什么是图形用户界面?是 JFrame 吗?
  • 试试这个链接。它可以帮助您解决问题。 Link
  • 是的,GUI 是一个 JFrame。我拿了一些我找到的源代码并复制了它和一些东西,以便它适合我的应用程序。我应该把BackgroundPanel放在哪里?我真的很挣扎。这是我的第一个 java 程序。我不确定如何在链接中使用该代码并将其放入我的项目中。我尝试更改所有内容的名称,但仍然有很多错误。

标签: java user-interface background


【解决方案1】:

这...

public void paint(Graphics g)
{
    // Draws the img to the BackgroundPanel.
    g.drawImage(img, 0, 0, null);
}

从来都不是一个好主意。你没有尊重油漆链。绘制链是一组复杂的方法,可以完成很多重要的工作。

一个更好的主意是使用paintComponent

protected void paintComponent(Graphics g)
{
    super.paintComponent(g);
    // Draws the img to the BackgroundPanel.
    g.drawImage(img, 0, 0, null);
}

您将遇到的另一个问题是您没有让组件有机会监视图像的状态。因为您使用的是Toolkit.getDefaultToolkit().createImage("Background.jpg"),所以方法可能会使用后台线程来加载图像。你需要一些方法来告诉组件图像已经完成加载并准备好绘画......

g.drawImage(img, 0, 0, this);

这将让组件监控图像的状态并根据需要自行更新。

Toolkit#createImage 可能不是加载图像的最佳选择。如果无法加载图片,该方法不会抛出异常。

最好使用ImageIO#read。这不仅会在类无法加载图像时抛出异常,而且保证返回一个完全限定的图像(即,它会阻塞直到图像被实际加载)。

您还没有告诉我们Background.jpg 的位置。图片是否为嵌入式资源。如果图像只是一个文件(在应用程序的执行上下文中),那么您尝试加载文件就可以了,如果它是嵌入式资源(包含在应用程序 Jar 中),那么您需要使用 Class#getResource 代替...

img = ImageIO.read(getClass().getResource("/Background.jpg"));

您没有为BackgroundPanel 指定首选大小。某些布局管理器将无法按照您预期的方式布局此容器。

public Dimension getPreferredSize() {
    return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(this), img.getHeight(this));
}

另外,正如已经开始提到的,不要忘记将面板添加到您的 UI ;)

更新示例

我还注意到您似乎在混合 Swing 和 AWT 组件,这绝不是一个好主意,如果可以避免,那就这样做(Panel 是 AWT/重量级组件)。

public class Apples {

    public static void main(String[] args) {
        new Apples();
    }

    public Apples() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new BackgroundPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class BackgroundPanel extends JPanel {

        Image img;

        public BackgroundPanel() {
            try {
                img = ImageIO.read(getClass().getResource("/Background.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Draws the img to the BackgroundPanel.
            if (img != null) {
                g.drawImage(img, 0, 0, null);
            }
        }

        public Dimension getPreferredSize() {
            return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(this), img.getHeight(this));
        }
    }
}

【讨论】:

  • 好的,我用你给我的代码更新了程序(也更新了我的第一篇文章,所以你可以看到它),但我仍然遇到很多错误。我绝对觉得我没有把你给我的新代码放在正确的位置。对不起。我应该知道这些东西,但我只是想为我的英语项目做这个,而且我以前从未真正做过 guis(以前的机器人编程经验)。在我的 gui 类中如何以及在何处添加面板?
  • 更新了工作示例
  • 非常感谢您写这篇文章!对此,我真的非常感激!尝试发布该代码时,我遇到了一些问题。我在上面发布了我的 GUI 代码,但无论如何,当我将光标放在按钮上时,按钮的背景会淡出。当您使用我的 Gui Code 进行尝试时,您会明白我的意思。此外,您发布的程序必须与消息框的尺寸搞砸了,因为现在它垂直拉伸并且关闭时的退出不再出现。将 gui 代码与您制作的程序一起运行,您就会明白我的意思了。
  • 帧被水平拉伸,因为这是它的首选尺寸(JFrame#pack 将帧打包到其内容的首选尺寸)。不确定“按钮的背景淡出”是什么意思 - 这可能是一个外观问题。消息对话框可能被拉伸的主要原因是因为我选择覆盖getPreferredSize方法并返回背景图像的大小
  • 哦,好的,谢谢。我现在不在我的程序中,但是我可以通过设置尺寸而不是使用包来解决这个问题吗?另外,当您尝试该程序(使用 gui)时,您的背景图像是否有效?我的没有,因为我相信我的路错了。我会告诉你我做了什么。我从 Google 下载了图像并将其保存在我的桌面上。我将名称更改为背景。我的文件路径不应该是 C:/Users/John/Desktop/Background.jpg 吗?当我尝试仅使用 /Background.jpg 时,它也不起作用
猜你喜欢
  • 2011-01-09
  • 2011-09-02
  • 2020-09-18
  • 2016-10-04
  • 2014-07-01
  • 2014-07-22
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多