简体   繁体   English

如何在 java swing 中的内容窗格(JPanel)上打印图像

[英]How to print a image on a contentpane(JPanel) in java swing

In the main class Practice extends JFrame , there are three classes UpperPanel , CenterPanel and LowerPanel that extend JPanel .在主要的 class Practice extends JFrame ,共有三个类UpperPanelCenterPanelLowerPanel扩展了JPanel

I'm going to put buttons on UpperPanel and LowerPanel, and put a image on CenterPanel, and print it in one frame.我将在 UpperPanel 和 LowerPanel 上放置按钮,在 CenterPanel 上放置一个图像,然后将其打印在一帧中。 However, when the image prints out, three Panels aren't printed.但是,当图像打印出来时,没有打印三个面板。 and when three Panels print out, the image isn't printed.当三个面板打印出来时,图像没有打印出来。 I think the problem is setContentPane(new ImagePanel());我认为问题是setContentPane(new ImagePanel()); when I enter this code (in CenterPanel ), Only images are printed.当我输入此代码(在CenterPanel中)时,仅打印图像。 The rest of the panels(Upper, Center, Lower) are not output.面板(上、中、下)的 rest 不是 output。 (I have created a separate image output class(ImagePanel extends JPanel) , but It's okay to delete this class. But I want to use paintComponent(Graphics g) . (我已经创建了一个单独的图像 output class(ImagePanel extends JPanel) ,但是删除这个 class 是可以的。但我想使用paintComponent(Graphics g)

I'm sorry for my poor English, and Thank you for reading it please help me我很抱歉我的英语很差,谢谢你阅读它,请帮助我

    import java.awt.Color;

    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    
    public class Practice extends JFrame {
    public int width = 480; 
    public int height = 720;
    
    public Practice() {
        setTitle("20201209");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(null);
        setSize(width,height);  
        c.add(new UpperPanel());
        c.add(new CenterPanel());
        c.add(new LowerPanel());
        setVisible(true);
    }
    
    
    class UpperPanel extends JPanel {
        public UpperPanel() {
        JPanel UpperPanel = new JPanel();
        
        UpperPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 25));
        UpperPanel.setBackground(Color.MAGENTA);
        UpperPanel.setBounds(0, 0, 480, 100);
        getContentPane().add(UpperPanel);
        
        JButton btnEnlarge = new JButton("1");
        btnEnlarge.setFont(new Font("궁서체", Font.PLAIN, 20));
        btnEnlarge.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        UpperPanel.add(btnEnlarge);
        
        JButton btnReduce = new JButton("2");
        btnReduce.setFont(new Font("바탕체", Font.ITALIC, 20));
        btnReduce.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        UpperPanel.add(btnReduce);
        
        JButton btnFit = new JButton("3");
        btnFit.setFont(new Font("돋움체", Font.BOLD, 20));
        btnFit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        UpperPanel.add(btnFit);
        }
    }
    
    class CenterPanel extends JPanel{
        public CenterPanel() {
        JPanel CenterPanel = new JPanel();
        CenterPanel.setLayout(null);
        CenterPanel.setBackground(Color.YELLOW);
        CenterPanel.setBounds(0, 100, 480, 500);
        CenterPanel.setOpaque(true);
        getContentPane().add(CenterPanel);
        
        setContentPane(new ImagePanel()); // when I enter this code, Only images are printed. The rest of the panels(Upper, Center, Lower) are not output
        }
    }
    
    class ImagePanel extends JPanel { //this class is for image printing on CenterPanel
        private ImageIcon icon = new ImageIcon("images/1771211.jpg");
        private Image img = icon.getImage();
        
        public void paintComponent(Graphics g) { //I want to use this code
            super.paintComponent(g);
            g.drawImage(img, 10, 110, this);
        }
    
    }
    
        
    class LowerPanel extends JPanel {
        public LowerPanel() {
            JPanel LowerPanel = new JPanel();
            LowerPanel.setLayout(null);
            LowerPanel.setBackground(Color.BLACK);
            LowerPanel.setBounds(0, 600, 480, 120);
            getContentPane().add(LowerPanel);
            getContentPane().add(new MyButton());
            }
        }
    
    class MyButton extends JLabel{ //this class is for a Button on LowerPanel
        MyButton(){
            JButton btn = new JButton("4");
            btn.setBounds(10, 610, 460, 100);
            btn.setHorizontalAlignment(SwingConstants.CENTER);
            btn.setVerticalAlignment(SwingConstants.CENTER);
            btn.setFont(new Font("돋움체", Font.BOLD, 50)); 
            btn.setBackground(Color.WHITE);
            btn.setForeground(Color.RED);
            btn.setOpaque(true);
            getContentPane().add(btn);
            }
        }
    
    public static void main(String[] args) {
        new Practice();
    }
}
  1. Don't extend JFrame class unnecessarily不要不必要地扩展JFrame class
  2. Don't use a null / AbsoluteLayout rather use an appropriate LayoutManager不要使用null / AbsoluteLayout而是使用适当的LayoutManager
  3. Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you不要在组件上调用setBounds()setSize() ,如果您使用正确的布局管理器,这将为您处理
  4. Call JFrame#pack() before setting the frame to visible在将框架设置为可见之前调用JFrame#pack()
  5. All Swing components should be called on the EDT via SwingUtilities.invokeLater应通过SwingUtilities.invokeLaterEDT上调用所有 Swing 组件

Here is a small example of what you want to achieve这是您要实现的目标的一个小示例

在此处输入图像描述

TestApp.java: TestApp.java:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestApp {

    BufferedImage image;

    public TestApp() {
        createAndShowGui();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TestApp::new);
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame("TestApp");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // load image
        try {
            image = ImageIO.read(new URL("https://i.stack.imgur.com/XNO5e.png"));
        } catch (MalformedURLException ex) {
            Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
        }

        // upper panel
        JPanel upperPanel = new JPanel(); // JPanels use FlowLayout by default
        JButton button1 = new JButton("Button 1");
        JButton button2 = new JButton("Button 2");
        JButton button3 = new JButton("Button 3");
        upperPanel.add(button1);
        upperPanel.add(button2);
        upperPanel.add(button3);

        // center panel
        JPanel centerPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, 0, 0, this);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(image.getWidth(), image.getHeight());
            }

        };

        // lower panel
        JPanel lowerPanel = new JPanel();
        JButton button4 = new JButton("Button 4");
        JButton button5 = new JButton("Button 5");
        JButton button6 = new JButton("Button 6");
        lowerPanel.add(button4);
        lowerPanel.add(button5);
        lowerPanel.add(button6);

        frame.add(upperPanel, BorderLayout.NORTH); // JFrame uses BorderLayout by default
        frame.add(centerPanel, BorderLayout.CENTER);
        frame.add(lowerPanel, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM