Java Graphics不在底部和右侧绘制

时间:2013-03-01 17:37:35

标签: java swing graphics jpanel paint

为什么这不会呈现底部和右侧。我如何解决它? 有一个小的白色区域,什么都没有画出来?我确信有一个简单的解决办法,但我太傻了。

我已经摆脱了任何不必要的东西,但可能仍然存在一些无用的随机代码。

package test;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JPanel implements Runnable
{
    /**
     * Default serial version
     */
    private static final long serialVersionUID = 1L;


    private static final int WIN_WIDTH = 760;
    private static final int WIN_HEIGHT = 480;

    private boolean running;
    private Thread thread;
    public Graphics g;
    public Graphics2D g2d;
    static final int UPDATE_RATE = 60;
    static final long UPDATE_PERIOD = 1000000000L / UPDATE_RATE;

    static public final int EONWIDTH = 24;
    static public final int EONHEIGHT = 24;

    /**
     * Contains a list of Eon instances by their instance ID.
     */

    ///////////////////////////////////CONSTRUCTER/////////////////////////////
    public Test()
    {
        Dimension size = new Dimension(WIN_WIDTH, WIN_HEIGHT);
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);       
    }

    /**
     * Main java runnable, required
     * @param args Unused, required by default
     */
    public static void main(String[] args)
    {
        Test game = new Test();

        JFrame frame = new JFrame("See guys, It's off centered... - 00.00.10");
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(game, BorderLayout.CENTER);
        frame.setContentPane(panel);
        frame.pack();
        frame.isFocusable();
        frame.setFocusable(true);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        game.g = game.getGraphics();

        game.start(game);
    }


    private void loopUpdate(Test game)
    {
            game.repaint();
    }

    boolean done = true;
    public void paint(Graphics g)
    { 
        System.out.print(g.getClipBounds().width + ", " + g.getClipBounds().height + "\n");
        super.paint(g);
        g.setClip(0,0, WIN_WIDTH, WIN_HEIGHT);
        final Graphics2D g2d = (Graphics2D) g;
        if (done) 
        {
            done=false;

            try
            {

        g2d.fillRect(0, 0, WIN_WIDTH + 100, WIN_HEIGHT + 100);


        } catch (Exception e) {
                e.printStackTrace();
            }
            g.dispose();
            done = true;
    }
    }

    @Override
    public void run()
    {
        loopUpdate(this);
    }
}

This is the output

请。我知道这里的每个人都知道如何解决这个问题所以请有人帮助我。

1 个答案:

答案 0 :(得分:0)

您假设JPanel的大小正好是WIN_WIDTH和WIN_HEIGHT。使用getBounds()而不是常量来获取JPanel的实际实现大小。实际大小由容器的LayoutManager决定,因此如果您绝对需要指定的确切尺寸,可以调查不同的布局管理器或绝对定位。