0

我只是想知道这里是否有一个 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);        
}});
4

2 回答 2

0

不,该变量仅在它创建的块内可见。您可以在外部创建一个变量,并依赖于if (...){...} else{...}该变量持有 aJButton或 null ,如果它不持有,您可以添加它null

于 2013-06-02T18:15:31.747 回答
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);






}});
于 2013-06-02T18:18:38.440 回答