2013-06-02 29 views
0

我只是想知道是否有做一个JButton内一个不错的选择:创建的新的JButton内如果

if(RandomNrJeden <= 50) 
{ 
    JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be green."); 
    JButton dialogOdp = new JButton(); 
} 
else 
{ 
    JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be red."); 
} 

然后只需键入: panel.add(dialogOdp); 外面?

这里是整个代码:

final JButton continueGame = new JButton(); 
continueGame.setPreferredSize(new Dimension(1000, 30)); 
continueGame.setLocation(95, 45); 
continueGame.setText("<html>Continue</html>"); 
continueGame.addActionListener(new ActionListener(){ 
    @Override 
    public void actionPerformed(ActionEvent ev) { 
     panel.remove(continueGame); 

     SwingUtilities.updateComponentTreeUI(frameKontrastGame); 
     if(RandomNrJeden <= 50) 
     { 
      JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be green."); 
      JButton dialogOdp = new JButton(); 
     } 
     else 
     { 
      JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be red."); 
     } 
    }}); 


    //final JLabel im = new JLabel(new ImageIcon("kontrast_logo_2.png"));   
    //panel.add(im);   
    panel.add(dialogOdp);   
    panel.add(continueGame);   
    frameKontrastGame.getContentPane().add(panel);   
    frameKontrastGame.setLocationByPlatform(true);   
}}); 

回答

0

只是在你的代码的修改

final JButton continueGame = new JButton(); 
    JButton dialogOdp;  // declare here 
    continueGame.setPreferredSize(new Dimension(1000, 30)); 
    continueGame.setLocation(95, 45); 
    continueGame.setText("<html>Continue</html>"); 
    continueGame.addActionListener(new ActionListener(){ 
     @Override 
     public void actionPerformed(ActionEvent ev) { 
      panel.remove(continueGame); 
      SwingUtilities.updateComponentTreeUI(frameKontrastGame); 
       if(RandomNrJeden <= 50) 
       { 
        JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be green."); 
        dialogOdp = new JButton(); // initialize here 


       } 
       else 
       { 
        JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be red."); 
       } 
    }}); 




//final JLabel im = new JLabel(new ImageIcon("kontrast_logo_2.png")); 
//panel.add(im); 
if(dialogOdp != null) // check for null 
    panel.add(dialogOdp); 
panel.add(continueGame); 
frameKontrastGame.getContentPane().add(panel); 
frameKontrastGame.setLocationByPlatform(true); 






}}); 
+0

没有什么太多的解决,如果不重新确认和重新绘制叫 – mKorbel

0

否,变量只是创建它的块内可见。 你可以在外面if (...){...} else{...}和因创建一个变量的变量保存JButton或空,你可以,如果它认为没有null添加它。