我嘗試測試是否可以更改組合框選定的索引時,我按下按鈕,但它不適用於我什麼我試試如果我的組合框被添加到我的框架從另一個班級,請問我想念什麼?如何將選定的索引設置爲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是一個高級主題,您應該已經瞭解對象引用和通過方法訪問來封裝屬性。 –