2013-03-17 67 views
2

我试图让PlaySci按钮被按下时打开图像,所以我把图像放在PlaySci动作监听器中,但是只有当按下退出按钮时它才会打开?当我在GUI中的actionListener中按下按钮时,图像无法打开?

我已经看了几个小时,仍然不明白为什么,我试图摆脱退出按钮alltogether,但然后图像根本不显示。

我所造的像成JLabel顶部:

ImageIcon scis1 = new ImageIcon("scis.jpg"); 

private JLabel picture = new JLabel(scis1); 

这里是我的PlaySci按钮ActonListener代码:

class PlaySciHandler implements ActionListener { 
    public void actionPerformed(ActionEvent event) { 

     String computerRand = sps.computerChoice(); 
     txtComputerRand.setText(computerRand); 
     String result = sps.play(Sps.SCISSORS); 
     txtResult.setText(result); 
     picture.setBounds(60, 200, 400, 400);// this is the image I want displayed when the PlaySci button is pressed 
     panel.add(picture); 
    } 
} 

这是退出按钮的ActionListener(由于某种原因是显示图像的唯一方式):

class exitHandler implements ActionListener{ 
    public void actionPerformed(ActionEvent e) { 
     int n = JOptionPane.showConfirmDialog(frame, //when this button is pressed the image comes up? 
       "Are you sure you want to exit?", 
       "Exit?", 
       JOptionPane.YES_NO_OPTION); 
     if(n == JOptionPane.YES_OPTION){ 
      System.exit(0); 
     } 
    } 
} 

这是co创建按钮并添加ActionListener:

   btnPlaySci = new JButton ("Scissors!"); 
     btnPlaySci.setBounds(180, 40, 110, 20); 
     btnPlaySci.addActionListener(new PlaySciHandler()); 
     panel.add (btnPlaySci); 
     btnPlaySci.setForeground(Color.MAGENTA); 

任何帮助,将不胜感激。

+0

显示你是如何将听众设置为按钮 – Sach 2013-03-17 15:01:49

+0

的,向你展示将代码'ActioListener'注册到'JButtons'的代码。 – 2013-03-17 15:02:05

+0

ok,已编辑 – dhali 2013-03-17 15:05:49

回答

2

不要加在class PlaySciHandler implements ActionListenerJLabel block.Add它在你createForm()方法,使其隐形:picture.setVisible(false); ,当你想有一个按钮,点击后显示,使其可见:picture.setVisible(true);

+0

工作....最后!谢啦!非常感谢 – dhali 2013-03-17 15:29:06

+0

@dhali欢迎:) – 2013-03-17 15:29:44

3

你应该添加图片后重新绘制面板。请参阅PlaySciHandleractionPerformed方法的代码。

class PlaySciHandler implements ActionListener { 
     public void actionPerformed(ActionEvent event) { 

      String computerRand = sps.computerChoice(); 
      txtComputerRand.setText(computerRand); 
      String result = sps.play(Sps.SCISSORS); 
      txtResult.setText(result); 
      picture.setBounds(60, 200, 400, 400);// this is the image I want displayed when the PlaySci button is pressed 
      panel.add(picture); 
      panel.repaint();//Must repaint the panel . 
     } 
    } 

注:作为一个方面说明我会建议你从来不使用null LayoutJPanel。使用由Swing提供的内置Layouts。您可以在此official site获得有关布局使用情况的更多信息。另一个是始终坚持使用java命名约定。 exitHandler应改为ExitHandler。要了解更多,请看official site

+0

第一个答案为我工作,但感谢您的帮助和零布局 – dhali 2013-03-17 15:41:24

+0

1+的建议,以避免空布局。 – 2013-03-17 16:06:11

相关问题