我尝试测试是否可以更改组合框选定的索引时,我按下按钮,但它不适用于我什么我试试如果我的组合框被添加到我的框架从另一个班级,请问我想念什么?如何将选定的索引设置为0从另一个类的组合框
,我创建的组合框我的班级:
package MyPackage;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
public class AddMyBox {
private JComboBox combobox;
String[] array = {"Select", "1", "2", "3"};
public JComboBox theBox() {
combobox = new JComboBox();
combobox.setModel(new DefaultComboBoxModel(array));
combobox.setBounds(10, 11, 414, 20);
return combobox;
}
}
,并在那里创建了我的躯体,并在那里我添加成分是类:
package MyPackage;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyFrame extends JFrame {
public MyFrame() {
getContentPane().setLayout(null);
setVisible(true);
// adding the comboBox from class AddMyBox
AddMyBox getBox = new AddMyBox();
getContentPane().add(getBox.theBox());
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
// if selected index is 1 make it 0 when the button is pressed
if(getBox.theBox().getSelectedIndex() != 0) {
getBox.theBox().setSelectedIndex(0);
}
} catch (Exception e) {
// TODO: handle exception
}
}
});
btnNewButton.setBounds(10, 63, 414, 23);
getContentPane().add(btnNewButton);
setSize(500,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void MyFrame1() {
// TODO Auto-generated method stub
}
}
我的主类是: 包MyPackage;
public class MyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyFrame getFrame = new MyFrame();
getFrame.MyFrame1();
}
}
*“你可以告诉我我错过了什么吗?”*基本的面向对象,应该在两个类中计算出来,这两个类意味着从命令行运行。 GUI是一个高级主题,您应该已经了解对象引用和通过方法访问来封装属性。 –