关键的代码是如这样子的:
jComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int nIndex=jComboBox.getSelectedIndex()
////然后针对不同的nIndex值(即不同的被选项)而写入不同的代码。
}
})
我这里帮你编写了一个非常简单的案例,你可以运行看看。
代码如下:
import java.awt.BorderLayout
import javax.swing.JPanel
import javax.swing.JFrame
import java.awt.Dimension
import javax.swing.JComboBox
import java.awt.Rectangle
import javax.swing.JLabel
public class JianTing extends JFrame {
private static final long serialVersionUID = 1L
private JPanel jContentPane = null
private JComboBox jComboBox = null
private JLabel jLabel = null
private JLabel jLabel1 = null
/**
* This is the default constructor
*/
public JianTing() {
super()
initialize()
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(314, 204)
this.setContentPane(getJContentPane())
this.setTitle("JFrame")
this.setVisible(true)
this.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0)
}
})
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jLabel1 = new JLabel()
jLabel1.setBounds(new Rectangle(51, 89, 65, 18))
jLabel1.setText("选项内容:")
jLabel = new JLabel()
jLabel.setBounds(new Rectangle(51, 110, 186, 36))
jLabel.setText("")
jContentPane = new JPanel()
jContentPane.setLayout(null)
jContentPane.add(getJComboBox(), null)
jContentPane.add(jLabel, null)
jContentPane.add(jLabel1, null)
}
return jContentPane
}
/**
* This method initializes jComboBox
*
* @return javax.swing.JComboBox
*/
/////这里是重点代码!!!!
private JComboBox getJComboBox() {
if (jComboBox == null) {
jComboBox = new JComboBox()
jComboBox.setBounds(new Rectangle(62, 25, 170, 27))
jComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int nIndex=jComboBox.getSelectedIndex()
if(nIndex==0){
jLabel.setText(("选项A"))
}
else if(nIndex==1){
jLabel.setText(("选项B"))
}
else if(nIndex==2){
jLabel.setText(("选项C"))
}
}
})
String[] myList={"选项A","选项B","选项C"}
jComboBox.addItem(myList[0])
jComboBox.addItem(myList[1])
jComboBox.addItem(myList[2])
}
return jComboBox
}
public static void main(String args[]){
new JianTing()
}
} // @jve:decl-index=0:visual-constraint="10,10"
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)