簡體   English   中英

擴展JFrame和擴展ActionListing時如何在Java中引發IOException

[英]How to throw IOException in Java when you are Extening JFrame and Extending ActionListing

我正在編寫一個基本的聊天機器人程序,其中包含用戶鍵入的內容並作出響應。 我將其回答的問題以及這些問題的答案存儲在一個文本文件中。 我正在使用掃描儀讀取文件。 這也是我使用GUI與用戶交互的第二個程序。 我有一個TextField,一個Label和兩個按鈕(一個用於輸入詢問的問題,另一個用於退出程序)。 據我了解Java中的GUI,您必須在主類中擴展JFrame。 這是我為用於計算矩形面積的圖形程序編寫的另一個程序:

 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class RectangleProgram extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 200; private JLabel lengthL, widthL, areaL; private JTextField lengthTF, widthTF, areaTF; private JButton calculateB, exitB; //Button handlers: private CalculateButtonHandler cbHandler; private ExitButtonHandler ebHandler; public RectangleProgram() { lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT); widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT); areaL = new JLabel("Area: ", SwingConstants.RIGHT); lengthTF = new JTextField(10); widthTF = new JTextField(10); areaTF = new JTextField(10); //SPecify handlers for each button and add (register) ActionListeners to each button. calculateB = new JButton("Calculate"); cbHandler = new CalculateButtonHandler(); calculateB.addActionListener(cbHandler); exitB = new JButton("Exit"); ebHandler = new ExitButtonHandler(); exitB.addActionListener(ebHandler); setTitle("Sample Title: Area of a Rectangle"); Container pane = getContentPane(); pane.setLayout(new GridLayout(4, 3)); //Add things to the pane in the order you want them to appear (left to right, top to bottom) pane.add(lengthL); pane.add(lengthTF); pane.add(widthL); pane.add(widthTF); pane.add(areaL); pane.add(areaTF); pane.add(calculateB); pane.add(exitB); setSize(WIDTH, HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private class CalculateButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { double width, length, area; length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields. width = Double.parseDouble(widthTF.getText()); area = length * width; areaTF.setText("" + area); } } public class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } public static void main(String[] args) { RectangleProgram rectObj = new RectangleProgram(); } } 

我正在使用它來通過此程序使用GUI測試不同的事物。 當我嘗試在CalculateButtonHandler中拋出IOException時,它說我做不到。 我正計划對Chat Bot程序使用非常類似的設置,但是想知道IOException是否有解決方法,或者是否有更好,更輕松的方法來制作GUI?

您不能更改接口中已定義的方法以引發尚未聲明要拋出的異常。 如果您確實想拋出一個異常,則可以拋出某種RuntimeException,因為它不是經過檢查的異常,因此不必聲明為拋出異常。

話雖這么說,您實際上應該避免在事件調度線程中引發異常。 事件調度線程是處理所有與GUI相關的事件的地方。 當您編寫在事件調度線程中執行的代碼時,它應該簡短,快速且可靠。 穩健的含義是不應包含需要錯誤處理的代碼,否則應迅速處理錯誤並繼續前進。

對於更多的事件Dispath,您可以查看以下解釋: Java Event-Dispatching Thread解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM