0

我想用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,只有当我重新调整主框架的大小时。

4

2 回答 2

4

每次为JLabel您的. 在您调整(或+ )面板的大小之前,标签不会出现。JPanel jp2ActionEventJComboBoxrevalidaterepaint

最好添加一个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;
}
于 2013-01-13T00:03:04.827 回答
0

JLabel 必须刷新。要么按照 raven1981 的建议执行 jp2.repaint(),要么按照 Reimeus 的建议调用 setText。

于 2013-01-13T00:07:08.143 回答