Window frame covering graphics content

前端 未结 3 1327
Happy的楠姐
Happy的楠姐 2021-01-21 02:01

this is my first post here and I have a question that seems really nooby, but this has been troubling me for the past hour or so.

I\'m making a simple JFrame with a JPa

相关标签:
3条回答
  • 2021-01-21 02:36

    you may got your answer but for a newbie to java swing i suggest that you should the Net-beans IDE. it graphically adds and lays out the GUI and you dont need to write any hand-written code. It's a great place to start, as stated here:

    http://docs.oracle.com/javase/tutorial/uiswing/learn/index.html

    0 讨论(0)
  • 2021-01-21 02:38

    Here is a sample code that shows how your goal can be achieved. Try to spot the differences with your code to find what is wrong:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class RedSunGame {
    
        private static final int SQUARE_SIZE = 20;
        private JPanel rs;
        private JFrame frame;
    
        private void initUI() {
            frame = new JFrame("Red Sun");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            rs = new JPanel(new BorderLayout()) {
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.setColor(Color.YELLOW);
                    g.fillRect(0, 0, SQUARE_SIZE, SQUARE_SIZE);
                }
    
                @Override
                public Dimension getPreferredSize() {
                    Dimension preferredSize = super.getPreferredSize();
                    // Let's make sure that we have at least our little square size.
                    preferredSize.width = Math.max(preferredSize.width, SQUARE_SIZE);
                    preferredSize.height = Math.max(preferredSize.height, SQUARE_SIZE);
                    return preferredSize;
                }
            };
            frame.add(rs);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    RedSunGame redSunGame = new RedSunGame();
                    redSunGame.initUI();
                }
            });
        }
    }
    
    0 讨论(0)
  • 2021-01-21 02:38

    Verify that WIDTH and HEIGHT are > 0.

    Try this:

    //add(rs, "center");
    add(rs, BorderLayout.CENTER);
    
    0 讨论(0)
提交回复
热议问题