可以帮忙看看是哪里出错了吗

nimifur 2018-12-19 10:03:24
package cn.itcast.swing.demo;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.io.File;
import java.awt.event.ActionEvent;

public class MyWindow extends JFrame {

private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private JPanel contentPane;
private JTextField textField;
private JButton button;
private JTextArea textArea;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyWindow frame = new MyWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public MyWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

textField = new JTextField();
textField.setBounds(10, 10, 254, 30);
contentPane.add(textField);
textField.setColumns(10);

JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonActionPerformed(e);
}
});
btnNewButton.setBounds(302, 10, 93, 30);
contentPane.add(btnNewButton);

JTextArea textArea = new JTextArea();
textArea.setBounds(10, 53, 383, 198);
contentPane.add(textArea);
}

private void buttonActionPerformed(ActionEvent e) {
showDir();
}

private void showDir() {

/*
* 通过点击按钮获取文本框中目录,
* 将目录中的内容显示在文本区域中。
*/

String dir_str = textField.getText();
File dir = new File(dir_str);

if(dir.exists() && dir.isDirectory()){
textArea.setText("");
String[] names = dir.list();

for(String name : names){
textArea.append(name+LINE_SEPARATOR);
}
}
}

}





一直提示这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at cn.itcast.swing.demo.MyWindow.showDir(MyWindow.java:85)
at cn.itcast.swing.demo.MyWindow.buttonActionPerformed(MyWindow.java:71)
at cn.itcast.swing.demo.MyWindow.access$0(MyWindow.java:70)
at cn.itcast.swing.demo.MyWindow$2.actionPerformed(MyWindow.java:59)
...全文
371 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ekidohna 2018-12-22
  • 打赏
  • 举报
回复
你的控件new了么?
Albert Yang 2018-12-20
  • 打赏
  • 举报
回复
传智的代码,大兄弟要想学东西个人建议还是要多敲代码呀
_Ricky_ 2018-12-19
  • 打赏
  • 举报
回复
textArea没有实例化 ,把btnNewButton.addActionListener(..... 这段代码移到65行下面去

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧