How to record multiple information in multiple classes using only one save class?

Asked

Viewed 299 times

0

My problem is this, I’m developing a program that has several buttons that correspond to certain students, within each student I have personal information about and only this Student, I have a class that records everything in the same way only I wanted instead of I was doing every record class for each student I wanted that in each student he would pick up this class and if he had come from student X he would record in student X.txt if it was student Y recorded in student Y.txt

public class Gravação_Dados extends JFrame {

    private JPanel contentPane;
    private JTextPane textArea;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Gravação_Dados frame = new Gravação_Dados();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Gravação_Dados() {
        setLocationByPlatform(true);
        setResizable(false);
        setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\Science-Classroom-icon.png"));
        setTitle("Grava\u00E7\u00E3o Notas");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("Detalhes/Notas");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 11));
        lblNewLabel.setBounds(10, 59, 89, 14);
        contentPane.add(lblNewLabel);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(100, 59, 317, 123);
        contentPane.add(scrollPane);
        textArea = new  JTextPane();
        scrollPane.setViewportView(textArea);

        JButton btnNewButton = new JButton("Gravar");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try
                {
                    FileWriter writer= new FileWriter("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt");
                    BufferedWriter bw=new BufferedWriter (writer);

                    textArea.write(bw);
                    bw.close();
                    textArea.setText("");
                    textArea.requestFocus();
                    dispose();
                }
                catch(Exception e1){
                    JOptionPane.showMessageDialog(null, e1);
                }
            }

        });
        btnNewButton.setBounds(293, 205, 89, 23);
        contentPane.add(btnNewButton);
        final JButton Abrir = new JButton("Abrir");
        Abrir.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                Abrir.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {

                        try
                        {
                            FileReader reader=new FileReader("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt");
                            BufferedReader br= new BufferedReader (reader);
                            textArea.read(br, null);
                            br.close();
                            textArea.requestFocus();
                        }
                        catch(Exception e1){
                            JOptionPane.showMessageDialog (null,  e1);
                        }

                    }
                });
            }
        });
        Abrir.setBounds(168, 205, 89, 23);
        contentPane.add(Abrir);

        JButton Preciso_de_ajuda = new JButton("Preciso de Ajuda");
        Preciso_de_ajuda.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Ajuda().setVisible(true);
            }
        });
        Preciso_de_ajuda.setIcon(new ImageIcon("C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\dica.png"));
        Preciso_de_ajuda.setBackground(SystemColor.control);
        Preciso_de_ajuda.setHorizontalAlignment(SwingConstants.LEFT);
        Preciso_de_ajuda.setBounds(0, 0, 444, 23);
        contentPane.add(Preciso_de_ajuda);
    }
}

Basically I wanted when the user pressed the student button for example the program knew that I wanted to record this information in the corresponding file.txt. Here this edition this is the main menu:

public class PARTE2 extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    PARTE2 frame = new PARTE2();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public PARTE2() {
        setExtendedState(Frame.MAXIMIZED_BOTH);
        setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\icons\\Science-Classroom-icon.png"));
        setTitle("Planta da Sala de Aula");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);


        JButton PC_1 = new JButton("PC 1");
        PC_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno1_Magda().setVisible(true);
            }
        });
        PC_1.setBounds(10, 586, 138, 84);
        contentPane.add(PC_1);

        JButton PC_2 = new JButton("PC 2");
        PC_2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno2_Carolina().setVisible(true);
            }
        });
        PC_2.setBounds(10, 496, 138, 84);
        contentPane.add(PC_2);

        JButton PC_3 = new JButton("PC 3");
        PC_3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    new Aluno3_Pedro().setVisible(true);
            }
        });
        PC_3.setBounds(10, 406, 138, 84);
        contentPane.add(PC_3);

        JButton PC_4 = new JButton("PC 4");
        PC_4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno4_Alexandre ().setVisible(true);
            }
        });
        PC_4.setBounds(10, 316, 138, 84);
        contentPane.add(PC_4);

        JButton PC_5 = new JButton("PC 5");
        PC_5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno5_Tomas ().setVisible(true);
            }
        });

        PC_5.setBounds(10, 226, 138, 84);
        contentPane.add(PC_5);

        JButton PC_6 = new JButton("PC 6");
        PC_6.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno6_Raul().setVisible(true);
            }
        });
        PC_6.setBounds(10, 136, 138, 84);
        contentPane.add(PC_6);

        JButton PC_8 = new JButton("PC 8");
        PC_8.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno8_Jorge().setVisible(true);
            }
        });

        JButton PC_7 = new JButton("PC 7");
        PC_7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Aluno7_Ruben().setVisible(true);
            }
        });
        PC_7.setBounds(10, 46, 138, 84);
        contentPane.add(PC_7);
        PC_8.setBounds(269, 46, 200, 84);
        contentPane.add(PC_8);

        JButton PC_9 = new JButton("PC 9");
        PC_9.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno9_Joao().setVisible(true);
            }
        });
        PC_9.setBounds(469, 46, 200, 84);
        contentPane.add(PC_9);

        JButton PC_10 = new JButton("PC 10");
        PC_10.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno10_Miguel().setVisible(true);
            }
        });
        PC_10.setBounds(669, 46, 200, 84);
        contentPane.add(PC_10);

        JButton PC_11 = new JButton("PC 11");
        PC_11.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno11_Diogo().setVisible(true);
            }
        });
        PC_11.setBounds(869, 46, 200, 84);
        contentPane.add(PC_11);

        JButton PC_12 = new JButton("PC 12");
        PC_12.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno12_Miguel().setVisible(true);
            }
        });
        PC_12.setBounds(1214, 46, 138, 84);
        contentPane.add(PC_12);

        JButton PC_13 = new JButton("PC 13");
        PC_13.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno13_Francisco().setVisible(true);
            }
        });
        PC_13.setBounds(1214, 136, 138, 84);
        contentPane.add(PC_13);

        JButton PC_14 = new JButton("PC 14");
        PC_14.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno14_Ze().setVisible(true);
            }
        });
        PC_14.setBounds(1214, 226, 138, 84);
        contentPane.add(PC_14);

        JButton PC_15 = new JButton("PC 15");
        PC_15.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno15_Floriano().setVisible(true);
            }
        });
        PC_15.setBounds(1214, 316, 138, 84);
        contentPane.add(PC_15);

        JButton PC_16 = new JButton("PC 16");
        PC_16.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno16_Ruben().setVisible(true);
            }
        });
        PC_16.setBounds(1214, 406, 138, 84);
        contentPane.add(PC_16);

        JButton PC_17 = new JButton("PC 17");
        PC_17.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Aluno17_Edmara().setVisible(true);
            }
        });
        PC_17.setBounds(1214, 497, 138, 84);
        contentPane.add(PC_17);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBackground(SystemColor.menu);
        menuBar.setBounds(0, 0, 1362, 21);
        contentPane.add(menuBar);

        JMenu ficheiro = new JMenu("Ficheiro ");
        menuBar.add(ficheiro);

        JMenuItem sair = new JMenuItem("Sair");
        sair.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Object[] options = { "Sim", "Não" };
                int selectedOption=JOptionPane.showOptionDialog(null, "   Deseja realmente sair do programa?", "Planta Sala-Sair",
                JOptionPane.INFORMATION_MESSAGE, JOptionPane.INFORMATION_MESSAGE,
                null, options, options[0]);

                 if (selectedOption == JOptionPane.YES_OPTION) {
                     dispose();
                 }
            }
        });
        sair.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        sair.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
        ficheiro.add(sair);

        JMenu mnAjuda = new JMenu("Ajuda");
        menuBar.add(mnAjuda);

        JMenuItem precisoajuda = new JMenuItem("Preciso de Ajuda");
        mnAjuda.add(precisoajuda);

        JMenuItem mntmNewMenuItem_1 = new JMenuItem("Sobre");
        mntmNewMenuItem_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Menu_Sobre().setVisible(true);
            }
        });
        mnAjuda.add(mntmNewMenuItem_1);

        JButton Secretaria = new JButton("Secret\u00E1ria");
        Secretaria.setAlignmentX(Component.CENTER_ALIGNMENT);
        Secretaria.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Relatorio_().setVisible(true);
            }
        });
        Secretaria.setFont(new Font("Tahoma", Font.PLAIN, 22));
        Secretaria.setBounds(404, 529, 554, 141);
        contentPane.add(Secretaria);
    }
}

That will give the window of the respective student:

public class Aluno7_Ruben extends JFrame {

    protected static final File texto1 = null;
    private JPanel contentPane;



    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    Aluno7_Ruben frame = new Aluno7_Ruben();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Aluno7_Ruben() {
        setResizable(false);
        setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\icon\\Science-Classroom-icon.png"));


        setTitle("PC7-Ruben Gato");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("Detalhes/Notas:");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 17));
        lblNewLabel.setBounds(10, 106, 194, 23);
        contentPane.add(lblNewLabel);

        JLabel lblNewLabel_1 = new JLabel("Localiza\u00E7\u00E3o da avaria:");
        lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 17));
        lblNewLabel_1.setBounds(10, 11, 169, 20);
        contentPane.add(lblNewLabel_1);
        File file = new File("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt");
        FileInputStream fis = null;
        String texto = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                texto += (char) content;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 128, 414, 85);
        contentPane.add(scrollPane);

        final JTextArea textArea1 = new JTextArea(texto);
        scrollPane.setViewportView(textArea1);

        textArea1.setEditable(false);
        textArea1.setWrapStyleWord(true);



        final JCheckBox Teclado = new JCheckBox ("Teclado");
        Teclado.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Teclado.isSelected()){
                    try {
                        String texto_teclado = "O Teclado está danificado";
                        BufferedWriter writer = new BufferedWriter(
                        new FileWriter("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt", true));
                        writer.write(texto_teclado);
                        writer.newLine();
                        textArea1.append(texto_teclado+"\n");
                        writer.close();
                    } catch (IOException e1) {
                    }
                }
            }
        });
        Teclado.setToolTipText("Selecionar caso esteja danificado");
        Teclado.setBounds(6, 54, 94, 23);
        contentPane.add(Teclado);

        final JCheckBox  Rato = new JCheckBox ("Rato");
        Rato.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Rato.isSelected()){
                    try {
                        String texto_rato = "O Rato está danificado";
                        BufferedWriter writer = new BufferedWriter(
                        new FileWriter("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt", true));
                        writer.write(texto_rato);
                        textArea1.append(texto_rato+"\n");
                        writer.newLine();
                        writer.close();
                    } catch (IOException e1) {
                    }
                }
                else{
                }
            }
        });
        Rato.setToolTipText("Selecionar caso esteja danificado");
        Rato.setBounds(98, 54, 81, 23);
        contentPane.add(Rato);

        final JCheckBox  Monitor = new JCheckBox ("Monitor");
        Monitor.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Monitor.isSelected()){
                    try {
                        String texto_monitor = "O Monitor está danificado";
                        BufferedWriter writer = new BufferedWriter(
                        new FileWriter("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt", true));
                        writer.write(texto_monitor);
                        textArea1.append(texto_monitor+"\n");
                        writer.newLine();
                        writer.close();
                    } catch (IOException e1) {
                    }
                }
                else{
                }       
            }
        });
        Monitor.setToolTipText("Selecionar caso esteja danificado");
        Monitor.setBounds(181, 54, 96, 23);
        contentPane.add(Monitor);

        final JCheckBox Torre = new JCheckBox ("Torre");
        Torre.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Torre.isSelected()){
                    try {
                        String texto_torre = "A Torre está danificada";
                        BufferedWriter writer = new BufferedWriter(
                        new FileWriter("C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt", true));
                        writer.write(texto_torre );
                        textArea1.append(texto_torre +"\n");
                        writer.newLine();
                        writer.close();
                    } catch (IOException e1) {
                    }
                }
                else{
                }   
            }       
        });
        Torre.setToolTipText("Selecionar caso esteja danificado");
        Torre.setBounds(288, 54, 109, 23);
        contentPane.add(Torre);

        JButton Adicionar_notas = new JButton("Escrever novas notas");
        Adicionar_notas.addActionListener(new ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FAZJA(evt);
            }
        });

        Adicionar_notas.setBounds(137, 224, 159, 23);
        contentPane.add(Adicionar_notas);
    }

    protected void FAZJA(ActionEvent evt) {
        this.dispose();
        new Gravação_Dados().setVisible(true);
    }
}
  • @Meuchapeu do not understand why I edited my question I am Portuguese and not Brazilian so you do not have the right to correct things that are fine, so next try to help people instead of making corrections for everything and for nothing

  • if I understand correctly your problem is in write and in the reader that you wanted it to be dynamic? This is to create that path automatically?

  • @Joaogil I’m sorry that the edition has displeased you, feel free to reverse it if it seems appropriate. For my part, however, I believe that it improved yes the question (by correctly formatting the code) and, although I am not versed in pt_PT, I see that one of the reviewers that approved that edition yeah, and if he didn’t find any problems in that issue I trust his judgment (feel free to disagree in the meantime).

  • 1

    @mgibsonbr just to complete your comment, since this happened to me, http://meta.pt.stackoverflow.com/questions/1700/editar-alterar-conte%C3%Bado-da-resposta has here an equal problem that I took to the goal, so it can be more clarified...

  • The implementation must necessarily be that way, creating a file .txt per student? It would be better to use a SGBD for persistence of information, or a file XML.

  • because from the beginning I try to write to txt documents because I don’t know how to use SGBD or XML files, but even so I have idea that this would be for example a variable called number for example and I would start and declare this variable in each student’s class when using the label class had a switch case, case number=1 writes to student 1.txt case number=2 writes to student 2.txt is it possible to do this somehow? @mxn

  • @jsantos1991 yes I wanted the program to know where the data came from and then to save it in the right files

  • @Joaogil I have understood what you want to do (I think), but I don’t know how to explain it to you, because I don’t know who calls that class gravar_dados, however I will draw up an answer to see if it helps you...

  • new Aluno9_Joao().setVisible(true);, new Aluno8_Jorge().setVisible(true);, new Aluno5_Tomas ().setVisible(true);. Please improve the object orientation of this business fast. This is awful. Do not copy and paste code! This way, you’re creating a monster and soon it will devour you!

Show 4 more comments

1 answer

3

Your code has a long series of problems. Let’s try to fix everything.

First step:

We have to avoid this code copied and pasted everywhere:

        final JCheckBox Teclado = new JCheckBox ("Teclado");
        Teclado.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Teclado.isSelected()){
                    try {
                        String texto_teclado = "O Teclado está danificado";
                        BufferedWriter writer = new BufferedWriter(
                        new FileWriter(NOTAS, true));
                        writer.write(texto_teclado);
                        writer.newLine();
                        textArea1.append(texto_teclado+"\n");
                        writer.close();
                    } catch (IOException e1) {
                    }
                }
            }
        });
        Teclado.setToolTipText("Selecionar caso esteja danificado");
        Teclado.setBounds(6, 54, 94, 23);
        contentPane.add(Teclado);

The solution to this is to encapsulate the creation of this JCheckBox in some methods. I’ll put one method to save to the file and another to create the checkbox:

    private static final String NOTAS = "C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt";

    private void salvar(String texto) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(NOTAS, true))) {
            writer.write(texto);
            writer.newLine();
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null, "Um erro inesperado ocorreu:\n" + e1.toString());
        }
    }

    private JCheckBox criarCheckDanificado(String nome, boolean masculino, final JTextArea area, int x, int y, int w, int h) {
        final JCheckBox equipamento = new JCheckBox(nome);
        equipamento.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (equipamento.isSelected()) {
                    String texto;
                    if (masculino) {
                        texto = "O " + nome + " está danificado";
                    } else {
                        texto = "A " + nome + " está danificada";
                    }
                    salvar(texto);
                    area.append(texto + "\n");
                }
            }
        });
        equipamento.setToolTipText("Selecionar caso esteja danificado");
        equipamento.setBounds(x, y, w, h);
        contentPane.add(equipamento);
        return equipamento;
    }

Second step:

Having multiple student screens, one for each student is terrible because it means a lot of code duplication. The only thing that’s different between these screens is the PC number and the student name, so we can parameterize this to create a class Aluno unique. Parameterization is done by defining the name and number of the student in the constructor.

I will already take advantage and put the file paths in constants and also put the setVisible(true); inside the constructor, since whenever this is called, we want the screen to be already visible.

public class Aluno extends JFrame {

    private static final String ICON = "C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\icon\\Science-Classroom-icon.png";
    private static final String NOTAS = "C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt";

    protected static final File texto1 = null;
    private JPanel contentPane;
    private int numero;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    int numero = Integer.parseInt(JOptionPane.showInputDialog("Digite o nome do aluno.");
                    String nome = JOptionPane.showInputDialog("Digite o nome do aluno.");
                    Aluno frame = new Aluno(numero, nome);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void salvar(String texto) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(NOTAS, true))) {
            writer.write(texto);
            writer.newLine();
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null, "Um erro inesperado ocorreu:\n" + e1.toString());
        }
    }

    private JCheckBox criarCheckDanificado(String nome, boolean masculino, final JTextArea area, int x, int y, int w, int h) {
        final JCheckBox equipamento = new JCheckBox(nome);
        equipamento.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (equipamento.isSelected()) {
                    String texto;
                    if (masculino) {
                        texto = "O " + nome + " está danificado";
                    } else {
                        texto = "A " + nome + " está danificada";
                    }
                    salvar(texto);
                    area.append(texto + "\n");
                }
            }
        });
        equipamento.setToolTipText("Selecionar caso esteja danificado");
        equipamento.setBounds(x, y, w, h);
        contentPane.add(equipamento);
        return equipamento;
    }

    /**
     * Create the frame.
     */
    public Aluno(int numero, String nome) {
        this.numero = numero;
        setResizable(false);
        setIconImage(Toolkit.getDefaultToolkit().getImage(ICON));
        setTitle("PC" + numero + "-" + nome);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("Detalhes/Notas:");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 17));
        lblNewLabel.setBounds(10, 106, 194, 23);
        contentPane.add(lblNewLabel);

        JLabel lblNewLabel_1 = new JLabel("Localiza\u00E7\u00E3o da avaria:");
        lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 17));
        lblNewLabel_1.setBounds(10, 11, 169, 20);
        contentPane.add(lblNewLabel_1);
        File file = new File(NOTAS);
        FileInputStream fis = null;
        String texto = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                texto += (char) content;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 128, 414, 85);
        contentPane.add(scrollPane);

        JTextArea textArea1 = new JTextArea(texto);
        scrollPane.setViewportView(textArea1);
        textArea1.setEditable(false);
        textArea1.setWrapStyleWord(true);

        JCheckBox teclado = criarCheckDanificado("Teclado", true, textArea1, 6, 54, 94, 23);
        JCheckBox rato = criarCheckDanificado("Rato", true, textArea1, 98, 54, 81, 23);
        JCheckBox monitor = criarCheckDanificado("Monitor", true, textArea1, 181, 54, 96, 23);
        JCheckBox torre = criarCheckDanificado("Torre", false, textArea1, 288, 54, 109, 23);

        JButton adicionarNotas = new JButton("Escrever novas notas");
        adicionarNotas.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fazJa(evt);
            }
        });

        adicionarNotas.setBounds(137, 224, 159, 23);
        contentPane.add(adicionarNotas);
        this.setVisible(true);
    }

    protected void fazJa(ActionEvent evt) {
        this.dispose();
        new Gravação_Dados().setVisible(true);
    }
}

Note that now we have only one class Aluno and once we encapsulate the logic of creating the checkboxes, it became much cleaner than the original(s) (is).

Third step:

In your class PARTE2, the logic of button creation is quite repetitive. I will also extract it in a separate function to simplify:

    private JButton criarBotao(int numero, String nome, int x, int y) {
        JButton pc = new JButton("PC " + numero);
        pc.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno(numero, nome);
            }
        });
        pc.setBounds(x, y, 138, 84);
        contentPane.add(pc);
        return pc;
    }

And so that’s how your class gets:

public class PARTE2 extends JFrame {

    private static final String PLANTA = "C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\icons\\Science-Classroom-icon.png";
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    PARTE2 frame = new PARTE2();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private JButton criarBotao(int numero, String nome, int x, int y) {
        JButton pc = new JButton("PC " + numero);
        pc.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Aluno(numero, nome);
            }
        });
        pc.setBounds(x, y, 138, 84);
        contentPane.add(pc);
        return pc;
    }

    /**
     * Create the frame.
     */
    public PARTE2() {
        setExtendedState(Frame.MAXIMIZED_BOTH);
        setIconImage(Toolkit.getDefaultToolkit().getImage(PLANTA));
        setTitle("Planta da Sala de Aula");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton PC_1 = criarBotao(1, "Magda", 10, 586);
        JButton PC_2 = criarBotao(2, "Carolina", 10, 496);
        JButton PC_3 = criarBotao(3, "Pedro", 10, 406);
        JButton PC_4 = criarBotao(4, "Alexandre", 10, 3164);
        JButton PC_5 = criarBotao(5, "Tomas", 10, 226);
        JButton PC_6 = criarBotao(6, "Raul", 10, 136);
        JButton PC_7 = criarBotao(7, "Ruben Gato", 10, 436);
        JButton PC_8 = criarBotao(8, "Jorge", 269, 46);
        JButton PC_9 = criarBotao(9, "Joao", 469, 46);
        JButton PC_10 = criarBotao(10, "Miguel", 669, 46);
        JButton PC_11 = criarBotao(11, "Diogo", 869, 46);
        JButton PC_12 = criarBotao(12, "Miguel", 1214, 46);
        JButton PC_13 = criarBotao(13, "Francisco", 1214, 136);
        JButton PC_14 = criarBotao(14, "Ze", 1214, 226);
        JButton PC_15 = criarBotao(15, "Floriano", 1214, 316);
        JButton PC_16 = criarBotao(16, "Ruben", 1214, 406);
        JButton PC_17 = criarBotao(17, "Edmara", 1214, 497);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBackground(SystemColor.menu);
        menuBar.setBounds(0, 0, 1362, 21);
        contentPane.add(menuBar);

        JMenu ficheiro = new JMenu("Ficheiro");
        menuBar.add(ficheiro);

        JMenuItem sair = new JMenuItem("Sair");
        sair.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object[] options = { "Sim", "Não" };
                int selectedOption = JOptionPane.showOptionDialog(null, "Deseja realmente sair do programa?", "Planta Sala-Sair",
                        JOptionPane.INFORMATION_MESSAGE, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

                if (selectedOption == JOptionPane.YES_OPTION) {
                    dispose();
                }
            }
        });
        sair.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        sair.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
        ficheiro.add(sair);

        JMenu mnAjuda = new JMenu("Ajuda");
        menuBar.add(mnAjuda);

        JMenuItem precisoajuda = new JMenuItem("Preciso de Ajuda");
        mnAjuda.add(precisoajuda);

        JMenuItem mntmNewMenuItem_1 = new JMenuItem("Sobre");
        mntmNewMenuItem_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Menu_Sobre().setVisible(true);
            }
        });
        mnAjuda.add(mntmNewMenuItem_1);

        JButton secretaria = new JButton("Secret\u00E1ria");
        secretaria.setAlignmentX(Component.CENTER_ALIGNMENT);
        secretaria.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Relatorio_().setVisible(true);
            }
        });
        secretaria.setFont(new Font("Tahoma", Font.PLAIN, 22));
        secretaria.setBounds(404, 529, 554, 141);
        contentPane.add(secretaria);
    }
}

Fourth step:

In class Gravação_Dados, Look at your open button:

        final JButton Abrir = new JButton("Abrir");
        Abrir.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                Abrir.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {

                        // Código omitido...

                    }
                });
            }
        });
        Abrir.setBounds(168, 205, 89, 23);
        contentPane.add(Abrir);

This is wrong! You are using two actions listeners. When you first click, nothing happens to the user, but it creates another one ActionListener. By clicking on the second it saves, but the first ActionListeneralso runs and creates a third party ActionListener. By clicking the third time, it saves twice and creates a fourth ActionListener. That’s not what you want. Just use one ActionListener.

Fifth step:

You should already be impatient, and as to your purpose of recording in files alunoX, alunoY, etc.?

Let’s go back to the method salvar that I created in class Aluno:

    private static final String NOTAS = "C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\notas.txt";

    private void salvar(String texto) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(NOTAS, true))) {
            writer.write(texto);
            writer.newLine();
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null, "Um erro inesperado ocorreu:\n" + e1.toString());
        }
    }

Remember I added the student number to the constructor? So, right at the beginning of the constructor, I store it in a field, so you can do this:

    private static final String NOTAS = "C:\\Users\\João Gil\\workspace\\sala de aula\\pic\\aluno$.txt";

    private void salvar(String texto) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(NOTAS.replace("$", String.valueOf(numero)), true))) {
            writer.write(texto);
            writer.newLine();
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null, "Um erro inesperado ocorreu:\n" + e1.toString());
        }
    }

Sixth step:

In class Gravação_Dados, you read and save in the same class file Aluno. Use the same technique of passing the student number as a parameter in the constructor in this class. Also, separate the code that reads and writes files into methods, never leave them inside ActionListeners, because this is a bad programming practice.

Seventh step:

The Java naming rules say that variable names and methods should start with lowercase letters and follow the camelCase pattern. That is to say, use teclado instead of Teclado, utilize abrir instead of Abrir, utilize precisoDeAjuda instead of Preciso_de_ajuda, utilize fazJa instead of FAZJA, utilize adicionarNotas instead Adicionar_notas.

Nomenclature rules also state that classes have a nomenclature pattern similar to variables and methods, but starting with uppercase letters. That is, use MenuSobre instead of Menu_Sobre.

These rules of nomenclature may seem unnecessary and dispensable, but they are not. By not following them, it is difficult to know if a given name is a class or a variable or a method. Right here in Stackoverflow’s syntax coloring it determines the colors of the words in the source code based on that. This nomenclature convention does not exist for nothing.

Also, do not use accented characters in class names (eg: Gravação_Dados). The reason is that the class is compiled into a file <nome da classe>.class, and since different operating systems use different encodings for accented characters you end up introducing a portability problem causing your class not to work on other operating systems. Some tools that read files .zip and .jar also have problems with accents in filenames.

And finally the name of variables and classes should be well chosen. For example PARTE2 is a bad name for a class because it does not describe what it does, what it represents or what its purpose is. Already mntmNewMenuItem_1 also does not describe what is or what the variable in question is for.

Other considerations:

  • To perform input and output operations, always prefer to use the Try-with-Resources to simplify the code. An example of this is the method salvar that I demonstrated above. But this is only for Java >= 7.

  • Never coma exceptions, that is, never neglect them with } catch (Exception e1) {}. Simply put } catch (Exception e1) { e1.printStackTrace(); } Nor is it usually good, since your system keeps ignoring the occurrence of an error as if nothing had happened. Also, in Swing applications, often the console where the exception will appear will not be visible.

  • To facilitate development, do not mix code that handles code files that manipulates screen components. That is, don’t put them inside ActionListeners, instead, put them in separate methods for this purpose.

  • Avoid file paths hardcoded. That is to say, "C:\\Users\\Jo\u00E3o Gil\\workspace\\sala de aula\\pic\\dica.png". Because that means that if you put the code on any computer other than yours, the system won’t work! The ideal is to use relative paths to read and save files, or allow the user to tell which folder the files are located in. In the case of figures, if your application is inside a file .jar, use the method Class.getResource(String) would be the best option.

  • It is convenient to put the setVisible(true) inside your screen builder, this avoids having to call you every time your screen is created.

  • If you are using Java 8, some lambda-Expressions would greatly simplify your code. For example, instead:

    precisoDeAjuda.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new Ajuda().setVisible(true);
        }
    });

You can use this:

    precisoDeAjuda.addActionListener(e -> new Ajuda().setVisible(true));
  • 1

    thanks @Victor from now on for all the work you’ve had now I won’t have much time to do the program but when I have if it is what I want I give approved or there it is, thank you very much

  • 1

    thank you very much for the work you’ve done !

  • 1

    @Joaogil. You’re welcome. Whenever you need it, there will be someone here at Stackoverflow PT available to help you.

  • 1

    I don’t know how to thank I’m in 12 years and I have a discipline where I only give basic and pascal and the teacher doesn’t know how to help me thanks!

  • @Joaogil If this was the answer you were looking for, click on the "accept answer" button. If that still doesn’t answer your question, explain it so you can improve it further. :)

  • I’m having some mistakes in the new class with the variables student and number but I do not have time now but I will certainly accept your answer, I do not know if you compiled the code but gave you so some error?

  • @Joaogil Oh, sorry, I had two extra parentheses and I was TextArea instead of JTextArea. In the first part, the method criarCheckDanificado was different from the second part. I already packed. This occurred because I’ve been through a lot of files and the version that I copied-and-paste here wasn’t the last, but now it’s right.

  • friend Victor was away for a while without programming but now I was taking a great look at the program, instead of appearing a message for me to say the number and the name I wanted as soon as the user pressed the button he knew in which file he was going to write, the harm was mine because I should have specified that I wanted several txt documents instead of a single called notes if you remember

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.