Java netbeans 如何将值传递给 jComboBox
Java netbeans How to pass value to jComboBox
如何将值从一个 class 传递到另一个 class 中的 jcombobox
Public void getItem (){
try {
dBconnection...
while(rs.next){
String customers = rs.getString (1);
this.jcombobox1.addItem (customers);
}
}
}
从这个方法到另一个class中的jcombobox。错误在 jcombobox 中?
通常这是一种糟糕的编码方式,无意冒犯。
您不应混合以下代码:
正在获取数据库连接
正在执行一些 SQL
命令并从 ResultSet
获取数据
创建图形
只需将您的方法 Public void getItem ()
更改为 Public List<String> getCustomers()
。这个方法的作用应该只是从数据库中获取数据,并返回客户姓名列表 List<String>
.
然后在你的另一个class中调用这个方法,将整个List<String>
设置为你的JComboBox
的模型。
参见下面的示例:
public class AnotherClass extends JFrame{
private JComboBox<String> jComboBox;
public AnotherClass() {
init();
}
private void init(){
//... other components
DBClass db = new DBClass();
List<String> customers = db.getCustomers();
jComboBox = new JComboBox<>(customers.toArray(new String[]{}));
this.add(jComboBox);
//... other components
}
}
class DBClass{
public List<String> getCustomers (){
List<String> customers = new ArrayList<>();
try{
//dBconnection...
ResultSet rs = null;// your code for getting ResultSet
while(rs.next()){
String customer = rs.getString (1);
customers.add(customer);
}
}catch(SQLException e){
e.printStackTrace();
}
return customers;
}
}
祝你好运。
因为您已经在 A
中拥有 B
的 class 对象,所以假设 ex Bclassobj
.
Public void getItem (){
try {
while(rs.next){
this.jcombobox1.addItem (rs.getString (1));
Bclassobj.Bclassjcombobox.addItem (rs.getString (1));
}
}
}
如何将值从一个 class 传递到另一个 class 中的 jcombobox
Public void getItem (){
try {
dBconnection...
while(rs.next){
String customers = rs.getString (1);
this.jcombobox1.addItem (customers);
}
}
}
从这个方法到另一个class中的jcombobox。错误在 jcombobox 中?
通常这是一种糟糕的编码方式,无意冒犯。
您不应混合以下代码:
正在获取数据库连接
正在执行一些
SQL
命令并从ResultSet
获取数据
创建图形
只需将您的方法 Public void getItem ()
更改为 Public List<String> getCustomers()
。这个方法的作用应该只是从数据库中获取数据,并返回客户姓名列表 List<String>
.
然后在你的另一个class中调用这个方法,将整个List<String>
设置为你的JComboBox
的模型。
参见下面的示例:
public class AnotherClass extends JFrame{
private JComboBox<String> jComboBox;
public AnotherClass() {
init();
}
private void init(){
//... other components
DBClass db = new DBClass();
List<String> customers = db.getCustomers();
jComboBox = new JComboBox<>(customers.toArray(new String[]{}));
this.add(jComboBox);
//... other components
}
}
class DBClass{
public List<String> getCustomers (){
List<String> customers = new ArrayList<>();
try{
//dBconnection...
ResultSet rs = null;// your code for getting ResultSet
while(rs.next()){
String customer = rs.getString (1);
customers.add(customer);
}
}catch(SQLException e){
e.printStackTrace();
}
return customers;
}
}
祝你好运。
因为您已经在 A
中拥有 B
的 class 对象,所以假设 ex Bclassobj
.
Public void getItem (){
try {
while(rs.next){
this.jcombobox1.addItem (rs.getString (1));
Bclassobj.Bclassjcombobox.addItem (rs.getString (1));
}
}
}