Adding an ArrayList created in a method to JCombobox - java

I've asked a similar question before, but realised the main issue at hand which I cannot solve:
Currently have an ArrayList called SundayList which is loaded as soon as the frame AddStudent is loaded (bit of GUI)
The Add Student class:
Edited
public class AddStudent extends javax.swing.JFrame {
public AddStudent() {
initComponents();
}
private void loadLists() throws IOException
{
//Creating the array of Activities to put into the ComboBoxes
File f = new File("Activities.dat");
sundayList = new ArrayList<>();
mondayList= new ArrayList<>();
tuesdayList= new ArrayList<>();
wednesdayList= new ArrayList<>();
thursdayList= new ArrayList<>();
try{
BufferedReader reader = new BufferedReader(new FileReader(f));
while(reader.ready())
{
String CDay = reader.readLine();
String CActivityName = reader.readLine();
String CSupervisor = reader.readLine();
String CLocation = reader.readLine();
String CPaid = reader.readLine();
String nothing = reader.readLine();
if(CDay.equals("Sunday"))
{
sundayList.add(CActivityName);
}
else if(CDay.equals("Monday"))
{
mondayList.add(CActivityName);
}
else if(CDay.equals("Tuesday"))
{
tuesdayList.add(CActivityName);
}
else if(CDay.equals("Wednesday"))
{
wednesdayList.add(CActivityName);
}
else if(CDay.equals("Thursday"))
{
thursdayList.add(CActivityName);
}
}
reader.close();
}
catch (IOException ex)
{
Logger.getLogger(StartUpFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
...
comboboxSunday = new javax.swing.JComboBox();
...
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddStudent().setVisible(true);
}
});
}
For a start,I've tried to call the list SundayList into the combo box comboboxSunday to populate it, but only got the cannot find symbol error.
What do I need to do to make this possible?
Also, I plan on avoiding the mySQL involved method I've seen before, as I'm not familiar with it..
Current Coding for Combo box
The code automatically generated for the combo box by Netbeans is:
comboboxSunday = new javax.swing.JComboBox();
comboboxSunday.setModel(new javax.swing.DefaultComboBoxModel<>(sundayList.toArray(new String[sundayList.size()])));

The variable SundayList is limited to the scope of your constructor. Assuming you are creating your JComboBox in your initComponents method, you will not be able to access this variable.
You could however make SundayList a class member variable allowing you to use the variable accross methods. Also better to have a method to load data rather than having non-UI functionality in a UI constructor:
public class AddStudent {
private List<String> sundayList;
private List<String> mondayList;
...
private void loadLists() throws IOException {
sundayList = new ArrayList<>();
...
Then to add:
comboboxSunday.setModel(new DefaultComboBoxModel<>(sundayList.toArray(new String[sundayList.size()])));
Don't forget to call your new load method:
AddStudent addStudent = new AddStudent();
addStudent.loadLists();
addStudent.setVisible(true);
Aside: note that Java naming conventions indicate that variable start with a lowercase letter which would make SundayList sundayList.

Related

How to read from textfile and pass values to another class Java?

I'm making a Java program that needs to read info from a text file and then store it in an array and pass it to another class when called. My issue is that I can't seem to call it due to the IOException needed in the file reader class.
This is the main class that is supposed to call the fileReader.
public class window {
public static void main(String[] args){
String[] people = readFromText.read("people.txt");
}
}
File Reader Class
public class readFromText{
public static String[] read(String textFile) throws IOException {
BufferedReader inputFile = new BufferedReader(new
FileReader(textFile));
String[] array = new String[10];
String line = inputFile.readLine().toString();
int cnt = 0;
while (line!=null){
array[cnt] = line;
line = inputFile.readLine().toString();
cnt++;
}
inputFile.close();
return array;
}
}
Is it possible to do this, this way?
Firstly your code is not correct. You can not return the String[] array for the function need String[][].
Secondly for problem about exception you just need to catch it in your main class.
try {
String[] people = readFromText.read("people.txt");
} catch (IOException e) {
e.printStackTrace();
}

Display Array contents in a JComboBox

I have two classes, one with a class that reads text in a file and puts the data into a array and in the main class I want to add the array contents into a JComboBox. But I am getting the error "cannot be resolved to a variable" Any help?
readfiles.java
public class readfiles {
String [] names = new String[15];
int i = 0;
public Scanner readNames;
//Opens the file
public void openFile() {
try {
readNames = new Scanner(new File("ChildName.txt"));
} catch (Exception e) {
System.out.println("Could not locate the data file!");
}
}
//Reads the names in the file
public void readFile() {
while(readNames.hasNext()) {
names[i] = readNames.next();
System.out.println(Arrays.toString(names));
System.out.println(names[i]);
i++;
}
}
//Closes the file
public void closeFile() {
readNames.close();
}
}
Main.java
//JComboBox for selecting child
JLabel selectChildName = new JLabel("Please Select Your Child:");
sPanel.add(selectChildName);
JComboBox<String> selectChild = new JComboBox<String>(names); // (names); is the error, cannot be resolved to a variable
sPanel.add(selectChild);
You won't be able to access the names vairable in the main because its not in main's scope. To access it create an instance of the readfiles class and then get the names by doing instance.names;
for example,
readfiles instance = new readfiles();
instance.openfile();
instance.readfile();
instance.closefile();
JComboBox<String> selectChild = new JComboBox<String>(instance.names);
The names variable is a variable of the readFiles class and thus not visible in your Main class. You need to call a getter method on readFiles to get the array when you need it.

ArrayList different method's scope

I have a problem with the code below. I'm getting different results base on where the line list = new ArrayList<InClass>(); is declared. In place //B but everything works fine when I add it to //A and I cannot understand the difference. Here is the code:
import java.util.*;
import java.io.*;
public class ArrayListOne {
private ArrayList<InClass> list;
private InClass in;
public static void main(String args[]) {
ArrayListOne a = new ArrayListOne();
a.readFile();
}
public void readFile() {
//A
/**
* adding "list = new ArrayList<InClass>();"
* getting all 4 lines of test.txt
*/
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
assignToObject(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
public void assignToObject(String s) {
//B
/**
* adding "list = new ArrayList<InClass>();"
* getting just last line of test.txt
*/
InClass n = new InClass(s);
list.add(n);
System.out.println(list.size());
}
public void readObject() {
for (int i=0; i<list.size(); i++) {
in = list.get(i);
System.out.println(in.stTest);
}
}
//inner class
public class InClass {
String stTest;
public InClass(String s) {
stTest = s;
}
}
}
the test.txt has 3 lines. in //A, I'm getting all three lines (what I want) but in //B I just get the last line.
It's easier to see the difference if you "inline" assignToObject() by copy-pasting the contents of assignToObject() to the proper place in readFile():
public void readFile() {
// B
// list = new ArrayList<InClass>();
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
// Here is where assignToObject() was //
// B
// list = new ArrayList<InClass>();
InClass n = new InClass(line);
list.add(n);
System.out.println(list.size());
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
Now think about if you put list = new ArrayList<InClass>() in A and B.
If you declare list = new ArrayList<InClass>() at A (i.e. inside readFile()), the statement will be executed once -- when readFile() is called in main(). So you'll end up with one ArrayList containing everything you need.
However, if you declare list = new ArrayList<InClass>() at B (i.e. inside assignToObject()), you'll get a new list for every line you read (i.e. every time you call assignToObject()). This means that every iteration you'll end up with a new ArrayList that only contains the most recently read line. The ArrayList containing the previous line was thrown away, as the reference that used to point to it now points to a new object.

How to use ArrayList while adding something to another Class's constructor ?

I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));

Passing values from jframe to java class in netbeans

in netbeans I've got a JFrame and a JavaClass. In my JFrame I have a combobox to select a file that will be used in the operations within the Java class.
Java class:
public class WekaTest {
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("Ficheiro " + filename + " não encontrado");
}
return inputReader;
}
(...)
public static void main(String[] args) throws Exception {
JFrame1 form = new JFrame1();
form.setVisible(true);
BufferedReader datafile = readDataFile("weather.nominal.arff");
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
(...)
}
}
What I need is, from the JFrame's combobox, to select a different datafile to read from. So, as I change the selected item in my combobox, I want to set my datafile as that value.
Here's the JFrame code:
public class JFrame1 extends javax.swing.JFrame {
public JFrame1() {
initComponents();
}
(...)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(arffComboBox.getSelectedItem().toString());;
}
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
(...)
}
How can I do this?
Make the following a private (or public) member:
private BufferedReader datafile = null;
Then do the read within the action listener you've assigned to the combobox:
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
String pth = arffComboBox.getSelectedItem();
datafile = readDataFile(pth);
}
Then you can use datafile either in the listener or elsewhere as necessary.
Something like that should do what you're after.
EDIT
Given the new information, you're probably going to do best with a PropertyChangeListener that subscribes to the JFrame1 (form.addPropertyChangeListener) object and listens to PropertyChangeEvents that you fire from within your arffComboBoxActionPerformed method.
In the arffComboBoxActionPerformed:
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
String pth = arffComboBox.getSelectedItem();
firePropertyChange('combo_changed', null, pth);
}
Then in the main:
JFrame1 form = new JFrame1();
form.setVisible(true);
form.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pce) {
// Handle the change here
String pth = (String) pce.getNewValue();
BufferedReader datafile = readDataFile(pth);
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
(...)
}
});

Categories

Resources