Window frame covering graphics content

三世轮回 提交于 2019-12-01 20:21:46

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

Verify that WIDTH and HEIGHT are > 0.

Try this:

//add(rs, "center");
add(rs, BorderLayout.CENTER);

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!