我如何从另一个类setVisible(true)一个JLabel

时间:2016-04-03 17:23:41

标签: java

这是我的代码。我在Check1标签上遇到了问题,因为我希望它在答案正确的时候是可见的,就像我使用卡片布局一样。 我删除了不重要的代码

public class Category1 extends JPanel {
public static JLabel Check1;
  public Category1 () {


    Check1 = new JLabel(newImageIcon(getClass().getResource("Buttons/Check.png")));
    Check1.setBounds(75 , 305, 40, 40);
    Check1.setVisible(false);
    add(Check1);

}}

这是另一个类,如果单击Submit1按钮,如果JTextField中的文本是正确的,我希望Check1按钮是可见的。

public class QuizPanelc1 {
   JPanel Quiz1;
   JTextField Answer1;
   JButton Submit1;

public QuizPanelc1(){

    Answer1 = new JTextField();
    Answer1.setBounds(180, 480, 200, 40);
    Quiz1.add(Answer1);
    Submit1 = new JButton(new ImageIcon(getClass().getResource("Buttons/SubmitButton.png")));
    Submit1.setBounds(390, 480, 40, 40);
    Quiz1.add(Submit1);

ButtonHandler1 events1 = new ButtonHandler1();
    Submit1.addActionListener(events1);
    Back1.addActionListener(events1)

}
private class ButtonHandler1 implements ActionListener {
    public void actionPerformed (ActionEvent eventClick) {
        Object event = eventClick.getSource();
        Category1 c1 = new Category1();

        if(Submit1==event)
        {
            if(Answer1.getText().equalsIgnoreCase("Fila"))
            {
                Answer1.setEditable(false);

                JOptionPane.showMessageDialog(null, "Correct");
                c1.Check1.setVisible(true);

            }
            else
            {

                JOptionPane.showMessageDialog(null, "Wrong Answer");

            }
        }
        else
        {
         System.exit(1);
        }
}}

1 个答案:

答案 0 :(得分:1)

将check1作为类的一个字段而不是静态,然后创建一个公共方法来设置可见性:

实施例

public class Category1 extends JPanel {
    private JLabel check1;

    public void setCheck1Visibility(boolean visible) {
        check1.setVisible(visible);
    }

    public Category1() {
        check1 = new JLabel(new ImageIcon(getClass().getResource("Buttons/Check.png")));
        check1.setBounds(75, 305, 40, 40);
        check1.setVisible(false);
        add(check1);
    }
}

然后由于你有一个 Category1 的实例,你可以这样做:

Category1 c1 = new Category1();
c1.setCheck1Visibility(true);
or 
c1.setCheck1Visibility(false);