Why are my JPanels not showing color or shapes

后端 未结 2 601
一整个雨季
一整个雨季 2021-01-26 11:04

So whenever I run the application the frame is there however all the colors and rectangles are not. I\'m making 3 different menus each intractable so I need 3 panels within my f

相关标签:
2条回答
  • 2021-01-26 11:17

    You have just a miss typos, you need to add container that you created to the frame like so frame.setContentPane(container); instead of adding a new container. and I just change colors so that you can see each panel :

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Application extends JPanel{
    
        public static void main(String[] args) {
    
            JFrame frame = new JFrame("FrogVibes");
            JPanel container = new JPanel();
            JPanel mainPanel = new JPanel();
            JPanel upgradePanel = new JPanel();
            JPanel frogPanel = new JPanel();
            JButton button = new JButton("button!");
    
            mainPanel.setSize(400,200);
            upgradePanel.setSize(500,690);
            frogPanel.setSize(400,690);
            mainPanel.setBackground(Color.RED);
            upgradePanel.setBackground(Color.BLACK);
            frogPanel.setBackground(Color.BLUE);
            
            upgradePanel.add(button);
    
            container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
            container.add(mainPanel);
            container.add(upgradePanel);
            container.add(frogPanel);
    
            new Application() {
            };
    
            frame.setContentPane(container);
            frame.setSize(1280,700);
            frame.setVisible(true);
            
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
    }
    
    public void Graphics(Graphics g) {
        super.paintComponent(g);
        g.drawRect(0,700,400,100);
        g.drawRect(0, 600,100,150);
    }
    }
    
    0 讨论(0)
  • 2021-01-26 11:34

    You need to create an instance of your Application class and add it to a JFrame:

    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Application extends JPanel{
    
        public static void main(String[] args) {
    
            JFrame frame = new JFrame("FrogVibes");
            JPanel application = new Application();
            frame.add(application);
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawRect(0,700,400,100);
            g.drawRect(0, 600,100,150);
        }
    }
    

    Also, the method must be named paintComponent(), not Graphics(). Now Swing will call paintComponent() when it draws the window.

    0 讨论(0)
提交回复
热议问题