简体   繁体   English

如何从SqlServer填充JComboBox

[英]How to populate JComboBox from SqlServer

I am trying to populate a JComboBox from data in SqlServer. 我正在尝试从SqlServer中的数据填充JComboBox。 I am using WindowBuilder if that makes a difference. 我正在使用WindowBuilder,如果有所作为。 This is the code I have so far. 这是我到目前为止的代码。 I am very new to Java so I don't have any idea what to do. 我对Java非常陌生,所以我不知道该怎么做。

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;

public class Customer extends  JFrame{

private JFrame frame;
private JTable table;
private JTable tblInformation;
private JTable tblHistory;

/**
 * Launch the application.
 */
public static void NewScreen()
{
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Customer window = new Customer();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
/**
 * Create the application.
 */
public Customer() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 819, 656);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JComboBox comboBox = new JComboBox();
    comboBox.setBounds(372, 28, 152, 22);
    frame.getContentPane().add(comboBox);

    JLabel lblCustomer = new JLabel("Select customer");
    lblCustomer.setFont(new Font("Tahoma", Font.PLAIN, 16));
    lblCustomer.setBounds(245, 30, 121, 16);
    frame.getContentPane().add(lblCustomer);

    JLabel lblCustomerInformation = new JLabel("Information");
    lblCustomerInformation.setFont(new Font("Tahoma", Font.PLAIN, 16));
    lblCustomerInformation.setBounds(12, 74, 92, 16);
    frame.getContentPane().add(lblCustomerInformation);

    JLabel lblHistory = new JLabel("History");
    lblHistory.setFont(new Font("Tahoma", Font.PLAIN, 16));
    lblHistory.setBounds(12, 334, 56, 16);
    frame.getContentPane().add(lblHistory);

    JButton btnEdit = new JButton("Edit");
    btnEdit.setBounds(12, 569, 97, 25);
    frame.getContentPane().add(btnEdit);

    JButton btnExit = new JButton("Exit");
    btnExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Welcome.main(null);
        }
    });
    btnExit.setBounds(690, 569, 97, 25);
    frame.getContentPane().add(btnExit);

    JButton btnAdd = new JButton("Add");
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) 
        {
            String custIDString, firstName, lastName, companyName, phoneNumber, street, city, state, zip;
            int custID; 

            custIDString = JOptionPane.showInputDialog(null,"Enter customer ID", "Customer ID", JOptionPane.INFORMATION_MESSAGE);
            custID = Integer.parseInt(custIDString);

            firstName = JOptionPane.showInputDialog(null,"Enter first name", "First Name", JOptionPane.INFORMATION_MESSAGE);
            lastName = JOptionPane.showInputDialog(null,"Enter last name", "Last Name", JOptionPane.INFORMATION_MESSAGE);
            companyName = JOptionPane.showInputDialog(null,"Enter company name", "Company Name", JOptionPane.INFORMATION_MESSAGE);
            phoneNumber = JOptionPane.showInputDialog(null,"Enter phone number (xxx-xxx-xxx)", "Phone Number", JOptionPane.INFORMATION_MESSAGE);
            street = JOptionPane.showInputDialog(null,"Enter street", "Street", JOptionPane.INFORMATION_MESSAGE);
            city = JOptionPane.showInputDialog(null,"Enter city", "City", JOptionPane.INFORMATION_MESSAGE);
            state = JOptionPane.showInputDialog(null,"Enter state", "State", JOptionPane.INFORMATION_MESSAGE);
            zip = JOptionPane.showInputDialog(null,"Enter zip", "Zip", JOptionPane.INFORMATION_MESSAGE);
        }


    });
    btnAdd.setBounds(235, 569, 97, 25);
    frame.getContentPane().add(btnAdd);

    table = new JTable();
    table.setBounds(257, 168, 137, -66);
    frame.getContentPane().add(table);

    tblInformation = new JTable();
    tblInformation.setBounds(12, 96, 422, 156);
    frame.getContentPane().add(tblInformation);

    tblHistory = new JTable();
    tblHistory.setBounds(12, 357, 422, 177);
    frame.getContentPane().add(tblHistory);

    JButton btnDelete = new JButton("Delete");
    btnDelete.setBounds(474, 569, 97, 25);
    frame.getContentPane().add(btnDelete);
}
public class TestComboBox extends JComboBox
{
    private Connection sqlCon;
    private Statement st;

    public TestComboBox()
    {
        super();

        initComponents();
    }
    private void initComponents()
    {
        try
        {
            st = sqlCon.createStatement();
            loadComboBox();
        }
        catch (SQLException sqle)
        {
            System.out.println(sqle);
        }
    }
    public void loadComboBox()
    {
        this.removeAllItems();
        this.addItem("Please select");
        try
        {
            ResultSet rs = st.executeQuery("select FirstName, LastName from Customer");
            while (rs.next())
            {
                this.addItem(rs.getString("FirstName") + "" + rs.getString("LastName"));
            }
        }
        catch (SQLException sqle)
        {
            System.out.println(sqle);
        }
    }

}
}
public void loadCombo(){
    Vector vec = new Vector();

        try {
            resultset = //"resultst from database";
            while (resultset.next()) {
                vec.add(resultset.getString("table column"));
                }
                 yourCombo.setModel(new DefaultComboBoxModel(vec)); 
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

well here is an example, what im doing here is getting values from resultset putting the values into a vector then im adding the vector inside the combobox try this. 好吧,这是一个示例,我在这里所做的就是从resultset集中获取values ,然后将值放入vector然后我将vector添加到combobox尝试一下。

Have you heard about overriding toString method in classes? 您是否听说过在类中重写toString方法? I'll try to explain. 我会尽力解释。

If you have a class named Customers and attributes for this class are firstName and lastName (with setters and getters), then you could override toString method in Customers class like this: 如果您有一个名为Customers的类,并且该类的属性是firstName和lastName(带有setter和getters),则可以在Customers类中重写toString方法,如下所示:

@Override
public String toString() {
    return firstName;
}

Then you could create a class Example that returns a DefaultComboBoxModel like this: 然后您可以创建一个类Example,该类返回一个DefaultComboBoxModel,如下所示:

public static DefaultComboBoxModel getCustomerModel() {
    DefaultComboBoxModel model = new DefaultComboBoxModel();
    ResultSet rs = st.executeQuery("select FirstName, LastName from Customer");
    while (rs.next()) {
        Customer c = new Customer();
        c.setFirstName(rs.getString("FirstName"));
        c.setLastName(rs.getString("LastName"));
        model.addElement(c);
    }
    return model;
}

Finally set your combobox model like this: 最后像这样设置组合框模型:

myComboBox.setModel(Example.getCustomerModel());

So in myComboBox you will see only the firstName of the customer and if you want to obtain a Customer from myComboBox object, then: 因此,在myComboBox中,您将仅看到客户的名字,并且如果要从myComboBox对象获取客户,则:

Customer c = (Customer) myComboBox.getSelectedItem();

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM