【问题标题】:get the x and y offset for the coordinates of a JPanel获取 JPanel 坐标的 x 和 y 偏移量
【发布时间】:2014-01-18 08:48:14
【问题描述】:

如何获取JPanel 坐标的 x 和 y 偏移量?

我正在尝试使用面板所在框架的绘制方法在正方形(面板)中间绘制一个圆圈(我希望圆圈移动到其他正方形,因此我无法在面板上绘制本身)

现在听起来很简单...当我尝试相对于面板的 x 和 y 坐标绘制圆时,似乎存在偏移量,因此我的圆坐标总是从中间偏移一点(也用矩形试了一下)。

但我发现 x 偏移量恒定为 8,但 y 偏移量正在改变,所以我无法修复硬编码...

我的构造函数和绘制方法如下所示:

    public Client() {
    tokens = new int[8][8];
    field = new JPanel[8][8];
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // setResizable(false);
    setBounds(100, 100, WIDTH, HEIGHT);
    setLocationRelativeTo(null);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new GridLayout(8, 8, 0, 0));

    // Draw field
    int row = -1;
    for (int i = 0; i < 64; i++) {
        if (i % 8 == 0)
            row++;
        JPanel panel = new JPanel();
        if ((i + row) % 2 == 0)
            panel.setBackground(Color.BLACK);
        else
            panel.setBackground(Color.WHITE);
        field[row][i % 8] = panel;
        contentPane.add(panel);
    }
}

    private void resizeToken(){
    tokenWidth = field[0][0].getWidth();
    tokenHeight = field[0][0].getHeight();
    xOffset = 8;
    //this one is wrong and just placed as example
    yOffset = 37;

}

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    super.paint(g);
    resizeToken();
    // draw all tokens
    tokens[1][1] = PLAYER_ONE;
    for (int row = 0; row < 8; row++) {
        for (int i = 0; i < 8; i++) {
            if (tokens[row][i] != EMPTY_FIELD) {
                JPanel p = field[row][i];
                if (tokens[row][i] == PLAYER_ONE)
                    g2.setColor(Color.RED);
                else
                    g2.setColor(Color.BLUE);
                g2.fillOval(p.getBounds().x+xOffset, p.getBounds().y-yOffset, tokenWidth, tokenHeight);
            }
        }
    }
    if (movingToken != null)
        g2.fillOval(movingToken.x, movingToken.y, tokenWidth, tokenHeight);
}

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2)您可能需要将侦听器添加到感兴趣的组件,而不是框架。比“可能”更好,请参阅第 1 点。

标签: java swing coordinates paint java-2d


【解决方案1】:

第一件事:

不要使用 JFRAME 的绘制方法。 相反,请使用您尝试绘制圆圈的 jpanel 的paintComponent。

第二件事:

圆基本上是矩形内的一个椭圆,它与 矩形。

所以理论上你只需要画一个矩形就可以画一个覆盖整个面板的圆

Ellipse2D circle = new Ellipse.Double(0,0,panelWidth,panelHeight);

public void paintComponent(Graphics g){
     super.paintComponent(g);//this is very important
      Graphics2D g2 = (Graphics2D) g;
      ....
      Ellipse2D circle = new Ellipse.Double(0,0,panelWidth,panelHeight);
      g2.draw(circle);  
}

【讨论】:

  • 在 contenPane 内绘图有帮助,谢谢。但我没有得到使用 Ellipse2D 对象的优势。
  • 这正是你应该做的......因为 jpanel 是双缓冲的,当你重绘它时它不会闪烁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多