1

In the main class Practice extends JFrame, there are three classes UpperPanel, CenterPanel and LowerPanel that extend JPanel.

I'm going to put buttons on UpperPanel and LowerPanel, and put a image on CenterPanel, and print it in one frame. 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()); when I enter this code (in CenterPanel), Only images are printed. The rest of the panels(Upper, Center, Lower) are not 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).

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();
    }
}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
ssing365
  • 23
  • 5

1 Answers1

2
  1. Don't extend JFrame class unnecessarily
  2. Don't use a null/AbsoluteLayout rather use an appropriate LayoutManager
  3. Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you
  4. Call JFrame#pack() before setting the frame to visible
  5. All Swing components should be called on the EDT via SwingUtilities.invokeLater

Here is a small example of what you want to achieve

enter image description here

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);
    }

}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    Great answer, but note re `"D:/test.png"`. If that image is embedded in the answer, it can then be hot-linked from the code in order to allow the example to be run without any changes whatsoever. In case you don't have rights to upload it, there is an alternative as expressed in one of my copy/paste comments.. One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). – Andrew Thompson Dec 10 '20 at 08:39
  • @AndrewThompson ahh great idea I tried to simply use the image link from the website but a few images wouldn't load not sure if somehow they blocked loading from any site but their own etc so I opted to just download and reference it but that's a great idea to post it here on the post and just use the link SO produces to show it. Will update it in a few minutes. Thanks mate. – David Kroukamp Dec 10 '20 at 08:51
  • Thank you very much. I was going to say thank you, but it's too late. It helped me a lot. Please continue to share your great skills. – ssing365 Dec 11 '20 at 08:28
  • @DaivdKroukamp If you have time, please read my new question. Thank you ! – ssing365 Dec 11 '20 at 09:17