Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JComponents没有以图片背景显示?_Java_Swing_Jframe_Jpanel_Bufferedimage - Fatal编程技术网

Java JComponents没有以图片背景显示?

Java JComponents没有以图片背景显示?,java,swing,jframe,jpanel,bufferedimage,Java,Swing,Jframe,Jpanel,Bufferedimage,我的组件没有出现。我该如何解决这个问题 代码: 结果: 首先看这个小例子,如果你理解这里发生的事情,一定要告诉我。只有我们会更进一步,慢慢地。试着看一下这个例子,在这个例子中,我向您展示了如何使用JPanel import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import jav

我的组件没有出现。我该如何解决这个问题

代码:

结果:


首先看这个小例子,如果你理解这里发生的事情,一定要告诉我。只有我们会更进一步,慢慢地。试着看一下这个例子,在这个例子中,我向您展示了如何使用
JPanel

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class PaintingExample {

    private CustomPanel contentPane;

    private void displayGUI() {
        JFrame frame = new JFrame("Painting Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new CustomPanel();        

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PaintingExample().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel {

    private BufferedImage image;

    public CustomPanel() {
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
        try {
            /*
             * Since Images are Application Resources,
             * it's always best to access them in the
             * form of a URL, instead of File, as you are doing.
             * Uncomment this below line and watch this answer
             * of mine, as to HOW TO ADD IMAGES TO THE PROJECT
             * http://stackoverflow.com/a/9866659/1057230
             * In order to access images with getClass().getResource(path)
             * here your Directory structure has to be like this
             *                 Project
             *                    |
             *         ------------------------
             *         |                      |
             *        bin                    src
             *         |                      |
             *     ---------             .java files             
             *     |       |                   
             *  package   image(folder)
             *  ( or              |
             *   .class        404error.jpg
             *   files, if
             *   no package
             *   exists.)
             */
            //image = ImageIO.read(
            //      getClass().getResource(
            //              "/image/404error.jpg"));
            image = ImageIO.read(new URL(
                        "http://i.imgur.com/8zgHpH8.jpg"));
        } catch(IOException ioe) {
            System.out.println("Unable to fetch image.");
            ioe.printStackTrace();
        }
    }

    /*
     * Make this one customary habbit,
     * of overriding this method, when
     * you extends a JPanel/JComponent,
     * to define it's Preferred Size.
     * Now in this case we want it to be 
     * as big as the Image itself.
     */
    @Override
    public Dimension getPreferredSize() {
        return (new Dimension(image.getWidth(), image.getHeight()));
    }

    /*
     * This is where the actual Painting
     * Code for the JPanel/JComponent
     * goes. Here we will draw the image.
     * Here the first line super.paintComponent(...),
     * means we want the JPanel to be drawn the usual 
     * Java way first (this usually depends on the opaque
     * property of the said JComponent, if it's true, then
     * it becomes the responsibility on the part of the
     * programmer to fill the content area with a fully
     * opaque color. If it is false, then the programmer
     * is free to leave it untouched. So in order to 
     * overcome the hassle assoicated with this contract,
     * super.paintComponent(g) is used, since it adheres
     * to the rules, and performs the same task, depending
     * upon whether the opaque property is true or false),
     * then later on we will add our image to it, by 
     * writing the other line, g.drawImage(...).
     */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}
编译并运行:
  • 启动命令提示符/terminal/cmd。然后移到指定的位置 通过项目文件夹
  • 现在使用以下命令编译代码:

    C:\Project>javac-d bin src\*.java
  • 现在,通过发出以下命令,移动到bin文件夹:

    C:\Project>cd-bin
  • 进入bin文件夹后,发出以下命令以运行:

    C:\Project\bin>java绘画示例
  • 以下是使用
    JLabel
    作为图像基础时的代码:

    import java.awt.*;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.*;
    
    public class LabelExample {
    
        private JPanel contentPane;
        private JLabel imageLabel;
    
        private void displayGUI() {
            JFrame frame = new JFrame("Label Example");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
            contentPane = new JPanel();
            contentPane.setOpaque(true);
            contentPane.setBorder(
                    BorderFactory.createLineBorder(Color.BLACK, 5));
            //imageLabel = new JLabel(
            //          new ImageIcon(
            //              getClass().getResource(
            //                  "/image/404error.jpg")));
            try {
                imageLabel = new JLabel(new ImageIcon(
                        new URL("http://i.imgur.com/8zgHpH8.jpg")));
            } catch(MalformedURLException mue) {
                System.out.println(
                        "Unable to get Image from"
                            + "the Resource specified.");
                mue.printStackTrace();
            }
            contentPane.add(imageLabel);
            frame.setContentPane(contentPane);  
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String... args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new LabelExample().displayGUI();
                }
            });
        }
    }
    
    以下是上述两个代码的输出:

    window.setVisible(true); should be invoked only after all the components have been added to the frame.
     void logini() throws IOException {
            JFrame window = new JFrame("Login");
            JPanel mainp = new JPanel(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            window.add(mainp);
    
            BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png"));
            JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
            mainp.add(picLabel, c);
    
            c.gridx = 0;
            c.gridy = 1;
            gusername = new JTextField();
            gusername.setText("Username");
            mainp.add(gusername, c);
    
            c.gridx = 0;
            c.gridy = 2;
            gpassword = new JTextField();
            gpassword.setText(" password ");
            mainp.add(gpassword, c);
    
            c.gridx = 0;
            c.gridy = 3;
            JButton login = new JButton("Login");
            mainp.add(login, c);
    
            login.addActionListener(this);
            login.setActionCommand("ok");
    
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setSize(500, 250);
            window.setResizable(false);
            window.setVisible(true);
        }
    

    您编写代码的方式值得怀疑。在实现
    JFrame
    的大小之前,切勿调用
    setVisible(true)
    。也就是说,将组件添加到
    Jframe
    中,然后调用
    setVsibile()
    。请看一看这个相关的@nIcE cOw Ok它成功了,现在所有的对象都不在图片上,而是写在框架的下方。因为您将组件添加到
    JPanel
    ,而图片位于
    JLabel
    上。因此,您可以做的是,在
    JPanel
    上绘制图像,如我所示的上述示例中所述,或者您可以通过设置
    布局将组件添加到
    JLabel
    ,如本文所述+1至少显示了您正在使用的代码,尽管这与作为一个有效的@nIcE cOw还不太接近,但我不理解这些示例,主要是因为我不理解什么在做什么的概念:/很抱歉,你发这封邮件时,回复太晚了,那是晚上:(让我给你加一个小例子,我会一步一步地解释整件事。@TimothyO'Connell:如果你想知道整件事的更多信息,请一定要告诉我:-)
    window.setVisible(true); should be invoked only after all the components have been added to the frame.
     void logini() throws IOException {
            JFrame window = new JFrame("Login");
            JPanel mainp = new JPanel(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            window.add(mainp);
    
            BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png"));
            JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
            mainp.add(picLabel, c);
    
            c.gridx = 0;
            c.gridy = 1;
            gusername = new JTextField();
            gusername.setText("Username");
            mainp.add(gusername, c);
    
            c.gridx = 0;
            c.gridy = 2;
            gpassword = new JTextField();
            gpassword.setText(" password ");
            mainp.add(gpassword, c);
    
            c.gridx = 0;
            c.gridy = 3;
            JButton login = new JButton("Login");
            mainp.add(login, c);
    
            login.addActionListener(this);
            login.setActionCommand("ok");
    
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setSize(500, 250);
            window.setResizable(false);
            window.setVisible(true);
        }