【发布时间】:2016-08-13 14:40:04
【问题描述】:
我尝试测试当我按下按钮时是否可以更改组合框选择的索引,但是如果我的组合框从另一个类添加到我的框架中,我尝试过的方法对我不起作用,请问告诉我我想念什么?
我创建组合框的班级是:
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
}
}
我的主要课程是: 包我的包;
public class MyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyFrame getFrame = new MyFrame();
getFrame.MyFrame1();
}
}
【问题讨论】:
-
“你能告诉我我想念什么吗?” 基本 OOP,应该在两个要从命令行运行的类中弄清楚。 GUI 是一个高级主题,您应该已经了解对象引用和方法访问对属性的封装。
标签: java swing jbutton jcombobox selectedindex