actionPerformed按钮的例外情况

时间:2016-01-03 12:26:03

标签: java swing actionlistener

这是一个正在建设中的秋千窗。问题出在一个行动中。 当我对"打开"按钮,我调用方法OpenFile()

此方法似乎一直有效,直到它抛出UnsupportedOperationException异常。

import static alphareader.AlphaReaderBackup.maxGap;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;


public class AlphaReader extends JFrame 
implements ActionListener {

    final JFileChooser fc = new JFileChooser();

    private final JButton open=new JButton("Open File.");
    private final JButton exitButton = new JButton(" Exit ");

    JLabel welcomeMsg=new JLabel("Welcome to alpha reader. ");


    //BoxLayout boxy = new BoxLayout();
    GridLayout gridy = new GridLayout(3,2);
    FlowLayout flow = new FlowLayout();
    GridLayout rowsGrid=new GridLayout();


    Dimension btn=new Dimension(132,32);

    public static void main(String[] args){
        AlphaReader alpha=new AlphaReader();
        alpha.setSize(800,800);
        alpha.createGui();
        alpha.setVisible(true);
    }

    private void createGui(){
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window=getContentPane();
    window.setLayout(gridy);
    JPanel row1=new JPanel();
    JPanel row2=new JPanel();
    JPanel row3=new JPanel();


    window.add(row1);
    row1.setLayout(new FlowLayout(flow.LEFT,10,10));
    row1.add(welcomeMsg); 
    welcomeMsg.setPreferredSize(new Dimension(400,32));
    welcomeMsg.setAlignmentX(LEFT_ALIGNMENT);
    row1.add(open);
    open.setPreferredSize(btn);
    open.addActionListener(this);
    exitButton.setPreferredSize(btn);
    row1.add(exitButton);
    exitButton.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent ev) {
    Object source = new Object();
    source=ev.getSource();
    if(source==open){
        openFile();
    }
        else if(source==exitButton){
                System.exit(0);
                }
    throw new UnsupportedOperationException("Not supported yet.");
    }

    private void openFile(){
        int returnVal = fc.showOpenDialog(AlphaReader.this);
        //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();} //I get the exception here.
    }

}

1 个答案:

答案 0 :(得分:3)

更改

Object source = new Object();
source=ev.getSource();
if(source==open){
    openFile();
}
else if(source==exitButton){
    System.exit(0);
}
throw new UnsupportedOperationException("Not supported yet.");

JButton source = (JButton) ev.getSource();
if(source == open){
    openFile();
}
else if(source == exitButton){
    System.exit(0);
}
else
    throw new UnsupportedOperationException("Not supported yet.");

如果没有else语句,将始终抛出UnsupportedOperationException