如何避免使此方法和所有其他变量保持静态?

时间:2014-01-22 21:02:34

标签: java swing static listener jlist

我对Java很陌生,我正在尝试使用swing进行一些操作。

    class CustomListSelectionListener implements ListSelectionListener {
    public void valueChanged (ListSelectionEvent e)
    {
        //All this listener does is to return the NAME of the selected connection to the static method gotocategories.
        JList lsm = (JList)e.getSource();
        Home.goToCategories((String)lsm.getSelectedValue());
    }

问题是,监听器是一个类,所以基本上如果我从“家庭类”调用静态方法,我需要在“goToCategories”函数中使用静态的所有变量。

    public static void goToCategories(String collectionname)
{
    Statement stmt;
    try
    {
        stmt = privconn.createStatement();
        //Getting the collection ID;
        String firststmt = "SELECT * FROM collection WHERE Name='"+collectionname+"' AND User_ID = "+userID+"";
        ResultSet rs = stmt.executeQuery(firststmt);
        rs.next();
        int id = rs.getInt("ID");
        JOptionPane.showMessageDialog(null, id);

    } catch(Exception E)
    {
        E.printStackTrace();
    }
}

此代码有效,但我认为我创建了很多静态变量,我不确定这是最好的方法。 当然,一旦我尝试删除静态,它就会说“不能静态引用非静态字段......”

2 个答案:

答案 0 :(得分:1)

如果您的CustomSelectionListener课程对Home课程的实例参考,您就可以调用非静态方法在那个例子上。

它看起来像这样:

MyClass someObject = new MyClass();
someObject.nonStaticMethod();

但是,通过使用类的名称来调用静态方法而不使用类的实例:

MyClass.someStaticMethod();

设计决定方法或成员变量是否应该是静态的,并且评论说你应该完全理解static的含义,以便正确地做出这个决定。

答案 1 :(得分:0)

我认为最好的办法就是在没有主要方法的情况下上课 在构造函数中执行所有操作,然后从另一个类(new my class)中的main方法创建该类的新实例,