【问题标题】:draw objects on JPanel placed within JTabbedPane在 JTabbedPane 内的 JPanel 上绘制对象
【发布时间】:2014-05-04 14:39:01
【问题描述】:

过去两天我一直在尝试在我的JPanel 上绘制对象。当我试图在JPanel 上绘制对象时,代码正在运行,而它没有放在JTabbedPane 中。但现在对我来说很忙。请帮助我。

MouseMotionListener注册JPanel

panel[i].addMouseMotionListener(this);

将面板添加到JTabbedPane

tp.addTab("Tab1",panel[i]);

mouseDragged事件代码如下

public void mouseDragged(MouseEvent e) {
   x = e.getX();
   y = e.getY();
   repaint();
}

鼠标释放事件

public void mouseReleased(MouseEvent e) {
    x1 = e.getX();
    y1 = e.getY();
    repaint();
}

paint 函数(必须自动调用)有以下几行

public void paint( Graphics g )
{
  super.paint(g); 
  // I even tried to add the following line but it didn't work too
  /// g=panel[tp.getSelectedIndex()].getGraphics();
  Graphics2D gtd=(Graphics2D) g;
  gtd.fillOval(x, y, x1-x, y1-y); //x1-x: For width of Oval; y1-y: for height
}

【问题讨论】:

标签: java swing graphics mouselistener


【解决方案1】:

x1 和 y1 将始终等于 x 和 y,因为鼠标释放总是发生在(或非常接近)最近鼠标拖动的位置。这意味着你的椭圆总是宽度为零,高度为零。

如果您的目标是创建一个与用户拖动区域大小相同的椭圆,则必须保存 mousePressed 事件的位置。然后,您应该在 mouseDragged 中更新对角(在您的情况下为 x1 和 y1)。

您不应在 mouseReleased 事件中更新任何坐标。相反,您应该保留一个布尔标志(在私有字段中),指示拖动正在进行中。发生 mousePressed 时设置为 true,发生 mouseReleased 时设置为 false。您的 mouseDragged 方法应该只在设置该标志时更新椭圆的坐标。

【讨论】:

  • 我还添加了 mousePrssed 事件。对不起,我错过了那个代码。 public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY();重绘();但它也没有用。我刚刚创建了另一个从 JPanel 扩展的类并复制了相同的代码,它在那里工作。感谢您抽出时间回答我..:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2021-09-10
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
相关资源
最近更新 更多