Boa noite pessoal.
Estou com uma dúvida e gostaria que me ajudassem, por favor. Estou usando o Netbeans e criei uma interface gráfica que vocês podem ver abaixo. Criei uma outra classe e gostaria de fazer ela acessar um componente da classe da interface gráfica, mais especificamente o objeto “jTextArea2”. Para fazer isso mudei as restrições dos objetos e deixei eles como “protected”. Extendi a classe “Historico” e fiz como mostrado abaixo no código. O problema é que o Netbeans não aponta erro nenhum, mas o jTextArea2 não mostra nada.
Obs. Para facilitar, olhe diretamente o método “private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)” e o arquivo “Historico.java”.
Coloquei os três arquivos para o caso de alguém querer compilar. Para testá-lo você pode fazer ele ler e mostrar na tela o conteúdo de um arquivo de texto.
[code]// Arquivo Interface.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Interface extends javax.swing.JFrame {
public Interface() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Abrir");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Executar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Fechar");
jLabel1.setText("Abaixo você pode ver o conteúdo do arquivo.");
jLabel2.setText("Nenhum arquivo selecionado ainda.");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(453, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(21, 21, 21)
.addComponent(jButton3)
.addGap(0, 233, Short.MAX_VALUE))
.addComponent(jScrollPane2))
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addContainerGap())
);
jTabbedPane1.addTab("tab1", jPanel1);
jTextArea2.setColumns(20);
jTextArea2.setRows(5);
jScrollPane1.setViewportView(jTextArea2);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 856, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
.addContainerGap())
);
jTabbedPane1.addTab("tab2", jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jTabbedPane1))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setDialogTitle("Arquivos");//Define o nome da janela.
jFileChooser.setMultiSelectionEnabled(true);//Ativa a opção de selecionar múltiplos arquivos.
int abriu = jFileChooser.showOpenDialog(this);
num_linhas = 0; //Zera o número de linhas.
if (abriu == JFileChooser.APPROVE_OPTION) {
try {
this.arquivo = jFileChooser.getSelectedFile();
String caminho = arquivo.getAbsolutePath();
FileReader reader = new FileReader(arquivo);
BufferedReader leitor = new BufferedReader(reader);
if (arquivo.exists() && arquivo.canRead() && arquivo.isFile()) {//Testa se o arquivo existe, se pode ser lido e se é um arquivo.
this.jTextArea1.setText(null);
String linha;
do {
linha = leitor.readLine();//Pega uma linha do arquivo.
if (linha != null) {
this.jTextArea1.append(linha);//Coloca no componente jTextArea1 a linha pega no arquivo lido.
this.jTextArea1.append("\n");
num_linhas++;
}
} while (linha != null);
leitor.close();
reader.close();
this.jLabel2.setText("O arquivo tem " + num_linhas + " linhas.");
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Arquivo não encontrado.", "Erro", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Erro no arquivo.", "Erro", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
this.hist = new Historico(num_linhas);
this.hist.preenche_matriz(arquivo);
//O trecho abaixo funciona, mas o método "preenche_matriz(arquivo)" que está acima, não funciona.
//this.jTextArea2.append("Se isto aparecer, então o componente funcionou.");
}//GEN-LAST:event_jButton2ActionPerformed
public static void main(String args[]) {
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(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Interface().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
protected javax.swing.JButton jButton1;
protected javax.swing.JButton jButton2;
protected javax.swing.JButton jButton3;
protected javax.swing.JLabel jLabel1;
protected javax.swing.JLabel jLabel2;
protected javax.swing.JPanel jPanel1;
protected javax.swing.JPanel jPanel2;
protected javax.swing.JScrollPane jScrollPane1;
protected javax.swing.JScrollPane jScrollPane2;
protected javax.swing.JTabbedPane jTabbedPane1;
protected javax.swing.JTextArea jTextArea1;
protected javax.swing.JTextArea jTextArea2;
// End of variables declaration//GEN-END:variables
protected int num_linhas; // Será usada para contar o número de linhas do arquivo lido.
protected File arquivo;
protected Historico hist;
}[/code]
[code]// Arquivo Historico.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Historico extends Interface
{
Integer[][] matriz;
public Historico(int num_linhas)
{
System.out.println("Matriz será criada com "+num_linhas+" e 6 colunas.");
}
//Netbeans não acusa erro, mas também não contece nada no componente que eu quero.
//O argumento “arquivo” eu precisarei depois, no momento só estava testando sem ele.
public void preenche_matriz(File arquivo)
{//Objeto “jTextArea2” que é da classe pai sendo invocado nessa classe e falhando vergonhosamente.
this.jTextArea2.append(“Se isto aparecer, então o componente funcionou.”);
}
}[/code]
// Arquivo Main.java
public class Main
{
public static void main(String[] args)
{
Interface janela = new Interface();
janela.setVisible(true);
}
}
Obrigado.