java如何在鼠标点击处画圆_Java如何在鼠标单击上绘制矩形

小编典典

这是一个相对简单的概念(没有冒犯性)。

首先,请勿将代码与JApplet和混合使用JFrame。如果您想在这两种媒介中使用您的应用程序,请将逻辑分成一个单独的

组件(如JPanel),您可以轻松地将其添加到其中。您真的不应该将顶级容器添加到另一个顶级容器(在框架中添加小程序)-太麻烦了。

请避免改写paint顶层容器的方法(如JApplet),而改用自定义组件(如JPanel)并改写它的paintComponent方法。

在您的示例中,您应该打电话super.paint而不是super.paintComponents。paint做重要的工作,您不想跳过

它-但您应该使用JComponent#paintComponent

MouseListener应当添加到您对管理鼠标事件感兴趣的组件中。因为clicked从不添加到任何容器,所以

它将永远不会收到鼠标事件。

Take a look at

PFNOx.png

public class SimplePaint03 {

public static void main(String[] args) {

new SimplePaint03();

}

public SimplePaint03() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (Exception ex) {

}

JFrame frame = new JFrame("Test");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(new PaintPane());

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

});

}

public class PaintPane extends JPanel {

private List grid;

private List fill;

public PaintPane() {

grid = new ArrayList<>(5);

fill = new ArrayList<>(5);

addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

for (Shape shape : grid) {

if (shape.contains(e.getPoint())) {

if (fill.contains(shape)) {

fill.remove(shape);

} else {

fill.add(shape);

}

}

}

repaint();

}

});

int colWidth = 200 / 50;

int rowHeight = 200 / 50;

for (int row = 0; row < 50; row++) {

for (int col = 0; col < 50; col++) {

grid.add(new Rectangle(colWidth * col, rowHeight * row, colWidth, rowHeight));

}

}

}

@Override

public Dimension getPreferredSize() {

return new Dimension(200, 200);

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.RED);

for (Shape cell : fill) {

g2d.fill(cell);

}

g2d.setColor(Color.BLACK);

for (Shape cell : grid) {

g2d.draw(cell);

}

}

}

}

Additional

Information from one paint cycle to another is not maintained. You are

required to repaint the component exactly the way you want it to appear. This

means you will need to maintain a list of click points that can be repainted

at any time.

2020-09-18

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值