我想在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
,只有当我重新调整主框架的大小时才会显示。
答案 0 :(得分:4)
每次JLabel
JPanel
被解雇时,您都会向jp2
ActionEvent
添加新的JComboBox
。在您调整面板(或revalidate
+ repaint
)面板之前,标签不会显示。
最好添加一个JLabel
并通过调用setText
来更新它。此方法不需要调用repaint
:
Integer selectedItem = (Integer) jcb.getSelectedItem();
switch (selectedItem) {
case 2: // currently using 2 for correct answers...
answerStatusLabel.setText("Right");
break;
default:
answerStatusLabel.setText("Wrong");
break;
}
答案 1 :(得分:0)
必须刷新JLabel。或者像raven1981建议的那样执行jp2.repaint(),或者调用像Reimeus建议的setText。