Java Swing文本编辑器引发NullPointerException
好吧。。。我从Java开始,现在已经开始使用SwingGUI。在我尝试处理文件输入和输出之前,一切都很顺利Java Swing文本编辑器引发NullPointerException,java,swing,nullpointerexception,Java,Swing,Nullpointerexception,好吧。。。我从Java开始,现在已经开始使用SwingGUI。在我尝试处理文件输入和输出之前,一切都很顺利 /* ** 'Gooey' GUI in Swing with Java. ** v3 With File Opening */ import javax.swing.*; // Import the swing library import javax.swing.filechooser.*; import java.awt.*;
/*
** 'Gooey' GUI in Swing with Java.
** v3 With File Opening
*/
import javax.swing.*; // Import the swing library
import javax.swing.filechooser.*;
import java.awt.*; // Import library
import java.awt.event.*; // Import event handling
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
class gooey implements ActionListener {
JFrame myFrame = null; // Create a JFrame, don't fill it
JEditorPane myPane = null;
String fileName = "myJava.java";
Font editorFont = new Font("Consolas",Font.PLAIN, 12);
public static void main(String[] args) {
(new gooey()).test(); // Create a GUI and 'test' it
}
private void test() { // Test run of a gooey
// FRAME
//////////
System.out.println("Creating myFrame..."); // Debug stuff
myFrame = new JFrame("Gooey"); // Create a new JFrame (window)
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Set it so that when the [X] button is clicked, the app exits
myFrame.setSize(400,300); // Set the size of 400x300px (WxH)
System.out.println("myFrame created!"); // Debug stuff
// MENU BAR
/////////////
System.out.println("Creating menuBar..."); // Debug stuff
JMenuBar myBar = new JMenuBar(); // Create a new JMenuBar called myBar
System.out.println("Done!"); // More debug stuff
System.out.println("Creating JButtons...");
JButton openButton = new JButton("Open"); // Create a button named openButton
openButton.addActionListener(this);
JButton saveButton = new JButton("Save"); // Create a button named saveButton
saveButton.addActionListener(this);
JButton quitButton = new JButton("Quit"); // Create a button named quitButton
quitButton.addActionListener(this); // Add an actionListener
myBar.add(openButton); // Add the buttons to the menubar
myBar.add(saveButton);
myBar.add(quitButton);
System.out.println("Done!"); // Even more debug stuff
// EDITOR PANE
////////////////
System.out.println("Creating myPane..."); // EVEN MOAR DEBUG
JEditorPane myPane = new JEditorPane(); // Create a new JEditorPane called myPane
myPane.setContentType("text/plain"); // Set it so that it can only edit plain text
myPane.setFont(editorFont);
myPane.setText(
"This is a JEditorPane."
+"\nIt can display text/rich text/HTML that can be edited."); // Set the starting text of myPane to that
System.out.println("Done!"); // And yet more debug stuff
// RUNNING IT
///////////////
System.out.println("Running it all..."); // DEBUG
myFrame.setJMenuBar(myBar); // Set the frame's menu bar to myBar
myFrame.setContentPane(myPane); // Set it so that the content in myFrame is myPane
myFrame.setVisible(true); // Make myFrame visible
System.out.println("myFrame has been created!");
}
// ACTION LISTENERS
/////////////////////
public void actionPerformed(ActionEvent e) {
// Basically, every time an action is performed (e.g. left mouse click)
// on something with an actionListener attached to it, we can call this
// method.
if (e.getActionCommand()=="Quit") System.exit(0); // If the string of the thing we're listening to was "quit", exit the program!
else {
// CREATE A FILE CHOOSER
/////////////////////////
JFileChooser myFileChoose = new JFileChooser();
myFileChoose.setCurrentDirectory(new File("C:"));
myFileChoose.setSelectedFile(new File(fileName));
myFileChoose.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter myFilter = new FileNameExtensionFilter(".java files","java");
myFileChoose.setFileFilter(myFilter);
try {
// OPEN COMMAND
/////////////////
if (e.getActionCommand()=="Open") {
int r = myFileChoose.showOpenDialog(myPane); // Create a file chooser
if (r == JFileChooser.APPROVE_OPTION) { // If the user has selected a file
File selectedFile = myFileChoose.getSelectedFile(); // Find that file
fileName = selectedFile.getName(); // Get it's name and store it in a variable
FileInputStream fis = new FileInputStream(selectedFile); // Stream the input
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); // Read said stream
char[] buffer = new char[1024]; // Create a buffer
int n = isr.read(buffer); // Read from the input and buffer
String text = new String(buffer, 0, n); // Put into string
myPane.setText(text); // Put into JEditorPane
isr.close();
}
// SAVE COMMAND
/////////////////
} else if (e.getActionCommand()=="Save") {
int r = myFileChoose.showOpenDialog(myPane);
if (r == JFileChooser.APPROVE_OPTION) { // If the user has selected a file
File selectedFile = myFileChoose.getSelectedFile(); // Find that file
fileName = selectedFile.getName(); // Get it's name and store it in a variable
FileOutputStream fos = new FileOutputStream(selectedFile); // Stream the input
OutputStreamWriter osr = new OutputStreamWriter(fos, Charset.forName("UTF-8")); // Read said stream
osr.write(myPane.getText());
osr.close();
}
}
} catch (Exception q) {
q.printStackTrace();
}
}
}
}
我尝试让它工作,但是当我尝试通过JFileChooser打开或保存文件时,它会显示以下内容:
打开文件错误:
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:120)
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:132)
gooey.actionPerformed处的java.lang.NullPointerException(gooey.java:120)
保存文件错误:
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:120)
java.lang.NullPointerException at gooey.actionPerformed(gooey.java:132)
gooey.actionPerformed处的java.lang.NullPointerException(gooey.java:132)
变量
myPane
未初始化(null
)。这会导致出现NullPointerException
创建一个新的JEditorPane(第65行附近),但将其分配给一个局部变量,因此同名的类成员仍然是null
(并且actionPerformed
使用类成员变量myPane
)。换乘65号线
JEditorPane myPane = new JEditorPane();
到
请在源代码中标记第120行和第132行。您需要检查文件是否存在,文件是否已存在,这将检查文件是否存在,如果不存在,您将得到一个空指针,如果要使用文件IO,最好检查以确保其退出。如果(file.exists()){}也可以使用.equals()检查
字符串
s的相等性,而不是=
@asgs:在这种特定的情况下,它会起作用,因为动作命令是用字符串文本设置和检查的,字符串文本保证会被插入,但一般来说:是的,总是这样做!