Java 在函数上使用组合框selectedItem

Java 在函数上使用组合框selectedItem,java,swing,Java,Swing,我有一个连接到数据库的函数 我有一个代码,在组合框中有一个选择和显示元素 因此,我希望传递connexion.java类组合框selectedItem,因为它包含我拥有的所有数据库 所以我希望类连接是动态的,所以传递在这个类上选择的元素 我不知道该怎么做请帮帮我 public class Connexion { private static Connection conn; { try { Class.forName("com.mysql.jd

我有一个连接到数据库的函数 我有一个代码,在组合框中有一个选择和显示元素 因此,我希望传递connexion.java类组合框selectedItem,因为它包含我拥有的所有数据库 所以我希望类连接是动态的,所以传递在这个类上选择的元素 我不知道该怎么做请帮帮我

public class Connexion {
  private static Connection conn;

    {       
           try { 
Class.forName("com.mysql.jdbc.Driver");
 } catch (ClassNotFoundException ex) {
            Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}

           try { 
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456"); 
} catch (SQLException ex) {
            Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }          
              }
public static Connection getconx()
{ 
    return conn; 
}  
}

JComboBox
接受任何类型的对象,因此您可以简单地执行以下操作

Connection con = new Connection();
JComboBox box = getBox();
box.addItem(con);
要获取价值,请执行以下操作:

JComboBox box = getBox();
Connection con = (Connection)box.getSelectedItem();
但是,在连接类中,必须重写
toString()
函数,因为它用于显示框

class Connection
{
     public String toString()
     {
         return "BoxItemDisplayvalue";    <--- here you must put something meaningfull which is displayed in the box.
     }
 }
类连接
{
公共字符串toString()
{
返回“BoxItemDisplayvalue”使用该类

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.NamingException;

import org.apache.commons.dbcp.BasicDataSource;

import sun.jdbc.rowset.CachedRowSet;

public class SQLConnection {

    private static Connection con = null;

    private static BasicDataSource dataSource;


    //we can enable and disable connection pool here
   //true means connection pool enabled,false means disabled
    private static boolean useConnectionPool = true;

    private static int count=0;

    private SQLConnection() {

        /*
        Properties properties = new Properties();
        properties.load(new FileInputStream(""));
        maxActive = properties.get("maxActive");
         */
    }

    public static String url = "jdbc:mysql://localhost:3306/schemaname";
    public static String password = "moibesoft";
    public static String userName = "root";
    public static String driverClass = "com.mysql.jdbc.Driver";
    public static int maxActive = 20;
    public static int maxIdle = 10;

    private static final String DB_URL = "driver.classs.name";
    private static final String DB_USERNAME = "database.username";
    static {
    /*Properties properties = new Properties();
        try {
        properties.load(new FileInputStream("D:\\CollegeBell\\properties\\DatabaseConnection.properties"));
            //properties.load(new FileInputStream("E:\\vali\\CollegeBell\\WebContent\\WEB-INF"));
            //properties.load(new FileInputStream("D:\\DatabaseConnection.properties"));
            url = properties.getProperty(DB_URL);
            System.out.println(url);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setMaxActive(maxActive);
        dataSource.setMinIdle(maxIdle);
        dataSource.setMaxIdle(maxIdle);

    }

    //public static Connection getConnection(String opendFrom) throws SQLException,
    public static Connection getConnection(String openedFrom) {
        count++;
           System.out.println("nos of connection opened till now="+count);
        System.out.println("Connection opended from "+openedFrom);
    //  System.out.println("Connection Opended ");
        try {

            if (useConnectionPool) {
                con = dataSource.getConnection();
                System.out.println(dataSource.getMinEvictableIdleTimeMillis());
                //dataSource.setMaxWait(15000);
                System.out.println(dataSource.getMaxWait());
                System.out.println(count );
            } else {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection(url, userName, password);
            }
        }

            //System.out.println("Connection : " + con.toString());
            catch (SQLException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return con;
    }

    public static void closeConnection(Connection con, String closedFrom)
            {

        //System.out.println("Connection closed from: " + con.toString());
    //  System.out.println("Connection closed from: " + closedFrom);
        //log.info("Connection closed from: " + closedFrom);
        if(con != null){
             count--;
             System.out.println("Connection count value after closing="+count);
        System.out.println("Connection closed from: " + closedFrom);
        try {
            con.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }
    //added by nehal
    public static void closeStatement(Statement ps, String closedFrom)
    {
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
    ps.close();
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}
}


    public static void closePreparedStatement(PreparedStatement ps, String closedFrom)
    {
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
    ps.close();
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}
}

    public static void closeResultSet(ResultSet rs, String closedFrom)
     {
if(rs != null){
System.out.println("ResultSet closed from: " + closedFrom);
try {
    rs.close();
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}
}
    //added by nehal

    /*public static ResultSet executeQuery(String query) throws Exception {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        CachedRowSet crset = null;
        try {
            con = getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery(query);
            crset = new CachedRowSet();
            crset.populate(rs);
        } catch (Exception e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        }
        return crset;
    }

    public static int executeUpdate(String query) throws Exception {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        int rows = -1;
        try {
            con = getConnection();
            stmt = con.createStatement();
            rows = stmt.executeUpdate(query);
        } catch (Exception e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        }
        return rows;
    }

    public static boolean execute(String query) throws Exception {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        boolean rowsreturned = false;
        try {
            con = getConnection();
            stmt = con.createStatement();
            rowsreturned = stmt.execute(query);
        } catch (Exception e) {
            throw e;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        }
        return rowsreturned;
    }*/

    /*
     * public static void closeConnection(Connection con) { try { con.close();
     * con=null; } catch (SQLException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } }
     */

}

据我所知,你们有两门课。。 一个是gui,其中有一个组合框,其中包含要连接的模式名。 因此,当按下提交按钮时,您必须有一个
EventListener
来“监听”

例如:

Connection con = null;
JButton submitButton = new JButton("Confirm db");
submitButton.addActionListener(new MyConnectionListener());

..
//Could be inner class
class MyConnectionListener implements ActionListener {

 @Override
 public void actionPerformed(ActionEvent evt){
         if(cmb.getSelectedItem() != null){
           con = Connection.getConx(cmb.getSelectedItem().toString());
         }

 }

}
在你的连接课上

public class Connexion {

public static Connection getconx(String schema)
{ 
 Connection conn = null;
          try { 
Class.forName("com.mysql.jdbc.Driver");
 } catch (ClassNotFoundException ex) {
            Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}

           try { 
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+schema, "root", "123456"); 
} catch (SQLException ex) {
            Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }          
              } 


   return conn; 
}  
}

我把这个问题读了三遍,我还是不知道你在问什么。我建议你先增加一些分数和大写字母,让它更可读。你还提到了一个组合框,但这在你所贴的代码中没有显示。总之,除了罗宾的建议之外,更清楚你实际上在追求什么,请考虑PASIN。一个格式良好、缩进正确的代码。为了更快地获得更好的帮助,请发布一个“Okey对不起,因为我不知道”这是combobox的代码,用于显示我在Connexion.java类中拥有的所有数据库。我想在函数Connexion中调用selectedItem意味着我随时都在做数据库的名称,我希望它与combobox SelectJCombox2.removeAllItems()相关;试试看{Connection conn=Connexion.getconx();String sql=“从信息中选择架构名称”\u schema.schemata;;“PreparedStatement prest=conn.prepareStatement(sql);ResultSet res=prest.executeQuery();而(res.next()){jComboBox2.addItem(res.getString(“schema_name”);}}catch(SQLException e){e.printStackTrace();}但是与ComboBox元素的关系在哪里使用此连接obj,从db获取所有值并显示在combo box中。JComboBox=getBox();其中是方法getBox()引用一次,它可能会帮助您理解以下含义:JComboBox=JComboBox.getActionCommand();我想在这里添加selectedItem的变量公共静态连接getconx(String dbase){return conn;}连接conn=Connexion.getconx();String box=jComboBox1.getActionCommand();但我不认为这是真的,因为我在URL中的类连接它包含一个数据库的名称,我希望这个名称在ComboboxYes thank中所选项目的函数中会发生变化,即使我用另一种方法来做,但这段代码似乎比我的mine@cisco.nat考虑接受任何回答并鼓励那些帮助你的人。