如何阻止JFileChooser打开一个新窗口

时间:2015-10-09 19:03:51

标签: java jfilechooser

目前正致力于一个相当简单的学校计划。我一直在努力教自己如何使用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);

}

}

1 个答案:

答案 0 :(得分:0)

显然我需要一些睡眠。问题是因为我在按钮上有两个动作监听器,其中一个正在与其他人一起调用。