繁体   English   中英

如何阻止JFileChooser打开新窗口

[英]How to stop JFileChooser from opening a new window

目前正在为学校开发一个相当简单的程序。 我一直在试图教自己如何使用JFileChooser并遇到一个小问题。 通过其相应按钮一次调用JFileChooser之后,每次也按下任何其他按钮时,窗口就会打开。 我的代码很草率,因为我不确定它到底是做什么的,所以我想知道是否有办法防止手动打开窗口? 我做了很多研究,似乎找不到任何东西。

就像我之前说过的那样,代码很草率,但是如果有人有时间浏览一下,就在这里。

public class Scramble extends JFrame
{
private final JFileChooser chooser = new JFileChooser();

Random randNum;

private int score = 0;
private int guess = 0;
private int totalWords;
private int currentWord;

private File file;

private ArrayList<String> originalWords = new ArrayList<>();

private JLabel labelScrambledWord = new JLabel("Unscramble");

private JTextField textUserGuess = new JTextField(28);

private JButton buttonCheck = new JButton("Check");
private JButton buttonGiveUp = new JButton("Give Up");
private JButton buttonBrowse = new JButton("Browse");

private JPanel mainPanel = new JPanel();

public Scramble()
{
    // Sets current word to random number
    randNum = new Random();
    changeCurrentWord();

    // Sets label to scrambled word as soon as program opens
    newWord();
    mainPanel.add(labelScrambledWord);

    mainPanel.add(textUserGuess);

    buttonCheck.addActionListener(new ButtonListener());
    buttonGiveUp.addActionListener(new ButtonListener());

    buttonBrowse.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e)
        {
            browseButtonClicked();
        }

    });

    mainPanel.add(buttonCheck);
    mainPanel.add(buttonGiveUp);
    mainPanel.add(buttonBrowse);

    this.add(mainPanel);
}

private void browseButtonClicked()
{   
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("Browse for text file");

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Txt File", "txt");
    chooser.setFileFilter(filter);

    int buttonVal = chooser.showOpenDialog(this);

    if(buttonVal == JFileChooser.APPROVE_OPTION)
    {
        file = chooser.getSelectedFile();

        try
        {
            readFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}

private void changeCurrentWord()
{
    if(originalWords.size() > 0)
    {
        currentWord = randNum.nextInt(originalWords.size());
    }
}

private void newWord()
{   
    // Checks if any words are left and then sets new word
    if(originalWords.size() > 0)
    {
        labelScrambledWord.setText(scramble(originalWords.get(currentWord)));
    }
    // Changes text field to display total score
    else if(totalWords > 0)
    {
        textUserGuess.setText("Complete: Your score is " + String.format("%.2f", (double)score/(double)totalWords) + "/" + 5);
    }
    else
    {
        textUserGuess.setText("Input text file");
    }
}

/*
 * Reads Strings from txt file
 */
private void readFile() throws IOException
{
    // Grabs txt file from path
    Scanner scan = new Scanner(file);

    // Adds new words to ArrayList until there are none left
    while (scan.hasNext())
    {
        originalWords.add(scan.next());
    }
    totalWords = originalWords.size();
    scan.close();
}

/*
 * Returns original word given in parameters as scrambled word
 */
private String scramble(String originalWord)
{
    randNum = new Random();

    int index;

    // String that will be returned
    String scrambledWord = "";

    // Allows us to remove characters from original word after character has
    // been added to scrambled word
    String editedWord = originalWord;

    for (int count = 0; count < originalWord.length(); count++)
    {
        index = randNum.nextInt(editedWord.length());
        scrambledWord += editedWord.substring(index, index + 1);

        // Removes the character added to the scrambled word from original
        editedWord = editedWord.substring(0, index) + editedWord.substring(index + 1);
    }
    return scrambledWord;
}

/*
 * ButtonListener class to use as action listener for buttons
 */
private class ButtonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        // Checks which button was clicked
        if (e.getActionCommand().equals("Check"))
        {
            checkButtonClicked();
        }
        // Executed when "Give Up" button is pressed
        else if (e.getActionCommand().equals("Give Up"))
        {
            giveUpButtonClicked();
        }
        else if(e.getActionCommand().equals("Browse"));
        {
            browseButtonClicked();
        }

    }

    // Executed if buttonCheck is clicked
    private void checkButtonClicked()
    {
        //Closes program if user hits another button after words are gone
        if(originalWords.size() == 0)
        {
            System.exit(0);
        }

        if (textUserGuess.getText().equalsIgnoreCase(originalWords.get(currentWord)))
        {
            textUserGuess.setText("That is correct. Here is a new word to try.");

            // Removes word from list
            originalWords.remove(currentWord);

            // Sets new current word
            changeCurrentWord();

            // Adds score based on number of guesses currently
            addScore();

            // Changes word to new word
            newWord();
        }
        else
        {
            textUserGuess.setText("Sorry, that is incorrect. Please try again.");

            // Adds a guess to the count after wrong answer
            guess++;
        }
    }

    // Executed if buttonGiveUp is clicked
    private void giveUpButtonClicked()
    {

        // Closes program if user hits another button after words are gone
        if(originalWords.size() == 0)
        {
            System.exit(0);
        }

        // Displays answer to user
        textUserGuess.setText(originalWords.get(currentWord));

        // Removes word from list
        originalWords.remove(currentWord);

        // Changes current word being displayed
        changeCurrentWord();

        // Sets guess back to 0 for new word
        guess = 0;

        // Sets new scrambled word
        newWord();
    }

    /*
     * Adds to player score based on number of guesses used
     */
    private void addScore()
    {
        switch (guess)
        {
        case 0:
            score += 5;
            break;
        case 1:
            score += 3;
            break;
        case 2:
            score += 1;
            break;
        default:
            score += 0;
        }

        guess = 0;
    }

}

public static void main(String[] args)
{

    Scramble frame = new Scramble();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);

    // Prevents user from changing dimensions and causing interface to look
    // different than intended.
    frame.setResizable(false);

    frame.setVisible(true);

}

}

显然我需要睡觉。 问题是因为我在按钮上有两个动作侦听器,而其中一个正在被其他人调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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