![](/img/trans.png)
[英]How can I use JPopupMenu actionlistener inside a class constructor?
[英]Can I use BufferedReader and create an array inside actionListener class?
我創建了一個actionListener類。 在actionPerformed方法中,我想運行一個代碼。 此代碼涉及從多個文本文件導入數據,並將其存儲在2D數組中。 然后它將打印出框架中的引號列表。 然后它將打印出5個分析,並讓用戶選擇哪個分析。 但是,我目前仍停留在IOException上。 另外,某些代碼狀態給出錯誤“無法訪問的代碼”。 那是什么意思 以下是我的actionListener類的代碼
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]);
}
}
}
}
這是秋千課。 它只包含一個按鈕,我似乎無法使其工作。
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));
}
}
主類:
public class Main
{
public static void main (String [] args)
{
new Swing();
}
}
您正在嘗試將不基於對象或類的簡單化線性控制台程序直接轉換為事件驅動的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.
}
復制和粘貼是程序員可以做的最糟糕的事情。
您的變量對於方法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 MainProgram1
java MainProgram2
java MainProgram3
這是一個簡單的解決方案,以偽代碼的形式進行編譯和運行,但不讀取任何文件。 希望OOPuritans可以讓您使用。 超過此閾值后,您將了解如何使用JTable,在JList中設置selectionModels,使用invokeLater范例等。祝您好運-MS
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);
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.