1、添加控件
private JComboBox selectCountryJComboBox;
private String[] countries = { "Russia", "China", "United States",
"Italy", "Australia", "South Africa", "Brazil", "Spain" };
createUserInterface():
// 对数组countries 进行排序
Arrays.sort( countries );
//把数组countries的内容绑定到JComboBox
selectCountryJComboBox = new JComboBox( countries );
selectCountryJComboBox.setBounds( 136, 32, 135, 21 );
selectCountryJComboBox.setMaximumRowCount( 3 );
contentPane.add( selectCountryJComboBox );
//获取JComboBox中第i个选项的名称(名称指我们看到的文字,而不是里面我们看不到的索引号;i为int
//型)
String country =
( String ) selectCountryJComboBox.getItemAt(i);
//获取被选择选项的索引
int i= selectCountryJComboBox.getSelectedIndex();
//设置JComboBox中被选选项的索引,下面代码表示设置JComboBox默认显示索引为0的对象
selectCountryJComboBox.setSelectedIndex( 0 );
2、与数据库结合
private JComboBox accountNumberJComboBox; //添加控件
createUserInterface():
//布置JComboBox
accountNumberJComboBox = new JComboBox();
accountNumberJComboBox.setBounds( 150, 12, 96, 25 );
accountNumberJComboBox.addItem( "" );
accountNumberJComboBox.setSelectedIndex( 0 );
accountNumberJPanel.add( accountNumberJComboBox );
accountNumberJComboBox.addItemListener(
new ItemListener() // anonymous inner class
{
// event handler called when account number is chosen
public void itemStateChanged( ItemEvent event )
{
accountNumberJComboBoxItemStateChanged( event );
}
} // end anonymous inner class
); // end call to addItemListener
×××××××××要注意这个事件驱动JComboBox的event.getStateChange() == ItemEvent.SELECTED
2.2把数据库里的一列绑定到JComboBox,其他setSelectedIndex等方法和数组一样的
// load account numbers to accountNumberJComboBox
private void loadAccountNumbers()
{
// get all account numbers from database
try
{//把accountNumber字段绑定到JComboBox
myResultSet = myStatement.executeQuery(
"SELECT accountNumber FROM accountInformation" );
// add account numbers to accountNumberJComboBox
while ( myResultSet.next() )
{
accountNumberJComboBox.addItem(
myResultSet.getString( "accountNumber" ) );
}
myResultSet.close(); // close myResultSet
} // end try
请接下来看实例