I have developed a program that is counting the number of lines in a file that is shown below
Scanner in=new Scanner(System.in);
System.out.println("Enter the Drive name like C,D,E etc");
String drive=in.next();
System.out.println("Enter the main folder name");
String main_folder=in.next();
File directory=new File(drive+":"+"//"+main_folder+"//");
Map<String, Integer> result = new HashMap<String, Integer>();
//File directory = new File("C:/Test/");
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile()) {
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try {
for (lineCount = 0; scanner.nextLine() != null; lineCount++);
} catch (NoSuchElementException e) {
result.put(file.getName(), lineCount);
} }}
for( Map.Entry<String, Integer> entry:result.entrySet()){
System.out.println(entry.getKey()+" ==> "+entry.getValue());
}
but I was trying to add a swing interface JFilechooser , I want that user should select the particular folder and all the files inside that folder to be get selected and rest above as my code works as it is , Please advise
Please advise for desiging the jfile chooser so that I can integrate my above code.
I have design one more solution that is
package aa;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FileBrowse extends JFrame {
private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(30);
private JButton approve = new JButton("Ok");
public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,80);
setResizable(false);
browseSwing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==browseSwing)
onBrowseSwing();
}});
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(browseSwing);
container.add(textField);
container.add(approve);
//pack();
}
protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}
public void fileRead(String input){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(input);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int count = 0;
int count2 = 0;
//Read File Line By Line
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
count++;
}else{
count2++;
}
}
System.out.println("-------Lines Of COdes-------");
System.out.println("number of lines:" + count);
System.out.println("number of blank lines:" + count2);
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
new FileBrowse().setVisible(true);
}
}
but it chooses the individual files I want that all the files to be get selected inside that folder Test
You could use this code (adapted from here):
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(choosers.getSelectedFile().getAbsolutePath()); //This is where you need to change.
File[] files = directory.listFiles();
for (File file : files)
{
if (file.isFile())
{
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{
for (lineCount = 0; scanner.nextLine() != null; lineCount++)
;
} catch (NoSuchElementException e)
{
result.put(file.getName(), lineCount);
}
}
}
for (Map.Entry<String, Integer> entry : result.entrySet())
{
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
}
This code should replace this section:
Scanner in=new Scanner(System.in);
System.out.println("Enter the Drive name like C,D,E etc");
String drive=in.next();
System.out.println("Enter the main folder name");
String main_folder=in.next();
File directory=new File(drive+":"+"//"+main_folder+"//");
Also, just a recommendation, when working with consoles and system paths, you should ideally use File.seperator. This will automatically provide you with the respective system's path separation character.
As per your edit, in your case you are using the fileChooser.getSelectedFile();. This will only get you the file that the user has selected, as per its name. What you should use is the fileChooser.getSelectedFile().getAbsolutePath() and iterate over the files which are within that same directory (as shown above).
EDIT 2: I use this code to display 2 buttons with their respective event handlers:
public static void main(String args[]) {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit= new JButton("EXIT");
ActionListener actionListenerExitButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Exit Button Was Clicked");
}
};
btnExit.addActionListener(actionListenerExitButton);
JButton btnEnter = new JButton("ENTER");
ActionListener actionListenerEnterButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Enter Button Was Clicked");
}
};
btnEnter.addActionListener(actionListenerEnterButton);
Container contentPane = frame.getContentPane();
contentPane.add(btnExit, BorderLayout.SOUTH);
contentPane.add(btnEnter, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
All that you need to do now is to plug in the code I have provided earlier in the appropriate event handler.
Related
I'm having a problem with my methods for a school assignment which are supposed to load and save String arrays to a file. It seems like it does not save or load properly. For example, I saved a string of "ok" in a file, let's call it x. Then I rerun the app and changed the path to a directory and it read the string "ok" from it even though it wasn't initially saved the directory and the directory shouldn't be allowed anyways. I really don't know how to solve it and I tried to manipulate the code but I do not know what causes it so it's hard to think of a solution.
Some details on my task:
have to use File Output/Input Stream and Object Output/Input Stream
question and answer strings have to be initialized to 0 size if the path is empty/is a dir/ file not found
take answer and question string from textfield, save it to a file and read the existing ones from the file
question and answer string arrays have to be in a separate class
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
public class App2 extends JFrame implements ActionListener {
JPanel mpanel, qpanel, apanel, bpanel, upanel;
JTextField tf1, tf2, tf3;
JButton jb;
JLabel jl1, jl2, jl3;
String path;
public static void main(String[] args) {
App2 object = new App2();
System.out.println("app init/ array size:" + QAData.question.length);
}
App2() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400, 200);
this.setTitle("App2");
mpanel = new JPanel();
this.add(mpanel);
mpanel.setLayout(new GridLayout(4, 1));
qpanel = new JPanel();
mpanel.add(qpanel);
apanel = new JPanel();
mpanel.add(apanel);
upanel = new JPanel();
mpanel.add(upanel);
bpanel = new JPanel();
mpanel.add(bpanel);
jl1 = new JLabel("Question: ");
qpanel.add(jl1);
tf1 = new JTextField(20);
tf1.setHorizontalAlignment(JTextField.LEFT);
qpanel.add(tf1);
tf1.addActionListener(this);
jl2 = new JLabel("Answer: ");
apanel.add(jl2);
tf2 = new JTextField(20);
tf2.setHorizontalAlignment(JTextField.LEFT);
apanel.add(tf2);
tf2.addActionListener(this);
jl3 = new JLabel("Path: ");
upanel.add(jl3);
tf3 = new JTextField(20);
tf3.setHorizontalAlignment(JTextField.LEFT);
upanel.add(tf3);
tf3.addActionListener(this);
jb = new JButton("Update");
jb.setHorizontalAlignment(JButton.CENTER);
bpanel.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tf3)
path = tf3.getText();
if (e.getSource() == jb) {
load();
save();
tf1.setText("");
tf2.setText("");
}
}
void load() {
try {
File file = new File("path");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (!fileIsOk) {
QAData.question = new String[0];
QAData.answer = new String[0];
System.out.println("size 0 applied");
} else {
QAData.question = (String[]) ois.readObject();
QAData.answer = (String[]) ois.readObject();
}
ois.close();
} catch (ClassNotFoundException e) {
System.out.println("No such class found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("I/O exception during the load");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to read has the null value");
e.printStackTrace();
}
}
void save() {
try {
File file = new File("path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (fileIsOk) {
QAData.question = Arrays.copyOf(QAData.question, QAData.question.length + 1);
QAData.question[(QAData.question.length - 1)] = tf1.getText();
QAData.answer = Arrays.copyOf(QAData.answer, QAData.answer.length + 1);
QAData.answer[(QAData.answer.length - 1)] = tf2.getText();
oos.writeObject(QAData.question);
oos.writeObject(QAData.answer);
}
oos.close();
} catch (IOException e) {
System.out.println("I/O exception during the save");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to save has the null value");
e.printStackTrace();
}
}
static class QAData implements Serializable {
static String[] question = new String[0];
static String[] answer = new String[0];
}
}
I am writing a program that "deletes" a line in a text file. How ever It is failing to both delete the original file and rename the new file.
What happens is, it will save the lines I want to save under the file name "temp.txt". However What it should do is delete the original file(TaskList.txt) and then rename temp.txt as TaskList.txt can anyone help? Here is my code:
import java.io.*;
import java.io.File;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
import java.awt.event.*;
class DeleteTask implements ActionListener{
private static Scanner x;
JFrame frame;
JButton deleteButton;
JTextField delete;
JLabel label;
public void completedTask()
{
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setTitle("Delete Task");
delete = new JTextField(10);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
label = new JLabel ("Enter task name");
frame.add(label,BorderLayout.WEST);
frame.add(delete,BorderLayout.CENTER);
frame.add(deleteButton,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String filePath = "TaskList.txt";
String removeTerm= delete.getText();
removeRecord(filePath,removeTerm);
frame.dispose();
}
public static void removeRecord(String filePath, String removeTerm)
{
String tempFile = "temp.txt";
File oldFile = new File(filePath);
File newFile = new File(tempFile);
String id = "" ; String name = "" ; String age = ""; String descript = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filePath));
x.useDelimiter("[,\n]");
while(x.hasNext())
{
id = x.next();
name = x.next();
age = x.next();
descript = x.next();
if(!id.equals(removeTerm))
{
pw.println(id + ", " + name + ", " + age + ", " + descript);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filePath);
newFile.renameTo(dump);
}
catch(Exception E)
{
}
}
}
I'm coding a swing App. Here the tasks are to download the file from a given URL and then get the counts of them. The program works with no issues/errors.
The problem is I've a testarea in my frame, when file 1 is downloaded I want the text area to show downloaded file 1 and when file 2 is done downloaded file 1 and so on...
Currently in my program the message is displayed but all at once. I mean if I've 10 files, it shows.
downloaded file 1
downloaded file 2
.
.
.
.
.
downloaded file 10
But this is shown only after all the 10 files are downloaded. To see if there is any other problem, I've added sysout just below the textarea code. And to my surprise, sysouts are printed 10 times, I mean each time a file is processed, this is triggered, but the textarea is appended with all the data at a time.
Below are my codes.
GuiForPDFs
import java.awt.BorderLayout;
public class GuiForPDFs extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiForPDFs frame = new GuiForPDFs();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
FileDownloadTest downloadTest = new FileDownloadTest();
public GuiForPDFs() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(10, 106, 516, 203);
contentPane.add(textArea);
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
downloadTest.fileDownloadTest(srcTextField.getText(), textArea);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
FileDownloadTest
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JTextArea;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileDownloadTest {
public void fileDownloadTest(String src, JTextArea textArea) throws IOException, InterruptedException {
String path = src;
FileInputStream fin = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fin);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
System.out.println("rows are " + rows);
XSSFCell cell;
// Make sure that this directory exists
String dirName = src.substring(0, src.lastIndexOf("\\"));
File f = new File(dirName);
if (!f.exists()) {
f.mkdir();
}
System.out.println(f.getAbsolutePath() + " is Directory Name " + src + " is the file");
for (int i = 1; i < rows; i++) {
XSSFCell url = sheet.getRow(i).getCell(0);
String URLString = url.toString();
cell = sheet.getRow(i).getCell(7);
String fileName = URLString.substring(URLString.lastIndexOf("/") + 1);
int pageNumbers = downloadFiles(dirName, url.toString().replace("http", "https"));
if (cell == null) {
cell = sheet.getRow(i).createCell(1);
}
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(pageNumbers);
FileOutputStream fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
textArea.append("downloaded " + fileName + "\n");
System.out.println("Done");
}
workbook.close();
fin.close();
}
public static int downloadFiles(String dirName, String urlString) {
System.out.println("Downloading \'" + urlString + "\' PDF document...");
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
System.out.println(fileName + " is file name");
try {
saveFileFromUrlWithJavaIO(dirName + "\\" + fileName, urlString);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Downloaded \'" + urlString + "\' PDF document...");
int pageNumber = 0;
try {
pageNumber = getNoOfPages(dirName + "\\" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
return pageNumber;
}
public static int getNoOfPages(String fileName) throws IOException {
PDDocument document = PDDocument.load(new File(fileName));
int numberOfPages = document.getNumberOfPages();
return numberOfPages;
}
public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(fileUrl).openStream());
fout = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
public static void saveFileFromUrlWithCommonsIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
}
please let me know How can I fix this.
Thanks
The above comments are correct, you are on the EDT when adding text to the TextArea. This is because you are calling downloadTest.fileDownloadTest from the dNcButton ActionListener implementation.
It's good practice to get off the EDT is you have a long running operation to perform, and downloading a file is often given as as example of the sort of thing you don't want to do on the EDT.
There are lots of resources online as to how to get off the EDT, including many on this great site;
On Event Dispatch Thread---want to get off of it
Make thread run on non EDT (event dispatch thread) thread from EDT
As with the other comments, you need to keep only UI related tasks on the EDT. Otherwise if your user is downloading 100 files the UI will lock up until the download task is finished. SwingWorker is the perfect class to do this for Swing applications. Here is a quick example:
// Run your FileDownloadTest inside a SwingWorker
// or have the class extend SwingWorker
new SwingWorker<Void, String>() {
#Override
protected Void doInBackground() throws Exception {
//Perform downloading here (done off the EDT)
//Call publish(downloadedFileName) to be sent to the process method()
return null;
}
#Override
protected void process(List<String> chunks) {
// Modify textArea (done on the EDT)
StringBuilder downloadedFiles = new StringBuilder();
for (String fileName : chunks) {
downloadedFiles.append("downloaded" + fileName + "\n");
}
textArea.setText(downloadedFiles);
}
#Override
protected void done() {
//Anything you want to happen after doInBackground() finishes
}
}.execute();
ok im having trouble passing arraylists between classes and im geting a nullPointer exception when i take the constructor out of the object creating in the main. i cant get the arraylist around while also being succesfully modified, or filled with the files it checks for in the directory, keep in mind im new at stackOverflow and programming in general, go easy on me please.
this is the main class
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
import javazoom.jl.player.*;
import org.apache.commons.io.IOUtils;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class StreamAudio
{
public static TextArea textArea;
public static ArrayList<File> files;
public StreamAudio()
{
ArrayList<File> files = new ArrayList<File>();
File folder = new File("C:\\Users\\hunter\\Desktop\\code\\StreamAudio\\Music");
File[] allFiles = folder.listFiles();
if(folder.isDirectory())
{
for (File file : allFiles)
{
if (file.isFile())
{
files.add(file);
}
}
}
int count = 0;
for(File i : files)
{
count++;
textArea.append(files.get(count - 1).getName()+"\n");
}
}
public static void main(String[] args)
{
MusicGUI gooey = new MusicGUI(ArrayList<File> files);
}
}
and this is the GUI class, can i also have some tips on organizing everything, im so messy
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
import javazoom.jl.player.*;
import org.apache.commons.io.IOUtils;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MusicGUI{
public static TextArea textArea;
public static ArrayList<File> files;
public MusicGUI(ArrayList<File> t)
{
files = t;
}
public MusicGUI()
{
JFrame frame = new JFrame("FrostMusic");
JButton next = new JButton("Next");
JPanel panel = new JPanel();
TextArea textArea = new TextArea("", 15, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(false);
//frame properties
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(650,450);
frame.setBackground(Color.white);
///////////////////////// MUSIC CODE /////////////////////////////
String path = files.get(1).getPath();
File song = new File(path);
String name = song.getName();
name.replace(".mp3", "");
//////////////////////////////////////////////////////////////////////
JLabel label = new JLabel("Now Playing "+name);
//panel properties
panel.setBackground(Color.white);
//play button
JButton play = new JButton("Play");
try
{
FileInputStream fis = new FileInputStream(song);
BufferedInputStream bis = new BufferedInputStream(fis);
String filename = song.getName();
Player player = new Player(bis);
play.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent jh)
{
try
{
player.play();
}catch(Exception e){}
}
});
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent jk)
{
try
{
player.close();
}catch(Exception e){}
}
});
}catch(Exception e){}
panel.add(play);
panel.add(textArea);
panel.add(label);
panel.add(next);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Look at this line in the StreamAudio class inside the main method
MusicGUI gooey = new MusicGUI(ArrayList<File> files);
You cannot "declare" a variable inside the call to a constructor. Change it the following and it should work:
MusicGUI gooey = new MusicGUI(files);
You can only pass a reference to an object or a variable or literal as a parameter within a method or a constructor.
Update
I'm updating some code here. Try to see if this works for you.
Here's the StreamAudio class:
public class StreamAudio {
private List<File> files;
public StreamAudio() {
files = new ArrayList<File>();
File folder = new File("/Users/ananth/Music/Songs");
File[] allFiles = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".mp3");
}
});
if (folder.isDirectory()) {
for (File file : allFiles) {
if (file.isFile()) {
files.add(file);
}
}
}
System.out.println(files);
}
public List<File> getFiles() {
return files;
}
public static void main(String[] args) {
StreamAudio streamAudio = new StreamAudio();
MusicGUI gooey = new MusicGUI(streamAudio.getFiles());
gooey.showUI();
}
}
And here's the MusicGUI class:
public class MusicGUI {
private TextArea textArea;
private List<File> files;
private JPanel panel;
private Player player;
private int index = -1;
public MusicGUI(List<File> t) {
files = t;
init();
}
public void init() {
panel = new JPanel();
JButton next = new JButton("Next");
textArea = new TextArea("", 15, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(false);
JLabel label = new JLabel("Now Playing: ");
// panel properties
panel.setBackground(Color.white);
// play button
JButton play = new JButton("Play");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent jh) {
String path = files.get(++index).getPath();
///////////////////////// MUSIC CODE ///////////////////////////////
System.out.println("path: " + path);
File song = new File(path);
String name = song.getName();
name.replace(".mp3", "");
label.setText("Now Playing " + name);
try {
FileInputStream fis = new FileInputStream(song);
BufferedInputStream bis = new BufferedInputStream(fis);
Player player = new Player(bis);
try {
player.play();
} catch (Exception e) {
}
} catch (Exception e) {
System.out.println(e);
}
//////////////////////////////////////////////////////////////////////
}
});
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent jk) {
try {
player.close();
} catch (Exception e) {
}
if(index==files.size()){
index = -1;
}
String path = files.get(++index).getPath();
System.out.println("path: " + path);
File song = new File(path);
String name = song.getName();
name.replace(".mp3", "");
label.setText("Now Playing " + name);
}
});
panel.add(play);
panel.add(scrollPane);
panel.add(label);
panel.add(next);
}
public void showUI() {
JFrame frame = new JFrame("FrostMusic");
// frame properties
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(650, 450);
frame.setBackground(Color.white);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
My program right now needs to load up two text files and I'm sorting them by string of words. JcomboxBox is supposed to allow you to select int between 1 and 4 (the size of the string to compare)
so 2 would return "I am" whereas 1 would return "I"
I'm getting null pointed exception and I have never used combo boxes before. Please help/
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
private JLabel label;
private JButton load, go,go2;
private CountList<SuperString> words;
private String filename;
private int width = 400;
private int height = 600;
private TextArea textarea,textarea2;
Scanner scan;
public Lab8()
{
Integer [] select = {1,2,3,4};
JComboBox input = new JComboBox(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File");
go2 = new JButton("Select 2nd Text File");
label = new JLabel("How many sequenced words would you like to analyze? (Must be => 1)" );
input.setSelectedIndex(0);
ButtonListener listener = new ButtonListener();
go.addActionListener(listener);
go2.addActionListener(listener);
input.addActionListener(listener);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(900,600));
text.add(textarea);
text.add(textarea2);
add(input);
add(go);
add(go2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex();
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
// System.out.println(ss);
words.add(ss );
}
scan.close();
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea.append(" "+word+"\n");
}
}
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
words.add(ss );
}
scan.close();
textarea2.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea2.append(" "+word+"\n");
}
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 8");
frame.getContentPane().add(new Lab8());
frame.pack();
frame.setVisible(true);
}
}
You're re-declaring your JComboBox variable in the constructor and thus shadowing the field found in the class. By doing this the field remains null:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input; // this guy remains null
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// the line below initializes a local input variable.
// this variable is visible only inside of the constructor
JComboBox input = new JComboBox(select); // ***** here ****
Don't re-declare the variable:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// JComboBox input = new JComboBox(select); // ***** here ****
input = new JComboBox(select); // ***** note difference? *****