I am a beginner with Java and currently i am developing a SWING JAVA app.
What does this app. do.
If an user tipes some numbers (let' say) [input], then the app. connects to the specific website and searches in there (url : http://www.example.com/search?text=[user's input]). The output (i want so) will be if user's input could be found or not (with help of boolean true/false and url connection). Just this.
I already read A java program to search in a certain website, but i dont want to use crawler. Seems to hard for me.
Also, i think, i dont need to parse a website, because if the user's input exists it will return what the user is looking for. So programs like jsoup are not needed.
My Question is this: What meathod should i use. How to solve this problem?
Basically, how to put user's input into the website URL and then click with swing button for search on that website
EDIT:
so a few points.
The user input should return possitive result , such as this e.g. "example.com/descriptionOfProduct.k973311" where 97311 is a specific ID of that product. It has alsways 6 numbers. And the letter "k." is there always too.
If the user input doesnt exists then 404. If it does then see above. AND the descriptionOfProduct is always a completely different. And it' absolutely random.
I use httpclient apache.
About that specific website : no api for search and it's e-commerce (eshop).
Here is my code, which is not finished because of this search functionality.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
public class Connection {
/**
* #param args
* #throws URISyntaxException
*/
#SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) throws URISyntaxException {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.example.cz");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
connection.getInputStream();
System.out.println("Connected to website");
// do something with the input stream here
// InputStream error = ((HttpURLConnection) connection).getErrorStream();
// # means special ID to understand where & what is wrong
} catch (MalformedURLException e1) {
e1.printStackTrace();
System.err.println("Something's wrong #1");
} catch (IOException e1) {
e1.printStackTrace();
System.err.println("Something's wrong #2");
} finally {
if(null != connection) { connection.disconnect(); }
}
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.example.com").setPath("/search")
.setParameter("text", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
and Here is the swing app
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
/**
* #author John Malc
* #version
*
*/
public class app {
private JFrame frame;
private JTextField textField;
private JButton btnSearch;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
app window = new app();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public app() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getTextField(), BorderLayout.NORTH);
frame.getContentPane().add(getBtnSearch(), BorderLayout.SOUTH);
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setColumns(10);
}
return textField;
}
private JButton getBtnSearch() {
if (btnSearch == null) {
btnSearch = new JButton("search");
}
return btnSearch;
}
}
Once you have the remote file you could always do something like this Java Grep Library
Basically, you need to get the remote file and search through the file for a string that matches your user input.
Related
I am trying to run a multi-user chat client java programme as part of another java programme.
How do I implement it in such a way that I can open up the chat client from the main programme? I have attempted to start it using ProcessBuilder but it causes the whole programme to crash.
The class to start the chat client and the client client itself is shown below respectively
--------------------- Class to start chat client ---------------------
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class ChatCommand extends Command {
public static final String COMMAND_WORD = "chat";
public static final String MESSAGE_USAGE = COMMAND_WORD + ":\n" + "Opens up a separate chat programme\n\t"
+ "Example: " + COMMAND_WORD;
public static final String MESSAGE_SUCCESS = "Initialising chat!";
public static void main(String[] args) {
new ChatCommand();
}
public ChatCommand() {
try {
int result = compile("seedu.addressbook.communications.ChatClient");
System.out.println("javac returned " + result);
result = run("seedu.addressbook.communications.ChatClient");
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
}
public int run(String clazz) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", clazz);
pb.redirectError();
pb.directory(new File("src"));
Process p = pb.start();
InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
consumer.start();
int result = p.waitFor();
consumer.join();
System.out.println(consumer.getOutput());
return result;
}
public int compile(String file) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("javac", file);
pb.redirectError();
pb.directory(new File("src"));
Process p = pb.start();
InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
consumer.start();
int result = p.waitFor();
consumer.join();
System.out.println(consumer.getOutput());
return result;
}
public class InputStreamConsumer extends Thread {
private InputStream is;
private IOException exp;
private StringBuilder output;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
#Override
public void run() {
int in = -1;
output = new StringBuilder(64);
try {
while ((in = is.read()) != -1) {
output.append((char) in);
}
} catch (IOException ex) {
ex.printStackTrace();
exp = ex;
}
}
public StringBuilder getOutput() {
return output;
}
public IOException getException() {
return exp;
}
}
public CommandResult execute() {
ChatClient cc = new ChatClient();
try {
cc.main(new String[]{"a", "b"});
} catch (Exception e) {
System.out.println("aaa");
}
commandHistory.addHistory(COMMAND_WORD);
return new CommandResult(MESSAGE_SUCCESS);
}
}
--------------------------- Chat Client --------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/* A simple Swing-based client for the chat server. Graphically
* it is a frame with a text field for entering messages and a
* textarea to see the whole dialog.
*
* The client follows the Chat Protocol which is as follows.
* When the server sends "SUBMITNAME" the client replies with the
* desired screen name. The server will keep sending "SUBMITNAME"
* requests as long as the client submits screen names that are
* already in use. When the server sends a line beginning
* with "NAMEACCEPTED" the client is now allowed to start
* sending the server arbitrary strings to be broadcast to all
* chatters connected to the server. When the server sends a
* line beginning with "MESSAGE " then all characters following
* this string should be displayed in its message area.
*/
public class ChatClient {
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame("MediChat");
private JTextField textField = new JTextField(40);
private JTextArea messageArea = new JTextArea(8, 40);
/* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Return in the
* listener sends the textfield contents to the server. Note
* however that the textfield is initially NOT editable, and
* only becomes editable AFTER the client receives the NAMEACCEPTED
* message from the server.
*/
public ChatClient() {
// Layout GUI
textField.setEditable(false);
messageArea.setEditable(false);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
// Add Listeners
textField.addActionListener(new ActionListener() {
/* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
* the text area in preparation for the next message.
*/
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
}
/* Prompt for and return the address of the server.
*/
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"Welcome to MediChat!",
JOptionPane.QUESTION_MESSAGE);
}
/* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
/* Connects to the server then enters the processing loop.
*/
private void run() throws IOException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
}
/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
You are seriously overcomplicating things:
don't make compiling your client code part of any Java class. Define a project setup in your IDE, or on the command line using gradle for example. Then use that to separately compile your classes whenever you change something. Running javac in your classes manually is seriously wrong!
and then, just make sure that all compiled class files are available on the classpath of your jvm. Don't bother to use reflection or anything else that is based on class names as raw strings.
most importantly: you use other classes by instantiating objects directly. The main method should only be used when you want to run a class standalone from the command line!
so instead of using class names as string, simply normally import the classes to use, and use new to create objects of them.
beyond that, separate your concerns. The client is the client, the server is the server. It is absolutely not a good idea to have the server start client instances. Meaning: rather create a third class, maybe called SetupTestEnvironment that first starts the server and a few clients for testing purposes.
So I created a message console. And used append to display messages and it works perfectly by running java -jar JavaProgram, however when I double click on it the application runs and I see the JFrame but nothing is displayed. The text that I did append is not present.
By the way, double clicking it on windows does display the message output but on my linux system nothing is displayed.
I'm running the same version of java on each machine.
Code Below:
package pdfCounter;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static JTextArea textComponent;
public static int count;
public static void main(String args[]) {
try {
JFrame somePanel = new JFrame();
somePanel.add(new JLabel(" Message Console"), BorderLayout.NORTH);
textComponent = new JTextArea(5, 10);
somePanel.setVisible(true);
somePanel.setSize(900, 300);
somePanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
somePanel.add(new JScrollPane(textComponent));
pdfCounter.MessageConsole mc = new pdfCounter.MessageConsole(textComponent);
mc.redirectOut(null, System.out);
mc.redirectErr(Color.RED, null);
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
File root = new File(s);
count = 0;
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext(); ) {
try {
File file = (File) iterator.next();
if (file.getName().endsWith(".pdf")) {
String absoluteFile = file.getAbsolutePath();
append(absoluteFile);
PDDocument doc = PDDocument.load(new File(file.getAbsolutePath()));
count = doc.getNumberOfPages() + count;
doc.close();
}
} catch (Exception e) {
continue;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
try (PrintStream out = new PrintStream(new FileOutputStream("NumberOfPages.txt"))) {
out.print(count);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void append(String absolutePath) {
textComponent.append(absolutePath + "\n");
}
}
when it gets to the `append(absoluteFile); part thats where the problem lies as it only appends on windows not linux.
UPDATE: I figured that opening it from a different file manager with double click, makes it work. With Nautilus is does not open, even when i choose to run it with java 8 or 9. Opening it with thunar(Different file manager) makes it work no problem with double clicking it. Both are set to run with java 9. I think it has something to do with folder permissions because if i run nautilus as root user, it works when double clicking.
I'm looking for a simple way to open a .txt file, modify it and read in real-time the changes applied on it.
I created a login panel, with two JTextField where user inserts ID/pass.
I want to implement a change password method, so I need to open the .txt file, delete the old password and write the new one (or overwrite). Then I have to read again the file to update the password.
That's the panel's code:
import static java.awt.Color.WHITE;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.JTextField;
import linteati_ced.GUI.frame.MainFrame;
import linteati_ced.HotArea;
import static linteati_ced.utils.Constants.*;
import linteati_ced.utils.Resources;
public class LoginPanel extends JPanel {
private MainFrame mf;
private BufferedImage background;
private FileReader file;
private BufferedReader reader;
private JTextField userArea, passwordArea;
private String user, password;
private HotArea confirm;
private HotArea exit;
private String message;
private Thread dialogue;
private String code;
public LoginPanel(MainFrame mainFrame) throws FileNotFoundException, IOException {
this.setSize(PANEL_X, PANEL_Y);
this.setLayout(null);
this.mf = mainFrame;
this.background = Resources.getImage(BACKGROUND_LOGIN);
this.message = DEFAULT_MESSAGE;
this.confirm = new HotArea(1178, 922, 60, 60);
this.exit = new HotArea(1178, 25, 60, 60);
this.file = new FileReader(Resources.extract(LOGIN));
this.reader = new BufferedReader(file);
this.userArea = new JTextField("");
this.userArea.setBounds(600, 460, 200, 30);
this.userArea.setFont(new Font("Arial", 0, 24));
this.passwordArea = new JTextField("");
this.passwordArea.setBounds(600, 550, 200, 30);
this.passwordArea.setFont(new Font("Arial", 0, 24));
this.add(this.userArea);
this.add(this.passwordArea);
try {
this.user = reader.readLine();
this.password = reader.readLine();
this.code = reader.readLine();
System.err.println(this.user);
System.err.println(this.password);
} catch (IOException ex) {
}
file.close();
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (confirm.isClicked(e)) {
if (user.equals(userArea.getText()) && password.equals(passwordArea.getText())) {
mf.log_in();
} else {
System.out.println("Error");
message = ERROR_MESSAGE;
dialogue = new Thread(new MessageDialogue());
dialogue.start();
repaint();
}
}
if (exit.isClicked(e)) {
System.exit(0);
}
}
});
}
public String getCode() {
return this.code;
}
public void resetTextField() {
this.userArea.setText("");
this.passwordArea.setText("");
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(background, 0, 0, null);
g.setColor(WHITE);
g.setFont(new Font("Arial", 0, 22));
g.drawString(message, 560, 660);
}
private class MessageDialogue implements Runnable {
#Override
public void run() {
try {
Thread.sleep(1500);
} catch (InterruptedException ex) {
}
message = DEFAULT_MESSAGE;
repaint();
}
}
}
These are the contents of the file.txt:
user
password
In your context:
Path path = Paths.get("... .txt");
List<String> = Files.readAllLines(path, StandardCharsets.UTF_8);
user = lines.get(0);
password = lines.get(1);
code = lines.get(2);
List<String> lines = new LinkedList<>();
Collections.addAll(lines, user, password, code);
Files.write(path, lines, StandardCharsets.UTF_8);
You could also use .properties with key=value pairs, with a variant in XML form.
If you think of later changing your software with a new format, maybe a version number in the data would be nice too.
When we are reading our file, we generally use String to store the contents of a file, but the problem is Strings are immutable that is they cannot be edited, but what you want to do could be done in this way :
When writing your password in a file try to write it in a separate one for the
sake of simplicity.
Then read that content and store it in a String variable.
Use replace method to change it.
and then rewrite that modified String on your file again.
One way to do this is to read the line of text from the file and, since you are using space delineation, split the string into an array using string.split(" "). Update the password in string[1], reform the string as username password and write it to the file using `FileOutputString(..., false) to overwrite the contents.
If you planned to leave the file open for periodic updates as needed, you could utilize a RandomAccessFile which maintains a pointer to the last seek and simply overwrite the password using ' ' to mask previous characters left behind from the previous password.
Either way, this is my suggestion but, as others pointed out already, for both security reasons and ease of maintenance, utilizing a database is far easier. Where I worked, I had access to just such a database and was recently required to encrypt the passwords in the table. This may be a desire of yours as well using cryptography.
I've tried googling the web but every question seems to address web development. I'm simply wondering if it is even possible to fetch data from internet (game results and in game events) that is updated every second ,or every 10 second and so on ,from a website that's not mine and to display it in a Java desktop client with the Swing library interface? And if yes, what is the best method?
ThankYou
Yes, you can do it. You should use java.net package to work with network.
Data fetching depends on the site from which you are going to fetch data, for example:
If site have API, like Stack Overflow, you should use it.
If data is presented on the page, you can use parser like jsoup (if page is html, of course)
I get stock data when requested, rather than on a timer, but you can look at my code and see how I get the stock data.
Here's what the JPanel looks like. It's the panel on the right.
This is the HistoricalDataRunnable class.
package com.ggl.stock.picker.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.SwingUtilities;
import com.ggl.stock.picker.model.Company;
import com.ggl.stock.picker.model.StockDay;
import com.ggl.stock.picker.model.StockHistory;
import com.ggl.stock.picker.model.StockPickerModel;
import com.ggl.stock.picker.view.StockPickerFrame;
public class HistoricalDataRunnable implements Runnable {
private static final String URLString =
"http://www.google.com/finance/historical?output=csv&q=";
private Company company;
private StockPickerFrame frame;
private StockPickerModel model;
public HistoricalDataRunnable(StockPickerFrame frame,
StockPickerModel model, Company company) {
this.frame = frame;
this.model = model;
this.company = company;
}
#Override
public void run() {
InputStream is = null;
BufferedReader br = null;
try {
String symbol = company.getStockSymbol();
URL url = new URL(URLString + symbol);
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; "
+ "Intel Mac OS X 10.4; en-US; rv:1.9.2.2) "
+ "Gecko/20100316 Firefox/3.6.2");
is = hc.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
processCSVFile(br);
} catch (MalformedURLException e) {
e.printStackTrace();
String message = e.getMessage();
message = "<html>" + message;
setMessageLabel(message);
} catch (IOException e) {
String message = e.getMessage();
message = "<html>" + message;
setMessageLabel(message);
} finally {
closeReaders(is, br);
}
}
private void processCSVFile(BufferedReader br) throws IOException {
String line = "";
int count = 0;
StockHistory history = new StockHistory(company);
while ((line = br.readLine()) != null) {
if (count > 0) {
StockDay stockDay = createStockDay(line);
if (stockDay != null) {
history.addStockDay(stockDay);
}
}
count++;
}
if (history.calculateNumbers()) {
model.addStockHistory(history);
addStockHistory();
setMessageLabel(" ");
} else {
String message = "<html>There is no data for "
+ company.getCompanyName();
setMessageLabel(message);
}
}
private StockDay createStockDay(String line) {
String[] parts = line.split(",");
if (parts[1].equals("-"))
return null;
double open = Double.valueOf(parts[1]);
double high = Double.valueOf(parts[2]);
double low = Double.valueOf(parts[3]);
double close = Double.valueOf(parts[4]);
long volume = Long.valueOf(parts[5]);
return new StockDay(parts[0], open, high, low, close, volume);
}
private void addStockHistory() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.addStockHistory();
}
});
}
private void setMessageLabel(final String text) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setMessageLabel(text);
;
}
});
}
private void closeReaders(InputStream is, BufferedReader br) {
try {
if (br != null)
br.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This class makes a URL connection with Google, and returns the historical stock information. This information is captured in a StockHistory instance, and stored in the StockPickerModel instance.
The User-Agent property is set to simulate a browser. Some web sites don’t allow programs to access their web server. By setting the User-Agent property, you can pretend to be a web browser. Your program should respect the web server, and not submit too many requests. How much is too many depends on the web server.
This class also updates the view. The only way we’ll know when the request is complete is when the HistoricalDataRunnable method receives a response from Google. It’s up to this class to update the model and the view.
Since this class is run in a separate thread, we have to call the SwingUtilities invokeLater method to execute any Swing GUI commands. That’s why the addStockHistory and setMessageLabel methods are enclosed in an invokeLater method.
This class displays any errors in the JLabel message. The stock might not be kept by Google. The stock may not have any stock day values. These error messages are displayed.
To see the rest of the code, take a look at my Stock Picker Using Java Swing article.
Hello i am trying to make a program that will allow me to load in a file and upload the name of it to a list. Once i select a file name in the list it should go through that file and take each line an put it in the specified jtextfield. But when i try and load a second file and try and select it, it tells me arrayIndexOutOfBounds. Can someone please explain to me what I'm doing wrong. I am using NetBeans.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package prog24178.assignment4;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
public class CustomerView extends javax.swing.JFrame {
/**
* Creates new form CustomerView
*/
private Application ass4App = new Application();
public ArrayList<Customer> customer = new ArrayList<Customer>();
public ArrayList<String> names = new ArrayList<String>();
public String fileName;
public Customer customers = new Customer();
public int i;
public void setApplication(Application customerApp) {
this.ass4App = ass4App;
}
public CustomerView() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void jExitItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void jOpenCusItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String currentPath = System.getProperty("user.dir");
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File[] file = fc.getSelectedFiles();
for (int i = 0; i < file.length; i++) {
try {
customers.constructCustomer(file[i]);
} catch (FileNotFoundException ex) {
Logger.getLogger(CustomerView.class.getName()).log(Level.SEVERE, null, ex);
}
customer.add(customers);
names.add(customer.get(i).getName());
}
jCustomerList.setListData(names.toArray());
}
}
private void jCustomerListValueChanged(javax.swing.event.ListSelectionEvent evt) {
// TODO add your handling code here:
jCusNameField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getName());
jAddressField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getAddress());
jCityField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getCity());
jProvinceField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getProvince());
jPostalCodeField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getPostalCode());
jEmailAddressField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getEmailAddress());
jPhoneNumberField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getPhoneNumber());
}
I fix the problem. I realized that i was just adding the variable customers to customer without giving it a proper value.
customer.add(customers.constructCustomer(file[i]));
I don't know what customers.constructCustomer(file[i]); or customer.add(customers); do, exactly -- we don't have enough code to know -- but you are using i to iterate through the array of File objects and to obtain a customer (customers.get(i)). That's the second place I'd look.
The FIRST place I'd look is at the error message; it tells you the line on which the array index was out of bounds, the value of the index, and the upper bound on the array.