Change Jtextfield value from another class or automatically

Asked

Viewed 545 times

3

I found some similar issues in the English version, but I could not resolve.

I have a boiler class, with the following attributes:

  • Boiler temperature;
  • how much;
  • Fire temperature;

In this program I will have to keep the boiler always above a minimum temperature to not stop working or below a maximum temperature not to explode. For this purpose, as the water evaporates, I add more water (not to overheat), and if too much water is added and the temperature falls too low, I increase the temperature of the fire.

The problem is that I need to do it in 3 different classes (Boiler, Increase Fire and Add - each on a different screen), using the Singleton design standard.

So I have a button (raise temperature) to open a screen where I can raise the temperature of the fire and thus raise the temperature of the boiler:

inserir a descrição da imagem aqui

Then I will have the button(and class/canvas) to add water too, but I only did the fire for now.

I can’t update the fields JTextField of temperatures (temperature of fire(jTextFieldMostraTempFogo) - and the boiler (jTextFieldMostraTempCaldeira) in a way that looks cool. By clicking the Increase Fire button inside class (screen) AumentarFogo. The fields are these:

inserir a descrição da imagem aqui

1st - Attempt:

public void preencherTemperaturas() { 

jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));
jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));

}

I created this method in the Boiler class and called it inside the Increase Fire button in the Increase Fire class:

inserir a descrição da imagem aqui

private void jButtonAumentarFogoActionPerformed(java.awt.event.ActionEvent evt) {                                                    

    Caldeira.getInstance().aumentarFogo(10); //acrescenta +10 na temp. do fogo
    Caldeira.getInstance().preencherTemperaturas();

}    

The funny thing is that it actually changes the attributes, but it doesn’t update jText.

2nd try (this one works, but only updates when I open the screen again:

private void jButtonAbrirTelaFogoActionPerformed(java.awt.event.ActionEvent evt) {                                                     
    AumentarFogo aumentarFogo = new AumentarFogo();
    aumentarFogo.setVisible(true);

    //única jeito que funciona.
    jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));
    jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));
}                                                    

I mean, I can only change the values of JTextField when I execute a command within the boiler class itself. But the attribute values are being changed when I click the Increase Fire class button. I have tried several things, I tried to put the back button, since it tells return to the main class, but also does not work.

I thought about using a Timer Reader as I saw in some questions of the stack in English, but I couldn’t implement it at all, so I decided to see if there was some other way.

The jText variables are not static. I even put them like this to do a test, but then they do not change in any way, nor have update from within the Boiler class.

Complete classes:

Caldeira Class:

package caldeira;

public class Caldeira extends javax.swing.JFrame {


    private static Caldeira caldeira = null; //declaração da classe static conforme padrão de projeto Singleton

    private final int TEMPERATURAMAXIMA = 500; //temperatura máxima em Cº que a caldeira pode ficar
    private final int TEMPERATURAMINIMA = 100; //temperatura mínima em Cº que a caldeira pode ficar
    private final int TEMPERATURAMAXIMAFOGO = 600; //temperatura máxima em Cº que pode colocar o fogo

    private static int temperaturaCaldeira = 120; // valores iniciais dos atributos
    private static int quantLitrosAgua = 100;
    private static int temperaturaFogo = 130;

    private Caldeira() { //construtor privado conforme padrão de projeto Singleton
        initComponents();
        setLocationRelativeTo(null);
        jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira)); //ja instancia o campo de texto tempcaldeira com o valor
        jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo)); //ja instancia o campo de texto tempfogo com o valor
        System.out.println("");
    }

    public void despejarLitrosDeAgua(int despejarLitrosDeAgua) { //acrescentar água para diminuir temperatura da caldeira
        quantLitrosAgua += 10;
    }

    public void aumentarFogo(int aumentoDoFogo) { // aumentar a temperatura do fogo para aumentar a temp. da caldeira
        temperaturaCaldeira += aumentoDoFogo;
        temperaturaFogo += aumentoDoFogo;
    }

    public static synchronized Caldeira getInstance() {
        if (caldeira == null) {
            caldeira = new Caldeira();
        }

        return caldeira;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButtonAbrirTelaFogo = new javax.swing.JButton();
        jButtonAbrirTelaAgua = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jTextFieldMostraTempCaldeira = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldMostraTempFogo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("C A L D E I R A O  ");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButtonAbrirTelaFogo.setText("Aumentar Temperatura");
        jButtonAbrirTelaFogo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAbrirTelaFogoActionPerformed(evt);
            }
        });

        jButtonAbrirTelaAgua.setText("Diminuir Temperatura");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 266, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 120, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTextFieldMostraTempCaldeira.setEditable(false);
        jTextFieldMostraTempCaldeira.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Temperatura Caldeirão");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Temperatura Fogo");

        jTextFieldMostraTempFogo.setEditable(false);
        jTextFieldMostraTempFogo.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextFieldMostraTempCaldeira, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldMostraTempFogo, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jLabel2)))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldMostraTempCaldeira, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldMostraTempFogo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonAbrirTelaFogo)
                            .addComponent(jButtonAbrirTelaAgua))))
                .addGap(27, 27, 27)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(63, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(jButtonAbrirTelaFogo)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonAbrirTelaAgua)))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("nome");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(171, 171, 171)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    public void preencherTemperaturas() { // uma das tentativas de alterar o valor dos campos de temperatura: NÃO FUNCIONA
        jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));
        jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));
    }

    private void jButtonAbrirTelaFogoActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        AumentarFogo aumentarFogo = new AumentarFogo();
        aumentarFogo.setVisible(true);

        //única jeito que funciona. Mas fica ruim ter que clicar em aumentar fogo de novo para atualizar.
        jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));
        jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));
    }                                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Caldeira().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonAbrirTelaAgua;
    private javax.swing.JButton jButtonAbrirTelaFogo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField jTextFieldMostraTempCaldeira;
    private javax.swing.JTextField jTextFieldMostraTempFogo;
    // End of variables declaration                   
}

Rising Class:

package caldeira;


public class AumentarFogo extends javax.swing.JFrame {

    public AumentarFogo() {
        initComponents();
        setLocationRelativeTo(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButtonAumentarFogo = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButtonVoltar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("AumentarFogo");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButtonAumentarFogo.setText("Aumentar Fogo");
        jButtonAumentarFogo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAumentarFogoActionPerformed(evt);
            }
        });

        jLabel1.setText("Aumenta a temperatura do Fogo");
        jLabel1.setToolTipText("");

        jButtonVoltar.setText("Voltar");
        jButtonVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jButtonAumentarFogo))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jButtonVoltar)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addComponent(jButtonAumentarFogo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonVoltar)
                .addGap(9, 9, 9))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(45, 45, 45))
        );

        pack();
    }// </editor-fold>                        

    private void jButtonVoltarActionPerformed(java.awt.event.ActionEvent evt) {                                              

        Caldeira caldeira = Caldeira.getInstance();
        Caldeira.getInstance().preencherTemperaturas(); // NÃO FUNCIONA
        dispose();

    }                                             

    private void jButtonAumentarFogoActionPerformed(java.awt.event.ActionEvent evt) {                                                    

        Caldeira.getInstance().aumentarFogo(10);
        Caldeira.getInstance().preencherTemperaturas(); //NÃO FUNCIONA

    }                                                   

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AumentarFogo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonAumentarFogo;
    private javax.swing.JButton jButtonVoltar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}
  • Where is the Singleton standard in the classes? Nothing about it. Is it really necessary to use Singleton for this? the api already has features, called listeners, for this.

  • One, the Singleton standard is in the private constructor, the "public Static Synchronized Caldeira getInstance()" method and the use of getInstance in the other class. I really think it is not ideal to use the Singleton standard in this case, but it is college work precisely to learn the Singleton standard.

  • Luis, none of this is necessary, see my answer below, you complicated something simple.

1 answer

4


With a few changes, it was possible to make your code work as expected without using Singleton. The main one is to avoid working with multiple Jframes, because there is a class JDialog, that makes it possible to work with windows dependent on a Jframe or other Jdialogs. Changing the class AumentarFogo for JDialog, you do not need to use Singleton or anything of the type to exchange data between the main frame and this subjanela.

Note: As your code is very large, I will comment only on the main changes I made, of the rest, you can check below the two updated classes.

  • First I changed the class heritage AumentarFogo for Jdialog and made some changes to the constructor, so that it can start correctly. You can refer to class documentation cited to better understand its parameters.

  • in the method of the button that increases the fire, I inserted the idea of a "click counter", in this way, just increment the counter each time the button is clicked and you will be able to know how much should increase in the field of the other screen.

  • In the back button method, with changes made in the class AumentarFogo, it becomes unnecessary to exist, but not to alter too much, I just left the dispose()in it.

  • As the modal screen keeps the main screen access interrupted until it is closed, to recover the value of the counter, I created the method getContador() that will return the number of times the button has been clicked times the factor you have already used to increase the value of the fire.

  • Now in class Caldeira, in the method AbrirTelaFogo, I delegated what you were doing in the other class, because as I turned it into Jdialog, the methods after the aumentarFogo.setVisible(true); will only be executed when the other screen is closed.

  • Tip: Don’t use identical names for methods and classes, especially in a giant code like this, you make the code even more unreadable. Try to give different names, but make sense of what the class/method actually does.

Finally, it follows both modified classes:

class Caldeira

import java.awt.Frame;

public class Caldeira extends javax.swing.JFrame {


private static Caldeira caldeira = null; //declaração da classe static conforme padrão de projeto Singleton

private final int TEMPERATURAMAXIMA = 500; //temperatura máxima em Cº que a caldeira pode ficar
private final int TEMPERATURAMINIMA = 100; //temperatura mínima em Cº que a caldeira pode ficar
private final int TEMPERATURAMAXIMAFOGO = 600; //temperatura máxima em Cº que pode colocar o fogo

private static int temperaturaCaldeira = 120; // valores iniciais dos atributos
private static int quantLitrosAgua = 100;
private static int temperaturaFogo = 130;

private Caldeira() { //construtor privado conforme padrão de projeto Singleton
    initComponents();
    setLocationRelativeTo(null);
    jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira)); //ja instancia o campo de texto tempcaldeira com o valor
    jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo)); //ja instancia o campo de texto tempfogo com o valor
    System.out.println("");
}

public void despejarLitrosDeAgua(int despejarLitrosDeAgua) { //acrescentar água para diminuir temperatura da caldeira
    quantLitrosAgua += 10;
}

public void aumentarFogo(int aumentoDoFogo) { // aumentar a temperatura do fogo para aumentar a temp. da caldeira
    temperaturaCaldeira += aumentoDoFogo;
    temperaturaFogo += aumentoDoFogo;
}

public static synchronized Caldeira getInstance() {
    if (caldeira == null) {
        caldeira = new Caldeira();
    }

    return caldeira;
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButtonAbrirTelaFogo = new javax.swing.JButton();
    jButtonAbrirTelaAgua = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    jPanel3 = new javax.swing.JPanel();
    jTextFieldMostraTempCaldeira = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jTextFieldMostraTempFogo = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("C A L D E I R A O  ");
    setResizable(false);

    jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jButtonAbrirTelaFogo.setText("Aumentar Temperatura");
    jButtonAbrirTelaFogo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonAbrirTelaFogoActionPerformed(evt);
        }
    });

    jButtonAbrirTelaAgua.setText("Diminuir Temperatura");

    jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 266, Short.MAX_VALUE)
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 120, Short.MAX_VALUE)
    );

    jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jTextFieldMostraTempCaldeira.setEditable(false);
    jTextFieldMostraTempCaldeira.setHorizontalAlignment(javax.swing.JTextField.CENTER);

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel2.setText("Temperatura Caldeirão");

    jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel3.setText("Temperatura Fogo");

    jTextFieldMostraTempFogo.setEditable(false);
    jTextFieldMostraTempFogo.setHorizontalAlignment(javax.swing.JTextField.CENTER);

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(46, 46, 46)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel3)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jTextFieldMostraTempCaldeira, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextFieldMostraTempFogo, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(35, 35, 35)
                    .addComponent(jLabel2)))
            .addContainerGap(36, Short.MAX_VALUE))
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addGap(40, 40, 40)
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jTextFieldMostraTempCaldeira, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(35, 35, 35)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jTextFieldMostraTempFogo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(87, 87, 87)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButtonAbrirTelaFogo)
                        .addComponent(jButtonAbrirTelaAgua))))
            .addGap(27, 27, 27)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(63, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(43, 43, 43)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(34, 34, 34)
                    .addComponent(jButtonAbrirTelaFogo)
                    .addGap(18, 18, 18)
                    .addComponent(jButtonAbrirTelaAgua)))
            .addContainerGap(28, Short.MAX_VALUE))
    );

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    jLabel1.setText("nome");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addGap(171, 171, 171)
            .addComponent(jLabel1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(32, 32, 32)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

public void preencherTemperaturas() { // uma das tentativas de alterar o valor dos campos de temperatura: NÃO FUNCIONA
    jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));
    jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));
}

private void jButtonAbrirTelaFogoActionPerformed(java.awt.event.ActionEvent evt) {                                                     
    AumentarFogo aumentarFogo = new AumentarFogo(this);
    aumentarFogo.setVisible(true);
    aumentarFogo(aumentarFogo.getcontador());
    preencherTemperaturas();

    //única jeito que funciona. Mas fica ruim ter que clicar em aumentar fogo de novo para atualizar.
    jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));
    jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));
}                                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Caldeira.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Caldeira().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButtonAbrirTelaAgua;
private javax.swing.JButton jButtonAbrirTelaFogo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JTextField jTextFieldMostraTempCaldeira;
private javax.swing.JTextField jTextFieldMostraTempFogo;
// End of variables declaration      
}

class AumentarFogo

public class AumentarFogo extends javax.swing.JDialog {

    private int contador;

public AumentarFogo(Frame owner) {
    //passa ao construtor do JDialog o vinculo entre a classe 
    // Caldeira e esta classe
    super(owner, true);
    initComponents();
    setLocationRelativeTo(owner);
    contador = 0;
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButtonAumentarFogo = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jButtonVoltar = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("AumentarFogo");
    setResizable(false);

    jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jButtonAumentarFogo.setText("Aumentar Fogo");
    jButtonAumentarFogo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonAumentarFogoActionPerformed(evt);
        }
    });

    jLabel1.setText("Aumenta a temperatura do Fogo");
    jLabel1.setToolTipText("");

    jButtonVoltar.setText("Voltar");
    jButtonVoltar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonVoltarActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(jButtonAumentarFogo))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(43, 43, 43)
                    .addComponent(jButtonVoltar)))
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addGap(27, 27, 27)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
            .addComponent(jButtonAumentarFogo)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jButtonVoltar)
            .addGap(9, 9, 9))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(19, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGap(45, 45, 45))
    );

    pack();
}// </editor-fold>                        

private void jButtonVoltarActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // com as alterações feitas, este método não precisa fazer mais nada
    // a nao ser fechar a janela
    dispose();
}                                             

private void jButtonAumentarFogoActionPerformed(java.awt.event.ActionEvent evt) {                                                    
    // aqui você só incrementa o contador para no final
    // calcular quantas vezes irá aumentaro fogo
    contador++;
}  



public int getcontador() {
    //método para você consultar
    // quantas vezes foi clicado
    return contador * 10;
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(AumentarFogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>


}

// Variables declaration - do not modify                     
private javax.swing.JButton jButtonAumentarFogo;
private javax.swing.JButton jButtonVoltar;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration     

}

See in operation:

inserir a descrição da imagem aqui

Browser other questions tagged

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