我想用java做一个问题。这是我的代码:
import java.awt.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Chestionar extends JFrame {
public Chestionar() {
super("Chestionar");
final int x, y, z;
x = y = z = 0;
String ch1;
JPanel jp = new JPanel();
JLabel jl = new JLabel("Name:");
JTextField jtf = new JTextField(10);
ch1 = jtf.getText();
jp.add(jl);
jp.add(jtf);
add(jp);
JPanel jp1 = new JPanel();
JLabel jl1 = new JLabel();
String s = "Welcome";
jl1.setText(s);
jp1.add(jl1);
add(jp1);
//first question
final JPanel jp2 = new JPanel();
JLabel jl2 = new JLabel("What is called as the roof of the world? 1.Nepal 2.Tibet etc");
final JComboBox jcb = new JComboBox();
for(int i=0; i<5; i++){
jcb.addItem(i);
}
ActionListener alege = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(jcb.getSelectedItem().toString().equals("2")){
JLabel bine = new JLabel("Right");
jp2.add(bine);
} else {
JLabel gresit = new JLabel("Wrong");
jp2.add(gresit);
}
}
};
jcb.addActionListener(alege);
jp2.setLayout(new FlowLayout());
jp2.add(jl2);
jp2.add(jcb);
add(jp2);
setVisible(true);
setLayout(new GridLayout(4, 1));
setSize(600, 600);
}
public static void main(String arg[]) {
Chestionar ch = new Chestionar();
}
}
我想让 JLabel 显示为“正确”或“错误”,这取决于JComboBox
. 我不知道为什么,如果没有出现从JComboBox
特定项目中选择的项目JLabel
,只有当我重新调整主框架的大小时。