2

你好我有一个小问题。我有JFrame一个JComponent我用来显示图形的。

组件的首选尺寸是 800x600,我JFrameJComponent这样的方式创建(GC作为组件):

public static void main(String[] args) {

  mainframe = new JFrame();
  mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mainframe.add(GC);
  mainframe.pack();
  mainframe.setResizable(false);
  mainframe.setVisible(true);

}

然后我画这样的图形:

public void paintComponent(final Graphics g)
{
    //temp bg
    g.setColor(Color.red);
    g.fillRect(Global.leftborder, 0, 600, 600);

            //code code.....
    }

问题是即使组件的高度为 600 像素,它也会在组件的按钮上留下 10 像素的白色。我意识到这是因为 (0,0) 位于整个窗口的左上角,而不是在组件上。

有没有办法解决这个问题,而不必在每次我画东西时增加 10 像素的高度和宽度?

4

1 回答 1

3

您应该覆盖 componentspaintComponent方法而不是框架。这样翻译应该已经正确进行了。


完整示例:

public class Test {
    public static void main(String[] args) {

        JFrame frame = new JFrame("Test");

        frame.add(new TestComponent());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    static class TestComponent extends JComponent {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.setColor(Color.red);
            g.fillRect(10, 0, 600, 600);
        }
    }
}
于 2012-01-31T07:43:26.517 回答