这是我的代码。我在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);
}
}}
最佳答案
使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);