سؤال

Making a full screen checkers game for learning/practicing drawings/swing in java but can't get it to draw on the upper portion of the screen (position [0,0] is about 20px below the top of my screen.)

Here's code for an example (I'm just using alt+F4 to exit for now)

public class Game extends JFrame{
        //get resolution
        public static GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        public static final int mWidth = gd.getDisplayMode().getWidth();
        public static final int mHeight = gd.getDisplayMode().getHeight();  

    public static void main(String[] a) {

        //create game window
        JFrame window = new JFrame();
        Board board = new Board();

        gd.setFullScreenWindow(window);

        window.setSize(mWidth, mHeight);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.setVisible(true);
        window.add(board);

        board.repaint();


    }

}

public class Board extends JComponent{

    public void paint(Graphics b){
        b.fillRect(0, 0, Game.mWidth-7, Game.mHeight-29);
        repaint();
    }
}
هل كانت مفيدة؟

المحلول

What you want to do is call:

window.setUndecorated(true);

Per the Frame documentation "A frame may have its native decorations (i.e. Frame and Titlebar) turned off with setUndecorated. This can only be done while the frame is not displayable."

Couple more changes were necessary. Remove the offset values from your Board class.

public class Board extends JComponent{
    public void paint(Graphics b){
        b.setColor(Color.BLUE); // Just to make the color more obvious
        b.fillRect(0, 0, Game.mWidth, Game.mHeight);
        repaint();
    }
}

And make sure you are calling window.setVisible() after adding and repainting the board like this:

public class Game extends JFrame{
        //get resolution
        public static GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        public static final int mWidth = gd.getDisplayMode().getWidth();
        public static final int mHeight = gd.getDisplayMode().getHeight();  

    public static void main(String[] a) {
        //create game window
        JFrame window = new JFrame();
        window.setUndecorated(true);
        Board board = new Board();

        gd.setFullScreenWindow(window);

        window.setSize(mWidth, mHeight);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.add(board);
        board.repaint();

        window.setVisible(true); // This needs to be last
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top