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.
Related
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();
}
I have a combo box that contains data from an array. I want to be able to get the the selected name in the JComboBox and print it to a text file. The problem is that the name wont write to the text file.
Array code:
public class readfiles {
String [] names = new String[15];
int i = 0;
private 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(names[i]);
i++;
}
}
//Closes the file
public void closeFile() {
readNames.close();
}
}
ComboBox code:
//JComboBox for selecting child
JLabel selectChildName = new JLabel("Please Select Your Child:");
sPanel.add(selectChildName);
readfiles readNames = new readfiles();
readNames.openFile();
readNames.readFile();
readNames.closeFile();
JComboBox<String> selectChild = new JComboBox<String>(readNames.names);
sPanel.add(selectChild);
And finally this is what I am doing to write the selected name to a text file.
bw.write(selectChild.getSelectedIndex());
UPDATE
Used:
bw.write(selectChild.getSelectedItem().toString());
You need JComboBox#getSelectedItem() instead of JComboBox#getSelectedIndex(). As it is a String, it should be printed within the file.
Returns the current selected item.
Do not forget to also use a ItemListener with your JComboBox
I want to save the contents of my arraylist to a textfile. What I have so far is shown below, however instead of adding x.format("%s%s", "100", "control1"); to the textfile, I want to add objects from an arraylist, how do I go about this?
import java.util.*;
public class createfile
{
ArrayList<String> control = new ArrayList<String>();
private Formatter x;
public void openFile()
{
try {
x = new Formatter("ControlLog.txt");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: Your file has not been created");
}
}
public void addRecords()
{
x.format("%s%s", "100", "control1");
}
public void closeFile()
{
x.close();
}
}
public class complete
{
public static void main(String[] args)
{
createfile g = new createfile();
g.openFile();
g.addRecords();
g.closeFile();
}
}
Both ArrayList and String implement Serializable. Since you have an ArrayList of string you can write it to the file like this:
FileOutputStream fos = new FileOutputStream("path/to/file");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(myArrayList); //Where my array list is the one you created
out.close();
Here is a really good tutorial that shows you how to write java objects to a file.
The written objects can be read back from the file in a similar way.
FileInputStream in = new FileInputStream("path/to/file");
ObjectInputStream is = new ObjectInputStream(in);
myArrayList = (ArrayList<String>) is.readObject(); //Note that you will get an unchecked warning here
is.close()
Here is a tutorial on how to read objects back from a file.
I don't know what's wrong with my main class. I dont know how to change it to fix it. Computer says: load from file cannot be referenced from static context. If I try to change it, my main class is missing.
public class Bsp3_1225814_3 {
public void static main(String [] args){
List<Linienzug> lst = new ArrayList<>();
load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_in");
dump_to_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_out");
}
public void load_from_file(String file) {
Scanner s = null;
try {
s = new Scanner(
new BufferedReader(new FileReader(file))).useDelimiter("\\n");
while (s.hasNext()) {
String[] in = s.next().split(":");
Linienzug l = new Linienzug();
for (int i=0; i<(in.length-1); i++){
l.add(new Punkt(Integer.parseInt(in[i]),
Integer.parseInt(in[i+1])));
}
this.lst.add(l);
}
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} finally {
if (s != null) {
s.close();
}
}
}
You cannot call a method that does not have the static keyword when you are in a static method. This is because there is an implicit reference to the this pointer which does not exist in a static context.
You cannot invoke instance methods, from a static context in this way.
You have to create an instance to invoke them.
Fix...
Bsp3_1225814_3 bsp3 = new Bsp3_1225814_3();
bsp3.load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_in");
bsp3.dump_to_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_out");
public void static main(String [] args){
Bsp3_1225814_3 myObj = new Bsp3_1225814_3();
myObj.load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen
...
}
And declare lst as a member of your class.
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.