I found some similar issues in the English version, but I could not resolve it.
I have a Boiler class, with the following attributes:
- Boiler temperature;
- Water quantum;
- 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 to not explode. To do this, as the water evaporates, I add more water (so as not to overheat), and if you add too much water and the temperature drops too much, the temperature of the fire increases.
The problem is that I need to do in 3 different classes (Boiler, Boost Fire and Add Water - each on a different screen) using the Singleton design pattern.
Then I have a button (increase temperature) to open a screen where I can increase the temperature of the fire and thus increase the temperature of the boiler:
ThenIwillhavethe(andclass/screen)buttontoaddwatertoo,butIonlydidthefirefornow.
IcannotupdatethefieldsJTextField
ofthetemperatures(firetemperature(jTextFieldMostraTempFogo
)-andboiler(jTextFieldMostraTempCaldeira
)inacoolway.AumentarFogo
.Thefieldsareasfollows:
1st-Attempt:
publicvoidpreencherTemperaturas(){jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));}
IcreatedthismethodintheBoilerclassandcalleditinsidetheIncreaseFirebuttonintheIncreaseFireclass:
privatevoidjButtonAumentarFogoActionPerformed(java.awt.event.ActionEventevt){Caldeira.getInstance().aumentarFogo(10);//acrescenta+10natemp.dofogoCaldeira.getInstance().preencherTemperaturas();}
Thefunnythingisthatitactuallychangestheattributes,butdoesnotupdatethejText.
2ndAttempt(thisworks,butonlyrefresheswhenIopentheBootScreenagain:
privatevoidjButtonAbrirTelaFogoActionPerformed(java.awt.event.ActionEventevt){AumentarFogoaumentarFogo=newAumentarFogo();aumentarFogo.setVisible(true);//únicajeitoquefunciona.jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));jTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));}
Thatis,IcanonlychangethevaluesofJTextField
whenIexecuteacommandinsidetheboilerclassitself.ButthevaluesoftheattributesarechangingwhenIclickthebuttonintheAumentarFogoclass.I'vetriedalotofthings,Itriedtoputthebackbutton,sinceitsendsmebacktothemainclass,butitdoesnotworkeither.
IthoughtofusingatimerlistenerasIsawinsomeofthestackquestioninEnglish,butIcouldnotimplementitatall,soIdecidedtoseeifitwouldhaveanyotherway.
ThejTextvariablesarenotstatic.Ievenputthemlikethistodoatest,butthentheydonotchangeinanyway,nordotheyhavetoupdatefromwithintheBoilerclass.
Completeclasses:
BoilerClass:
packagecaldeira;publicclassCaldeiraextendsjavax.swing.JFrame{privatestaticCaldeiracaldeira=null;//declaraçãodaclassestaticconformepadrãodeprojetoSingletonprivatefinalintTEMPERATURAMAXIMA=500;//temperaturamáximaemCºqueacaldeirapodeficarprivatefinalintTEMPERATURAMINIMA=100;//temperaturamínimaemCºqueacaldeirapodeficarprivatefinalintTEMPERATURAMAXIMAFOGO=600;//temperaturamáximaemCºquepodecolocarofogoprivatestaticinttemperaturaCaldeira=120;//valoresiniciaisdosatributosprivatestaticintquantLitrosAgua=100;privatestaticinttemperaturaFogo=130;privateCaldeira(){//construtorprivadoconformepadrãodeprojetoSingletoninitComponents();setLocationRelativeTo(null);jTextFieldMostraTempCaldeira.setText(Integer.toString(temperaturaCaldeira));//jainstanciaocampodetextotempcaldeiracomovalorjTextFieldMostraTempFogo.setText(Integer.toString(temperaturaFogo));//jainstanciaocampodetextotempfogocomovalorSystem.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
}
Class AumentarFogo:
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
}