Java 我可以使用BufferedReader并在actionListener类中创建一个数组吗?
我创建了一个actionListener类。在actionPerformed方法中,我想运行一段代码。此代码涉及从多个文本文件导入数据,并将其存储在二维数组中。然后它将打印出框架中的引号列表。然后它将打印出5个分析,让用户选择哪一个。然而,我目前被IOException困住了。另外,一些代码状态会给出一个错误“无法访问的代码”。这意味着什么?下面是我的actionListener类的代码Java 我可以使用BufferedReader并在actionListener类中创建一个数组吗?,java,swing,awt,actionlistener,Java,Swing,Awt,Actionlistener,我创建了一个actionListener类。在actionPerformed方法中,我想运行一段代码。此代码涉及从多个文本文件导入数据,并将其存储在二维数组中。然后它将打印出框架中的引号列表。然后它将打印出5个分析,让用户选择哪一个。然而,我目前被IOException困住了。另外,一些代码状态会给出一个错误“无法访问的代码”。这意味着什么?下面是我的actionListener类的代码 import java.awt.event.*; import java.io.*; import java
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class CrucibleButtonListener implements ActionListener
{
private Swing g;
public CrucibleButtonListener (Swing g)
{
this.g = g;
}
public void actionPerformed(ActionEvent e)
{
this.g.updateTextField(getQuotes());
}
private String getQuotes() throws IOException
{
BufferedReader inputQuote;
BufferedReader inputTheme;
BufferedReader inputCharacterAnalysis;
BufferedReader inputSignificance;
BufferedReader inputPlotEnhancement;
BufferedReader inputSpeaker;
Scanner in = new Scanner (System.in);
int howMany=0;
int quoteSelection;
int analysisSelection;
// Count how many lines in the text file
FileReader fr = new FileReader ("CrucibleQuotations.txt");
LineNumberReader ln = new LineNumberReader (fr);
while (ln.readLine() != null)
{
howMany++;
}
//import information from the text file
inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));
//Create array based on how many quotes available in the text file
String [][] quotes = new String [howMany][6];
//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
quotes [i][0] = inputQuote.readLine();
return (i+1 + ") " + quotes [i][0]);
quotes [i][1] = inputTheme.readLine();
quotes [i][2] = inputCharacterAnalysis.readLine();
quotes [i][3] = inputSignificance.readLine();
quotes [i][4] = inputPlotEnhancement.readLine();
quotes [i][5] = inputSpeaker.readLine();
}
//Ask user to choose the quote they want to analyze
return ("Choose a quotation by inputting the number: ");
quoteSelection = in.nextInt ();
if (quoteSelection!=0)
{
//Show user selections to analyze
return ("1. Theme");
return ("2. Character Analysis");
return ("3. Significance");
return ("4. Plot Enhancement");
return ("5. Speaker");
analysisSelection = in.nextInt ();
//Display the analysis
if (analysisSelection <= 5 || analysisSelection > 0)
{
return (quotes [quoteSelection-1][analysisSelection]);
}
}
}
}
主要类别:
public class Main
{
public static void main (String [] args)
{
new Swing();
}
}
复制粘贴是程序员能做的最糟糕的事情 您的变量是main方法的本地变量,您不能在其他任何地方访问它们。将它们移出方法。如果将它们设置为静态,则可以使用MainProgram.inputQuote等访问它们。但是,静态变量通常是一种糟糕的编码样式 因此,您最好将其与代码一起移动到一个单独的类中(现在我们称之为Worker),并在MainProgram中只执行以下操作
public void main(string[] args) {
Worker worker = new Worker();
CrucibleButtonListener l = new CrucibleButtonListener(Worker);
...
}
在CrucibleButtonListener的构造函数中,您将工作者分配到一个字段,并且可以随时访问该字段
这是一个多一点的类型,但导致了良好的风格和灵活性。找一本好书和/或学习一些好代码
您可以直接使用MainProgram而不是Worker,但我更倾向于最小化main类。我只让它将其他类绑定在一起。顺便说一句,使用一些有意义的名称,而不是“MainProgram”。否则,您将停止调用所有程序,如java主程序1
java主程序2
java MainProgram3
您试图直接将一个不基于对象或类的简单线性控制台程序转换为事件驱动的Swing GUI应用程序,坦率地说,这是行不通的;一方的逻辑不能硬塞进另一方的逻辑。您的第一个任务将是将代码更改为具有一个或多个类的真正的OOPs程序,并将所有用户交互代码与程序逻辑代码分离。一旦你做到了这一点,你将更容易在GUI程序中使用你的代码
附录:在try/catch块中调用getQuotes
try {
String quotes = getQuotes();
g.updateTextField(quotes);
} catch (IOException e1) {
e1.printStackTrace();
// or perhaps better would be to display a JOptionPane telling the user about the error.
}
下面是一个简单的入门解决方案,以编译和运行但不读取任何文件的伪代码的形式。希望OOPuritans会让你使用这个。一旦您跨过这个门槛,您将了解如何使用JTable、在JList中设置selectionModels、使用invokeLater范式等。祝您好运,-M.S
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Crucible extends JPanel implements ActionListener {
private JTextField tf = new JTextField();
private JList list = new JList (new String[] {"Theme", "Character Analysis",
"Significance", "Plot Enhancement", "Speaker"});
private final static String helpfulText =
"This is the GUI version of my aplication that analyzes\n" +
"the quotations received on crucibles and swings. ....",
bNames[] = {"Quit", "Run", "Help"};
public Crucible () {
super (new BorderLayout());
JPanel bp = new JPanel (new GridLayout (1,bNames.length));
for (int i = 0 ; i < bNames.length ; i++) {
JButton b = new JButton (bNames[i]);
b.addActionListener (this);
bp.add (b);
}
add (new JScrollPane (list), "Center");
add (bp, "South");
add (tf, "North");
}
private String getQuotes () {
int quoteSelection,
analysisSelection = list.getSelectedIndex(),
howMany = getLineCount ("CrucibleQuotations.txt");
if (analysisSelection < 0) {
JOptionPane.showMessageDialog (null, "Please select type of analysys",
"Crucible Quotes", JOptionPane.ERROR_MESSAGE);
return "";
}
// Create array based on how many quotes available in the text file
ListModel lm = list.getModel();
String[][] quotes = new String [howMany][1+lm.getSize()];
// Buffered Reader ...
// Populate the array and close the files
// catch IO, FileNotFound, etc Exceptions to return ""
// Some dummy data for now:
for (int i = 0 ; i < howMany ; i++) {
quotes[i][0] = "Quote [" + i + "]";
for (int j = 0 ; j < lm.getSize() ; j++)
quotes[i][j+1] = "(" + (String) lm.getElementAt (j) + ")";
}
// Next Step:
// Display the array with JTable in a JScrollPane,
// get quoteSelection as the selectedRow of JTable
// For now, ask for a quote index in a dialog
String qStr = JOptionPane.showInputDialog ("Please select quote index");
if (qStr == null)
return "";
try {
quoteSelection = Integer.parseInt (qStr) - 1;
if (quoteSelection < 0 || quoteSelection >= howMany)
return "";
return quotes[quoteSelection][0] + " " +
quotes[quoteSelection][analysisSelection];
} catch (NumberFormatException nfe) { }
return "";
}
private int getLineCount (String fileName) {
int howMany = 0;
try {
FileReader fr = new FileReader (fileName);
LineNumberReader ln = new LineNumberReader (fr);
while (ln.readLine() != null) {
howMany++;
}
} catch (FileNotFoundException fnfe) { fnfe.printStackTrace();
} catch (IOException ioex) { ioex.printStackTrace();
}
return howMany;
}
public void actionPerformed (ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals (bNames[0])) System.exit (0);
else if (cmd.equals (bNames[1])) tf.setText (getQuotes());
else
JOptionPane.showMessageDialog (null, helpfulText, "Swing Help",
JOptionPane.INFORMATION_MESSAGE);
}
public static void main (String[] args) {
JFrame cFrame = new JFrame ("Crucible");
cFrame.add (new Crucible());
cFrame.pack();
cFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
cFrame.setVisible (true);
}}
import java.io.*;
导入java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
公共类Crucible扩展JPanel实现ActionListener{
私有JTextField=newjtextfield();
private JList=new JList(新字符串[]{“主题”,“字符分析”,
“意义”、“情节强化”、“说话人”});
私有最终静态字符串helpfulText=
“这是我的应用程序的GUI版本,用于分析\n”+
“在坩埚和秋千上收到的报价……”,
bNames[]={“退出”、“运行”、“帮助”};
公共坩埚(){
超级(新边框布局());
JPanel bp=新JPanel(新网格布局(1,bNames.length));
对于(int i=0;i=多少)
返回“”;
返回引号[quoteSelection][0]+“”+
引号[quoteSelection][analysisSelection];
}catch(NumberFormatException nfe){}
返回“”;
}
私有int getLineCount(字符串文件名){
int多少=0;
试一试{
FileReader fr=新的FileReader(文件名);
LineNumberReader ln=新的LineNumberReader(fr);
while(ln.readLine()!=null){
有多少个++;
}
}catch(FileNotFoundException fnfe){fnfe.printStackTrace();
}catch(IOException ioex){ioex.printStackTrace();
}
返回多少;
}
已执行的公共无效操作(操作事件e){
字符串cmd=e.getActionCommand();
if(cmd.equals(bNames[0])System.exit(0);
else if(cmd.equals(bNames[1])tf.setText(getQuotes());
其他的
JOptionPane.showM
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Crucible extends JPanel implements ActionListener {
private JTextField tf = new JTextField();
private JList list = new JList (new String[] {"Theme", "Character Analysis",
"Significance", "Plot Enhancement", "Speaker"});
private final static String helpfulText =
"This is the GUI version of my aplication that analyzes\n" +
"the quotations received on crucibles and swings. ....",
bNames[] = {"Quit", "Run", "Help"};
public Crucible () {
super (new BorderLayout());
JPanel bp = new JPanel (new GridLayout (1,bNames.length));
for (int i = 0 ; i < bNames.length ; i++) {
JButton b = new JButton (bNames[i]);
b.addActionListener (this);
bp.add (b);
}
add (new JScrollPane (list), "Center");
add (bp, "South");
add (tf, "North");
}
private String getQuotes () {
int quoteSelection,
analysisSelection = list.getSelectedIndex(),
howMany = getLineCount ("CrucibleQuotations.txt");
if (analysisSelection < 0) {
JOptionPane.showMessageDialog (null, "Please select type of analysys",
"Crucible Quotes", JOptionPane.ERROR_MESSAGE);
return "";
}
// Create array based on how many quotes available in the text file
ListModel lm = list.getModel();
String[][] quotes = new String [howMany][1+lm.getSize()];
// Buffered Reader ...
// Populate the array and close the files
// catch IO, FileNotFound, etc Exceptions to return ""
// Some dummy data for now:
for (int i = 0 ; i < howMany ; i++) {
quotes[i][0] = "Quote [" + i + "]";
for (int j = 0 ; j < lm.getSize() ; j++)
quotes[i][j+1] = "(" + (String) lm.getElementAt (j) + ")";
}
// Next Step:
// Display the array with JTable in a JScrollPane,
// get quoteSelection as the selectedRow of JTable
// For now, ask for a quote index in a dialog
String qStr = JOptionPane.showInputDialog ("Please select quote index");
if (qStr == null)
return "";
try {
quoteSelection = Integer.parseInt (qStr) - 1;
if (quoteSelection < 0 || quoteSelection >= howMany)
return "";
return quotes[quoteSelection][0] + " " +
quotes[quoteSelection][analysisSelection];
} catch (NumberFormatException nfe) { }
return "";
}
private int getLineCount (String fileName) {
int howMany = 0;
try {
FileReader fr = new FileReader (fileName);
LineNumberReader ln = new LineNumberReader (fr);
while (ln.readLine() != null) {
howMany++;
}
} catch (FileNotFoundException fnfe) { fnfe.printStackTrace();
} catch (IOException ioex) { ioex.printStackTrace();
}
return howMany;
}
public void actionPerformed (ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals (bNames[0])) System.exit (0);
else if (cmd.equals (bNames[1])) tf.setText (getQuotes());
else
JOptionPane.showMessageDialog (null, helpfulText, "Swing Help",
JOptionPane.INFORMATION_MESSAGE);
}
public static void main (String[] args) {
JFrame cFrame = new JFrame ("Crucible");
cFrame.add (new Crucible());
cFrame.pack();
cFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
cFrame.setVisible (true);
}}