0

This question is similar to this : How do you reference a button inside of its actionlistener?

I want to create a simple form containing 8 toggle buttons. if i select the toggle button and click save button, it will write into the text file i.e "Button x, On". Next time i open the form, the form will check in the notepad if Button x is already on. If on, the toggle button will already be selected and vice versa.

I know how to write to and read from the notepad, but i am not sure how to check if i.e the user select button 2 then the code will write into second line " Button2, on"

Here is my code so far to write :

Path path = Paths.get(csvFile);

// check if button x is selected, if yes : <- how to refer to button x ?
BufferedWriter bw = new BufferedWriter(New FileWriter(csvFile, true);
writer.write ("button x,on" + "\r\n");
writer.close

and this is my code when the form is opened :

BufferedReader br = null;
String line = "";
String resFilesplitby = ",";
br = new BufferedReader(new FileReader(csvFile));

        while((line = br.readLine()) != null){
            String[] condition = line.split(csvFilesplitby);
            String power = condition[1];

            // check if button x is already selected
            if (button x power.equals("on")){
                button x.isSelected();
            }
        }
  • It may pay to ask your question again and explain some more details. You may not get any more answers to this question because we have already answered. – sorifiend Jun 24 '18 at 05:17
  • i tried my best to explain my question, although it seems like i make people confused instead haha. I have already found my own way to do the coding, what should i do with the question ? – Kevin Guswanto Jun 24 '18 at 07:35
  • Post your solution as an answer, and mark it as accepted. – sorifiend Jun 24 '18 at 07:40

3 Answers3

1

I manage to found a simple way to solve the problem By adding the button to an array.

JToggleButton[] buttons = new JToggleButton[8];

buttons[0] = seat1; //this is variable name of my button.
buttons[1] = seat2;
buttons[2] = seat3;
buttons[3] = seat4;
buttons[4] = seat5;
buttons[5] = seat6;
buttons[6] = seat7;
buttons[7] = seat8;

// do the work here
for (JToggleButton btn : buttons){
   if(btn.isSelected){

   }
}
0

For simplicity I recommend that you write all of the button statuses at the same time, and write them directly as a boolean value:

//Write the state of all the buttons in a single line:
writer.write (
    x1.isSelected() + "," + 
    x2.isSelected() + "," + 
    x3.isSelected() + "," + 
    x4.isSelected() + "," + 
    x5.isSelected() + "," + 
    x6.isSelected() + "," + 
    x7.isSelected() + "," + 
    x8.isSelected());

Then reading it back as a single line and just compare each of the 8 items split by the ",":

String[] condition = line.split(csvFilesplitby);
if (condition[0].equalsIgnoreCase("true")){
    x1.setSelected(true);
}else if (condition[1].equalsIgnoreCase("true")){
    x2.setSelected(true);
}else if (condition[2].equalsIgnoreCase("true")){
    x3.setSelected(true);
}else if (condition[3].equalsIgnoreCase("true")){
    x4.setSelected(true);
}else if (condition[4].equalsIgnoreCase("true")){
    x5.setSelected(true);
}else if (condition[5].equalsIgnoreCase("true")){
    x6.setSelected(true);
}else if (condition[6].equalsIgnoreCase("true")){
    x7.setSelected(true);
}else if (condition[7].equalsIgnoreCase("true")){
    x8.setSelected(true);
}

Obviously you should add some error checking and make sure all buttons are deselected before you set if they are selected or not. But I am sure you can work that part out.

sorifiend
  • 5,927
  • 1
  • 28
  • 45
  • this is possible but won't it be considered as hard code ? – Kevin Guswanto Jun 23 '18 at 11:23
  • @KevinGuswanto I don't understand what you mean, of course it is hard coded. If you want to read from and write to any spot in the file then you need just need to add some simple string recognition. For example: `if (line.startsWith("button x"))` then you can check for on or off like normal. – sorifiend Jun 23 '18 at 11:31
  • i mean like something like this could be able to be solved by for and if, so while the code above is possible, it's too ineffective – Kevin Guswanto Jun 23 '18 at 11:44
  • @KevinGuswanto This method may help answer your question "_but i am not sure how to check if i.e the user select button 2 then the code will write into second line_" https://stackoverflow.com/questions/25714779/how-can-i-write-to-a-specific-line-number-in-a-txt-file-in-java – sorifiend Jun 23 '18 at 11:48
  • i'm sorry, it seems like i didn't ask properly due to my limited language. I will edit it right now – Kevin Guswanto Jun 23 '18 at 11:54
0

Alternatively you can try something like below :

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;

public class Ques1 extends JFrame implements ActionListener {

    private JPanel panel;
    private JToggleButton[] buttons;

    public Ques1() {

        initComponents();
        buttonswork();
    }

    private void initComponents() {

        buttons = new JToggleButton[6];
        panel = new JPanel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
        panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));

        for (int i = 0; i < buttons.length; i++) {
            JToggleButton tb = buttons[i];
            tb = new JToggleButton("tb" + (i + 1));
            tb.addActionListener(this);
            panel.add(tb);
        }

        getContentPane().add(panel);
        pack();
    }

    private void buttonswork() {
        try {
            String line = "";
            String buttonString = "tb1-0\n"
                    + "tb2-0\n"
                    + "tb3-0\n"
                    + "tb4-1\n"
                    + "tb5-1\n"
                    + "tb6-0\n";

            BufferedReader br = new BufferedReader(new StringReader(buttonString));
            while ((line = br.readLine()) != null) {
                Component[] components = panel.getComponents();

                for (Component c : components) {
                    if (c instanceof JToggleButton) {
                        String ac = ((JToggleButton) c).getActionCommand();
                        ((JToggleButton) c).addActionListener(this);
                        if (ac.equalsIgnoreCase(line.split("-")[0])) {
                            ((JToggleButton) c).setSelected(Integer.parseInt(line.split("-")[1]) == 1);
                        }
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            new Ques1().setVisible(true);
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {

      switch (e.getActionCommand()) {
        case "tb1":
            //do your work here ...
            break;
        case "tb2":
            //do your work here ...
            break;

      }
    }
}
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36
  • i figured out it will be something like adding the button to the array and then put it in the loop. I will put it in my question, please check it out – Kevin Guswanto Jun 23 '18 at 12:22