Boa tarde pessoas,
Tenho algumas telas em SWING por aqui, e estou tentando o seguindo, utilizando a API de reflection:
Carregar a classe que herda de JFrame, add um actionListener em um botão desse mesmo JFrame, e invocar o método Main dessa classe, o qual carrega o JFrame pro usuário.
Seguem as classes:
View1 (JFrame)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package views;
/**
*
* @author Administrador
*/
public class View1 extends javax.swing.JFrame {
/**
* Creates new form View1
*/
public View1() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
botao = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
botao.setText("jButton2");
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(21, Short.MAX_VALUE)
.addComponent(botao)
.addGap(18, 18, 18))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(botao)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* @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(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new View1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton botao;
// End of variables declaration
}
package teste;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import views.View2;
public class Teste2 {
public static void main(String[] args) {
try {
Class classe = Class.forName("views.View1");
try {
Object objeto = classe.newInstance();
try {
Field botao = classe.getDeclaredField("botao");
botao.setAccessible(true);
JButton instanciaDoBotao = (JButton) botao.get(objeto);
instanciaDoBotao.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ISSSSSSSSSOOOOOOOOO!!!");
}
});
} catch (NoSuchFieldException | SecurityException ex) {
Logger.getLogger(Teste2.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(Teste2.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Teste2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
package teste;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Teste3 {
public static void main(String[] args) {
Class classe;
try {
classe = Class.forName("views.View1");
Method metodoMain;
try {
metodoMain = classe.getMethod("main", args.getClass());
try {
Object metodoInvocado = metodoMain.invoke(null, new Object[]{args});
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Teste3.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchMethodException | SecurityException ex) {
Logger.getLogger(Teste3.class.getName()).log(Level.SEVERE, null, ex);
}
// Now invoke the method.
} catch (ClassNotFoundException ex) {
Logger.getLogger(Teste3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Como podem ver, ao executar a classe Teste2, não consigo fazer o JFrame carregar pq ele é carregado no método main da primeira classe View1, sendo que isso não posso mudar (o JFrane tem que ser carregado no método main da classe dele próprio).
Como faço pra poder chamar o método main, e obter a instancia da classe View1 para add o listener ao seu JButton?
Caso eu não tenha sido muito claro em algo, é só falar.
Muito obrigado desde já, abraços!