Hola buenas tardes amigos ,
Tengo una duda ...
Como ejecutar un evento sobre un componente Swing de un JFrame desde otro JFrame.
Por Ejemplo de el JFrame1 existe un JLabel , como hacer para que desde un JFrame2 pueda asignarle un nuevo texto al JLabel de JFrame1.
Gracias por su atencion :)
No es muy dificil, si lo tienes en un mismo Jar
Solo tienes que tener la referencia del otro objeto que deseas usar
Es que si lo hago como esto :
JFrame1 JF ;
JF = new JFrame1();
JF.Jlabel.setText("nuevo texto");
No me aplica el nuevo texto al componente al JText
;(
Hola que tal, ando un poco de prisa.
Quieres hacer algo como esto? :-\
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class jFrame1 extends JFrame {
private JTextField jTextField1;
private jFrame2 jf2 = new jFrame2();
public jFrame1() {
iniciarInterfaz();
}
private void iniciarInterfaz() {
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("jFrame1");
setResizable(false);
setVisible(true);
getContentPane().setLayout(new FlowLayout());
jTextField1.setText("escribe algo y oprime enter");
jTextField1.setPreferredSize(new Dimension(200, 25));
jTextField1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
eventJTextField();
}
});
getContentPane().add(jTextField1);
pack();
}
private void eventJTextField() {
jf2.setVisible(true);
jf2.setText(jTextField1.getText());
}
public static void main(String args[]) {
new jFrame1();
}
}
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;
import java.awt.Dimension;
public class jFrame2 extends JFrame {
private JLabel jLabel1;
public jFrame2() {
initComponents();
}
private void initComponents() {
jLabel1 = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("jFrame2");
setResizable(false);
setLocation(50, 100);
getContentPane().setLayout(new FlowLayout());
jLabel1.setPreferredSize(new Dimension(200, 25));
getContentPane().add(jLabel1);
pack();
}
public void setText(String text) {
jLabel1.setText(text);
}
}
Eso entendí xD.
Un saludo
Pues tienes que aceder a la clase del frame que quieres modificar y desde ahi declarando la variable del objeto del control swing como static y public la modificas (static no es explicitamente necesario).
Saludos
Muchas gracias por sus respuesta,
la verdad estuve analizando mi pregunta y esta mal formulada. YA que efectivamente lo que ustedes me respondieron funciona. Pero en mi escenario no sirve simplemente declararlo , instanciarlo y ya. :(
Les "dibujare" mi escenario para que se comprenda mejor
JFrame
|
|-> JTabbedPane |--->JButton(Boton)
| |-> JPanel(JPanel1)--|
|-> JPanel --- |---> public void desactivar(){ Boton.setEnable(false);}
| |-> JPanel
|
| |-> JPanel
|-> JPanel ---
|-> JPanel(JPanel2)
...
bueno la cuestion es como hacer para que desde el JPanel2 pueda invocar a la función desactivar() que se encuentra en el Panel1 para que me desactive el JButton del Panel1.
Como mencione anteriormente ... no sirve...
//Codigo dentro de JPanel2
JPanel1 JP1;
JP1 = new JPanel1();
JP1.desactivar();
El código anterior no me saca ningún error pero no me efectúa ningún cambio sobre el GUI :(.
Espero puedan ayudarme a encontrar con la solución :D
Claro que ese code no funciona ya que es una nueva instancia del panel no la original.
Algunas soluciones
1. Puedes usar modificadores de acceso static o protected dependiendo.
2. Creas una variables privada dentro del jframe del panel1, ahora cuando agregas el panel panel2 le pasas por constructor el panel1 y lo guardas como referencia dentro de este. y así llamar el método desactivar();
3. Creas una variable privada dentro del jframe del panel1, y creas un método en jframe llamado desactivar() que cumpla la función que quieres, luego al panel2 le pasas por constructor el jframe y y así llamar al método desactivar() por la referencia del jframe.
Un saludo.
Tu respuesta es implementar un Gestor de JPanels, dicho gestor tendrá referencias a TODAS las JPanels agregadas al JTabbedPane , con ello , simplemente llamarás a las funciones del gestor para modificar el comportamiento de cualquier JPanel disponible en tu aplicación
JFrame
|
|-> JTabbedPane
| |-> JPanel(JPanel1)--|-------|
|-> JPanel --- |
| |-> JPanel(JPanelx)----------|
| |----->GestorTabs
| |-> JPanel(JPanely)----------|
|-> JPanel --- |
|-> JPanel(JPanel2)--|-------|
Bueno , te dejo un ejemplo que escribi, basándome en tu código , espero que te sirva, lo que hace es que toma el texto del textbox del primer JPanel y lo muestra en el label del segundo.
import javax.swing.JLabel;
import java.awt.Dimension;
import javax.swing.JPanel;
public class Ventana2 extends JPanel implements Gestionable {
private JLabel jLabel1;
private Gestor gestor;
public Ventana2(Gestor gestor) {
this.gestor = gestor;
initComponents();
}
private void initComponents() {
jLabel1 = new JLabel();
jLabel1.setPreferredSize(new Dimension(200, 25));
jLabel1.setText("Hola a todos");
this.add(jLabel1);
}
public void setText(String text) {
jLabel1.setText(text);
}
public Gestor getGestor(){
return this.gestor;
}
}
import javax.swing.JTextField;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Ventana1 extends JPanel implements Gestionable {
private JTextField jTextField1;
private Gestor gestor;
JButton boton = new JButton("Presiona aqui");
public Ventana1(Gestor gestor) {
this.gestor = gestor;
iniciarInterfaz();
}
private void iniciarInterfaz() {
GestorTabs gesorTabs = new GestorTabs(this);
jTextField1 = new javax.swing.JTextField();
jTextField1.setText("escribe algo y oprime enter");
jTextField1.setPreferredSize(new Dimension(200, 25));
jTextField1.addActionListener(gesorTabs);
boton.addActionListener(gesorTabs);
boton.setName("boton enviar");
this.add(jTextField1);
this.add(boton);
}
public JTextField getCajaTexto(){
return this.jTextField1;
}
public Gestor getGestor(){
return this.gestor;
}
}
public interface Gestionable {
public Gestor getGestor();
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class GestorTabs implements ActionListener{
Gestionable ventana;
public GestorTabs(Gestionable panel){
this.ventana = panel;
}
public void actionPerformed(ActionEvent e){
if(ventana instanceof Ventana1){
Ventana1 ven1 = (Ventana1)ventana;
this.ejecutarVentana1(ven1, ven1.getCajaTexto().getText());
}
}
/**
*
* @param ven
* @param textoMostrar
*/
public void ejecutarVentana1(Ventana1 ven, String textoMostrar){
Gestor ges = this.ventana.getGestor();
Ventana2 vent2 = (Ventana2)ges.getPanel("ventana 2");
vent2.setText(textoMostrar);
}
}
import java.awt.Component;
import java.awt.Container;
import javax.swing.JPanel;
public class Gestor {
Container container ;
public Gestor(Container conta){
this.container = conta;
}
/**
* Devuelve el panel especificado por nombre
* @param name
* @return
*/
public JPanel getPanel(String name){
Component []componentes = this.container.getComponents();
JPanel panel;
for(Component conp : this.container.getComponents()){
panel = (JPanel)conp;
if(name.equals(panel.getName())){
return panel;
}
}
return null;
}
}
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class Principal extends JFrame {
public static void main(String[] args) {
Principal prin = new Principal();
JTabbedPane panel = new JTabbedPane();
Gestor gestor = new Gestor(panel);
Ventana1 vent = new Ventana1(gestor);
Ventana2 vent2 = new Ventana2(gestor);
vent.setName("ventana 1");
vent2.setName("ventana 2");
panel.addTab("Ventana 1" ,vent);
panel.addTab("Ventana 2",vent2);
panel.setBounds(200, 5000, 6000 ,7000);
panel.setVisible(true);
prin.getContentPane().add(panel);
prin.setVisible(true);
prin.setBounds(500, 200, 500 ,500);
prin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Gracias amigos por sus respuestas , en la noche voy a probar sus soluciones y les cuento (Y).
Gracias :D