Can I use BufferedReader and create an array inside actionListener class?
I've created an actionListener class. in the actionPerformed method, i would like run a code. This code involves importing data from multiple text files, and store them in a 2D array. Then it will print out a list of quotes in the frame. Then it will print out the 5 analysis and let the user choose which one. However, i am currently stuck with the IOException. Plus, some code states gives an error "unreachable code." What does that means? Below is the code for my actionListener class
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] = inputPlotE开发者_如何学JAVAnhancement.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]);
}
}
}
}
Here is the swing class. It only contains a button, which i can't seem to make it work.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.*;
public class Swing
{
private JLabel label;
public Swing()
{
JFrame frame = new JFrame ("FRAME SAMPLE");
frame.setSize(500, 500);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JButton cButton = new JButton("The Crucible");//The JButton name.
frame.add(cButton);//Add the button to the JFrame.
cButton.addActionListener(new CrucibleButtonListener(this));
}
}
Main Class:
public class Main
{
public static void main (String [] args)
{
new Swing();
}
}
You are trying to directly convert a simplistic linear console program that is not based on objects or classes into an event-driven Swing GUI application, and to be blunt, this will never work; the logic of one cannot be shoehorned into the logic of the other. Your first task will be to change your code into a true OOPs program with one or more classes, and to separate all user interaction code from program logic code. Once you've done that, you will much more easily be able to use your code in a GUI program.
addendum: calling getQuotes in try/catch block
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.
}
Copy & paste is the single worst thing a programmer can do.
Your variables are local for the method main, you can't access them anywhere else. Move them out of the method. If you make them static, then you can access them using MainProgram.inputQuote, etc. However, static variables are in general a bad coding style.
So you'd better move it all into a separate class (let's call it Worker for now) together with the code, and do only the following in MainProgram
public void main(string[] args) {
Worker worker = new Worker();
CrucibleButtonListener l = new CrucibleButtonListener(Worker);
...
}
In the constructor of CrucibleButtonListener you assign the worker to a field and can access it anytime.
This is a bit more to type, but leads to a good style and flexibility. Get a good book and/or study some good code.
You could use MainProgram directly instead of Worker, but I strongly prefer to minimize the main class. I only let it bind the other classes together. Btw., use some meaningful name instead of "MainProgram". Otherwise you'll end calling all you program like
java MainProgram1
java MainProgram2
java MainProgram3
Here is a simple solution to get started, in the form of a pseudocode that compiles and runs, but doesnt read any file. Hopefully the OOPuritans will let you use this. Once you cross this threshold, you will figure out how to use JTable, set selectionModels in JList, Use the invokeLater paradigm, etc. Good wishes, - 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);
}}
精彩评论