我不想要JButton
或类似的东西,我在找出ActionListener
时遇到了麻烦。
如果有人可以告诉我应该在他的代码中添加什么,那么当我点击这些坐标时,它会将我带到下一个状态:
class paint extends JPanel implements ActionListener{
public void MouseInput(MouseEvent m){
int y = m.getY();
int x = m.getX();
if(x >= 250 && x <= 550 && y >= 300 && y <= 400){
}
}
public void actionPerformed(ActionEvent e) {
}
}
答案 0 :(得分:0)
为了让您的Swing组件JPanel
收到有关某些来源事件的通知,在您的情况下,您希望收听鼠标点击;你的组件应该添加一些实现MouseListener
的监听器(这个监听器应该实现MouseListener
接口中声明的方法,但这将是你的自定义逻辑的基础):
public class MyMouseListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent e)
{
// How click event should be handled
}
@Override
public void mousePressed(MouseEvent e)
{
// How press (clicked but not released) event should be handled
}
@Override
public void mouseReleased(MouseEvent e)
{
// How release mouse button event should be handled
}
@Override
public void mouseEntered(MouseEvent e)
{
// How mouse cursor enter event should be handled
}
@Override
public void mouseExited(MouseEvent e)
{
// How mouse cursor exit event should be handled
}
}
然后您的JPanel
组件可以添加此lisneter:
public class MyPanel extends JPanel
{
public static void main(String[] args)
{
MyPanel panel = new MyPanel();
panel.addMouseListener(new MyMouseListener());
}
}
默认方法是将MouseListener
特定实现声明为Swing组件的内部类,以便从这些类的自然绑定中受益,并从一个和另一个获得对两个实例变量的访问。
这将允许您为单个事件拥有多个侦听器,但如果您不需要,您仍然可以将自己的组件设置为侦听器:
public class MyPanel extends JPanel implements MouseListener
{
public static void main(String[] args)
{
MyPanel panel = new MyPanel();
panel.initialize();
}
private void initialize()
{
this.addMouseListener(this);
}
@Override
public void mouseClicked(MouseEvent e)
{
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
}
@Override
public void mouseExited(MouseEvent e)
{
}
}