有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaGridLayout和鼠标侦听器

嗨,我正在尝试用鼠标侦听器构建一个网格布局GUI。因此,当在网格中单击特定单元格时,将显示信息。我不知道从哪里开始,任何帮助都是好的 谢谢


共 (3) 个答案

  1. # 1 楼答案

    在gridlayout中,使用按钮或标签等组件设置所有网格。您可以在添加的组件上设置侦听器,并在单击组件时显示信息

  2. # 2 楼答案

    我相信您有一个继承自JPanel或JFrame的类,其中包含整个GUI。然后,这个类应该实现mouseListener。那么您的类应该有类似的代码:

    @override
    public void mouseClicked(MouseEvent e){}
    @override
    public void mousePressed(MouseEvent e){}
    @override
    public void mouseEntered(MouseEvent e){}
    @override
    public void mouseReleased(MouseEvent e){
        /*This method is being called when you release your click. It's better
          then mouseClicked because mouseClicked is only called when you press
          and release on the same pixel or Object (not sure about it)
        */
    }
    @override
    public void mouseExiteded(MouseEvent e){}
    

    在每种方法中,您都可以获得

    MouseEvent e
    

    使用

    Object source = e.getSource();
    if (source == button1){
        //Do sth
    }if (source == button2){
        //Do sth else
    }if (source == radioButton1){
        //Do whatever you want
    }
    

    然后您就可以引用源代码,这样您就可以修改所需的内容

  3. # 3 楼答案

    要正确使用gridbaglayout,应首先处理gridbagconstraints。然后,您应该使用ActionListener界面来处理鼠标单击。如果单元格是标签类型,可以使用myLabel隐藏文本setText(“”)并使用myLabel放置文本。setText(“要显示的信息”)。如果你需要更多的帮助,只要问:D和+1是否有帮助^^