如何将图像添加到面板

时间:2017-02-24 11:51:19

标签: java swing

编辑//我的问题比另一个简单,所以请在这里回答。另一个问题看起来太复杂了,我无法理解。

我想将图像添加到面板,但不确定它是如何完成的。我不想在设计页面上这样做,因为我没有设计我的面板我只编写它来显示。那么有谁知道我需要添加哪些代码才能显示图像?我在哪里保存图像以便包含它。这是我到目前为止所做的代码

JFrame frame = new JFrame("JButton");

frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
JPanel panel = new JPanel();
frame.add(panel);

JButton button = new JButton("London"); 
panel.add(button); 

JLabel label = new JLabel("Click", JLabel.CENTER);

3 个答案:

答案 0 :(得分:0)

{
  NODE_ENV: "development"
}

答案 1 :(得分:0)

您需要做的就是,

  1. 读取图像文件。
  2. 借助Graphics对象将图像绘制到背景中。
  3. 只需使用以下代码替换JPanel panel = new JPanel();

             JPanel panel = new JPanel() {
                 @Override
                 protected void paintComponent(Graphics g) {
                     Image image = null;
                     try {
                         image = ImageIO.read(new URL("https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"));
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                     super.paintComponent(g);
                     g.drawImage(image, 0, 0, null);
                 }
             };
    

答案 2 :(得分:0)

好的,有两种方法可以添加图片:

  1. 通过覆盖JPanel#paintComponent(...)方法使用自定义绘画。

  2. 使用JLabel显示图片并将其应用于各种layout managers以获得所需的图片。

  3. 我将在代码中扩展如何使用第一种方式和一些注释,最初的想法是在this answer中给出的,所以一定要给作者提供信用。

    您需要:

    • 创建自定义JPanel对象
    • 创建一个扩展JPanel
    • 的类

    在任何情况下,您都需要覆盖paintComponent(...)方法。

    稍后,在paintComponent()方法中,您需要使用Graphics#drawImage(...)方法绘制图像。这将使JPanel将图像绘制为背景。

    之后,您应该覆盖JPanel的{​​{3}}方法,这样您就可以拨打getPreferredSize(),这会将JFrame的尺寸调整为首选尺寸(这是所有组件可见的最小尺寸。)

    完成此操作后,您可以像以往一样轻松添加组件:

    panel.add(...);
    

    第二种方法是让JLabel充当容器,您可以在其中添加更多组件(就像在JPanel中一样)(如{{3}所示}})

    这样做的方法是:

    • 使用JLabel
    • 创建ImageIcon
    • 设置其布局管理器
    • 向其添加组件

    根据您选择的那个,您会有一些差异:

    • 使用自定义绘画选项,您需要注意容器的首选大小,但您可以更好地控制组件。但是,图像将填充窗口上的所有可用空间。
    • 使用JLabel选项,您只需拨打pack()上的JFrame即可调整图片大小,但如果您的图片太大,则JFrame会同样的大小。如果您将窗口调整为更短,则图像将被裁剪,如果您使窗口变大,则显示“白色”空间。

    这是图像的样子,左边是自定义绘画的2个选项,右边是标签方法。起初他们看起来都一样......

    JFrame#pack()

    但是......如果我们调整窗口大小,这就是我们得到的:

    this answer enter image description here

    我更喜欢自定义绘画方法,但这取决于您的需求和喜欢。

    产生上述输出的代码是:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class JPanelWithBackgroundImageExample {
    
        private JFrame frame; //Our window
        private JPanel panel; //The panel where we're going to draw the background image
        private Image image;
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new JPanelWithBackgroundImageExample().createAndShowGui();
                }
            });
        }
    
        public void createAndShowGui() {
            frame = new JFrame(getClass().getSimpleName());
    
            try {
                image = ImageIO.read(new URL("https://i.stack.imgur.com/XZ4V5.jpg")); //We read the image from the Internet
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            panel = new JPanel() { //We need to open the curly braces so we can change the default behavior of the JPanel
                /* 
                 * This method is the one that paints the background, by default it paints it with gray color,
                 * so, we need to tell it to draw an image instead. (This method belongs to JPanel already, so we need to add
                 * "@Override" before it, so the compiler knows we're overriding it
                 */
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g); //Never forget this line or you could break the paint chain
    
                    /* 
                     * This method belongs to the Graphics class and draws an image, this is what we want the JPanel to draw as our background
                     * The parameters are: the image to be drawn, the starting position (x, y) coords, the width and height and the observer
                     */
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
                }
    
                /* 
                 * This method is part of the JPanel, we're overriding it's preferred size and return the size we want
                 */
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(300, 200);
                }
            };
    
            JLabel label = new JLabel(new ImageIcon(image)); //We create a JLabel that will act as a container for our components
    
            panel.setBorder(BorderFactory.createLineBorder(Color.WHITE)); //We create a border just for visibility of both ways
            label.setBorder(BorderFactory.createLineBorder(Color.WHITE)); //We create a border just for visibility of both ways
    
            label.setLayout(new BoxLayout(label, BoxLayout.PAGE_AXIS)); //We set the layout manager for the label
    
            label.add(new JLabel("I'm a label inside a label")); //We add a new label to our label (that is acting as a container)
            label.add(new JButton("I'm a button inside a label")); //We add a button to our label (that is acting as a container)
    
            //You can add your components to the panel, as you always do it
            panel.add(new JButton("HEY! I'm a button!")); //We add a button to our jpanel
            panel.add(new JLabel("Click the button next to me! :D")); //We add a label to our jpanel
    
            frame.add(panel, BorderLayout.WEST); //We add the pane which has a size of 300 x 200 to the left part of our JFrame
            frame.add(label, BorderLayout.EAST); //We add the label (which acts as a container / jpanel) to the right part of our JFrame
            frame.pack(); //We pack the frame, so it takes its preferred size (and as we only added a single component to it (the JPanel)
                            //As the panel has a size of 300 x 200, the frame will also have this size
            frame.setVisible(true); //We set the visibility of the frame
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

    现在,作为一般提示,通过更改main()方法将您的计划放在enter image description here上,如下所示:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Your constructor here
            }
        });
    }
    

    现在,在评论中回答你的问题:

      除了图像之外,一切都有效,因为我没有那个图像。所以我从谷歌复制了一个图像网址并将其粘贴,但它没有出现?我该怎么办

    好吧,我认为您从链接的答案中获取了代码并更改了这一行:

    frame.setContentPane(new JLabel(new ImageIcon("C:/Users/Frakcool/workspace/StackOverflowProjects/src/test/Air.jpg")));
    

    对于这样的事情:

    frame.setContentPane(new JLabel(new ImageIcon("https://i.stack.imgur.com/XZ4V5.jpg")));
    

    那么在这种情况下,很明显代码不会那样工作,Swing不知道如何解释String中的http,但是enter image description here类会这样做,因此,你应该改变上面这样的行:

    frame.setContentPane(new JLabel(new ImageIcon(new URL("https://i.stack.imgur.com/XZ4V5.jpg"))));
    

    导入:

    import java.net.URL;
    

    在你的班上。

    我希望这有助于您了解代码的工作原理,如果没有,那么,我认为您需要付出更多努力来理解它。