Constructor for buttons - java

I have a text file that contains something like:
parameter 1 = true
parameter 2 = true
parameter 3 = false
and this goes on for over 90 parameters. I am creating a program that will read from this file and create buttons that will have different states depending if the parameter is set to true or false, and also alternate between these states.
My question is: To make this buttons, is there a way to create a constructor to be called that can create the buttons for me or do i have to copy and paste everything, one at a time? As I am relatively new to programming, I've been looking for days but I was never able to make it.
PS: I don't need the code for the states of the buttons, I just need to know if there is a simpler and quice, and if there is, how do I do it.

Assuming you don't need the names from the text file (parameter 1, etc), one possible solution is to try going through the text file and save each value to a boolean array. Then you can do something like this:
List<MyButton> buttons = new ArrayList<MyButton>();
for (int i = 0; i < buttonValues.length; i++) { //buttonValues is the array of booleans
buttons.add(new MyButton(buttonValues[i]);
}
Where MyButton is a class you make that has a constructor that takes a boolean value to indicate its state.
You don't even need to save the values in an array, you could skip straight to making the buttons as you read the file. You would change it to a while loop with the condition along the lines of myFileReader.hasNext() and pass the constructor the boolean value as you read it. You could also easily read the name of the parameter here as well, if you want to keep track of it. Just update MyButton's constructor to take the name.

You can read line by line and create a buttons in runtime for each line :
public Frame() throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader("1.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// read line by line
String[] paramAndValue = new String[2];
// split key/value
paramAndValue = line.split(" = ");
// add a Jbutton with the key as name
JButton button = new JButton(paramAndValue[0]);
// and the value as the state
button.setEnabled(Boolean.parseBoolean(paramAndValue[1]));
this.add(button);
}
}
}

Related

Storing text as an arraylist from JTextArea

I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}

Removing duplicate lines from a text file

I have a text file that is sorted alphabetically, with around 94,000 lines of names (one name per line, text only, no punctuation.
Example:
Alice
Bob
Simon
Simon
Tom
Each line takes the same form, first letter is capitalized, no accented letters.
My code:
try{
BufferedReader br = new BufferedReader(new FileReader("orderedNames.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("sortedNoDuplicateNames.txt", true)));
ArrayList<String> textToTransfer = new ArrayList();
String previousLine = "";
String current = "";
//Load first line into previous line
previousLine = br.readLine();
//Add first line to the transfer list
textToTransfer.add(previousLine);
while((current = br.readLine()) != previousLine && current != null){
textToTransfer.add(current);
previousLine = current;
}
int index = 0;
for(int i=0; i<textToTransfer.size(); i++){
out.println(textToTransfer.get(i));
System.out.println(textToTransfer.get(i));
index ++;
}
System.out.println(index);
}catch(Exception e){
e.printStackTrace();
}
From what I understand is that, the first line of the file is being read and loaded into the previousLine variable like I intended, current is being set to the second line of the file we're reading from, current is then compared against the previous line and null, if it's not the same as the last line and it's not null, we add it to the array-list.
previousLine is then set to currents value so the next readLine for current can replace the current 'current' value to continue comparing in the while loop.
I cannot see what is wrong with this.
If a duplicate is found, surely the loop should break?
Sorry in advance when it turns out to be something stupid.
Use a TreeSet instead of an ArrayList.
Set<String> textToTransfer = new TreeSet<>();
The TreeSet is sorted and does not allow duplicates.
Don't reinvent the wheel!
If you don't want duplicates, you should consider using a Collection that doesn't allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set which will not allow duplicates:
import java.util.*;
import java.util.stream.*;
public class RemoveDups {
public static void main(String[] args) {
Set<String> dist = Arrays.asList(args).stream().collect(Collectors.toSet());
}
}
Another way is to remove duplicates from text file before reading the file by the Java code, in Linux for example (far quicker than do it in Java code):
sort myFileWithDuplicates.txt | uniq -u > myFileWithoutDuplicates.txt
While, like the others, I recommend using a collection object that does not allow repeated entries into the collection, I think I can identify for you what is wrong with your function. The method in which you are trying to compare strings (which is what you are trying to do, of course) in your While loop is incorrect in Java. The == (and its counterpart) are used to determine if two objects are the same, which is not the same as determining if their values are the same. Luckily, Java's String class has a static string comparison method in equals(). You may want something like this:
while(!(current = br.readLine()).equals(previousLine) && current != null){
Keep in mind that breaking your While loop here will force your file reading to stop, which may or may not be what you intended.

java check a given string in csv file

I have a csv file the format is like this:
I have a another csv file which is the same number of columns and rows.
I need to check if file 1 has same value (value[0]) as file 2 and if not copy value from file 2.
Below is the code I have written, but when checking, if file 1 first row value is not equal to the row, I need to go and check the next row of file 2 without exiting the if statement.
while ((line = br4.readLine()) != null){
while ((line5 = br5.readLine()) != null){
String[] values = line.split(",");
String[] values5 = line5.split(",");
fw5.append("0").append('\n');
String comp2 = values[0];
String comp1 = values5[0];
if (values5[0] == null ? values[0] == null : values5[0].equals(values[0]))
{
fw6.append(values[0]).append("mad men ").append('\n');
}
else if ( values5[0] == null ? (values[0]) != null : !values5[0].equals(values[0])){
System.out.println("value is " +values5[0]);
fw6.append(values5[0]).append("mad women").append('\n');
fw6.flush();
}
break;
}
}
You are facing a typical newbie problem: insufficient abstractions.
You try to solve your whole problem in one method: instead create helpful abstractions. Like this:
first you create a class representing that row data. You might pass a string (content of one row) to the constructor. Then that class splits the string and puts all entries into meaningful named fields (instead of using an array named values which does not say anything).
then you add methods to that class to compare two instances of the class (could be the equals method or something you define on your own).
and while doing all of that you keep testing the code as you write.
then when you can parse that line of text and compare it as desired - then you add the code to read lines from your files. You read all lines, create objects and update them as required.
and finally you write code that writes updated objects back into file.
Long story short: slice your big problem into smaller ones and solve them one after the other.

How to search for name in file and extract value

I have a file that looks like this:
Dwarf remains:0
Toolkit:1
Cannonball:2
Nulodion's notes:3
Ammo mould:4
Instruction manual:5
Cannon base:6
Cannon base noted:7
Cannon stand:8
Cannon stand noted:9
Cannon barrels:10
...
What is the easiest way to open this file, search for name and return the value of the field? I cannot use any external libraries.
What i have tried/is this ok?
public String item(String name) throws IOException{
String line;
FileReader in = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
while ((line = br.readLine()) != null) {
if(line.contains(name)){
String[] parts = line.split(":");
return parts[1];
}
}
return null;
}
As a followup to your code - it compiles and works ok. Be aware though, that / is not the correct path separator on Windows (\ is). You could've created the correct path using, for example: Paths.get("C:", "test.txt").toString(). Correct separator is defined as well in File.separator.
The task can be easily achieved using basic Java capabilities. Firstly, you need to open the the file and read its lines. It can be easily achieved with Files.lines (Path.get ("path/to/file")). Secondly, you need to iterate through all the lines returned by those instructions. If you do not know stream API, you can change value returned from Files.lines (...) from Stream to an array using String[] lines = Files.lines(Paths.get("path/to/file")).toArray(a -> new String[a]);. Now lines variable has all the lines from the input file.
You have to then split each line into two parts (String.split) and see whether first part equals (String.equals) what you're looking for. Then simply return the second one.

Is it possible to read multiple lines from textfile and export it to their respective jtextfields?

private void loadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
FileReader reader = new FileReader("reload.txt");
BufferedReader br = new BufferedReader(reader);
koontf.read(br,null);
baamtf.read(br,null);
sachitf.read(br,null);
fakertf.read(br,null);
phonsekaltf.read(br,null);
lauretf.read(br,null);
yeontf.read(br,null);
aguerotf.read(br,null);
agnistf.read(br,null);
lokitf.read(br,null);
lawliettf.read(br,null);
ryuzakitf.read(br,null);
br.close();
koontf.requestFocus();
baamtf.requestFocus();
sachitf.requestFocus();
fakertf.requestFocus();
phonsekaltf.requestFocus();
lauretf.requestFocus();
yeontf.requestFocus();
aguerotf.requestFocus();
agnistf.requestFocus();
lokitf.requestFocus();
lawliettf.requestFocus();
ryuzakitf.requestFocus();
}catch(IOException e) {
}
}
Is it even possible to put each of them to a certain textfield?Like 12 to jtextfield1,10 to jtextfield2 and so on...I've tried some tutorials and can't really figure it out.
You could put all your textFields in an array and then iterate over that array while you are reading the text file. Like this:
JTextField[] textFields = new JTextField[10];
// ... init your textFields here
int line =0; // first line will be first textfield and so on
Scanner scanner = new Scanner(new File("reload.txt")); // use Scanner instead of FileReader, it's easier :)
while(scanner.hasNextLine()){ // as long as you did not reach the end of the file
textFields[line++].setText(scanner.nextLine()); // get the next line and put it in the respective textfield
}
However, in this case you have to make sure that there is a textfield for every line or that you do not read more lines than there are textfields.
for example:
while(.....){
....
if(line==textFields.length){
break;
}
}
Another thing to notice will be, that the order of the lines has to correspond to the order of your textFields.
Edit
I have to add, that all this can work without any problem. But it is not a very elegant solution. What happens when you change your UI and the Textfields are in a different order? Or there is an important new line in your textfile but no TextField in your UI?
Edit 2
The code from your comment does not show how you put the JTextFields in your array. My Guess is that you are using some IDE to create the GUI, so you should have a initComomponents(); call or something in your constructor. In this case, remove the line JTextField[] textFields = new JTextField[10]; from your loadActionPerformed method and put it in your constructor like this:
public class MyClass{
private JTextField[] textFields;
public MyClass(){
initComponents();
this.textFields = new JTextField[10] // where 10 is the number of lines in your textfile AND the number of JTextFields you have in your GUI
// then fill the array (by hand if you like)
this.textField[0] = koontf;
this.textField[1] = baamtf;
// and so on..
}
Edit 3
Just to make it clear, this is what you need to make the program run. Let's say your class is called MyClass then it could look like this:
private JTextField[] textFields; // this creates your array
public MyClass(){ // this is the constructor of your class (I don't know how it is called)
initComponents(); // auto generated code from NetBeans to initalize your GUI elements
// init your array
textFields = new JTextField[12]; // 12 if I counted correctly
// fill it
textFields[0] = koontf;
textFields[1] = baamtf;
textFields[2] = sachitf;
textFields[3] = fakertf;
textFields[4] = phonsekaltf;
textFields[5] = lauretf;
textFields[6] = yeontf;
textFields[7] = aguerotf;
textFields[8] = agnistf;
textFields[9] = lokitf;
textFields[10] = lawliettf;
textFields[11] = ryuzakitf;
}
private void loadActionPerformed(java.awt.event.ActionEvent evt){
int line = 0;
try(Scanner scanner = new Scanner(new File("reload.txt"))){
while(scanner.hasNextLine()){
textFields[line++].setText(scanner.nextLine());
if(line == textFields.length){
break;
}
}
}catch(FileNotFoundException ex){
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
koontf.requestFocus(); // you can only call request focus on one element at a time (it does not make sense to call it on all textfields
}

Categories

Resources