我的JPanel名为panelCrtanje
。
如果按下它,我需要更改cBox状态。
final PadDraw drawPad = new PadDraw();
panelCrtanje.setLayout(new BorderLayout());
panelCrtanje.add(drawPad, BorderLayout.CENTER);
在我使用以下方法将drawPad添加到panelCrtanje之前,它可以工作:
private void panelCrtanjeMousePressed(java.awt.event.MouseEvent evt) {
slikaC.setSelected(true);
}
PadDraw看起来像这样
public PadDraw(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter()){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(graphics2D != null) {
graphics2D.setStroke(new BasicStroke(18F,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
});
}
答案 0 :(得分:1)
您需要正确使用MouseEvent。要使用它,该类需要实现MouseListener。然后你需要为鼠标事件创建一个监听器,如下所示:
panelCrtanje.addMouseListener();
然后使用MouseListener和MotionMouseListener
中需要的这些方法@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
// TODO In HERE do what you want to do
}
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
单击鼠标时:mouseClicked 按住鼠标但不移动鼠标时:mousePressed 释放鼠标时:mouseReleased 当鼠标进入窗口时:mouseEntered 当鼠标离开窗口时:mouseExited
这就是你可以使用mouseListener做不同的事情。
答案 1 :(得分:0)
你应该在MouseListener
上注册一个panelCartanje
,我使用匿名内部类来执行此操作。
panelCrtanje.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e) {
/// cBox state change goes here . . .
}
});
答案 2 :(得分:0)
这是解决方案
MouseAdapter adap = new MouseAdapter(){
public void mousePressed(MouseEvent e) {
slikaC.setSelected(true);
}
};