简体   繁体   中英

how do i setVisible(true) a JLabel from another class

This is my codes. i had a problem on Check1 Label because i want it to be Visible when the Answer is Correct , by the way i am using Card Layout for that. i remove the not important codes

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);

}}

and here's the other class, if you click the Submit1 Button, and if the text in the JTextField is correct, i want the Check1 button to be Visible.

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);
        }
}}

Make check1 a field of the class and not static and then make a public method for setting the visibility:

Example:

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);
    }
}

then since you have an instance of Category1 , you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM