Java 如何在JFrame内部访问Jpanel内部的JTextField内容?
我试图从另一个文件中的另一个Java类读取JFrame中JPanel中的JTextField的内容 在一个.java文件中,我有以下代码:Java 如何在JFrame内部访问Jpanel内部的JTextField内容?,java,swing,jframe,jpanel,jtextfield,Java,Swing,Jframe,Jpanel,Jtextfield,我试图从另一个文件中的另一个Java类读取JFrame中JPanel中的JTextField的内容 在一个.java文件中,我有以下代码: public class Ventana extends JFrame implements ActionListener { public Ventana() { setSize(500, 500); setTitle("Ventana"); setLocationRelativ
public class Ventana extends JFrame implements ActionListener {
public Ventana() {
setSize(500, 500);
setTitle("Ventana");
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel();
grafica();
}
public void actionPerformed(ActionEvent e) {
}
public void panel() {
JPanel panel = new JPanel();
panel.setBounds(0, 0, 500, 50);
panel.setVisible(true);
panel.setBackground(Color.DARK_GRAY);
JLabel etiqueta1 = new JLabel("A: ");
JLabel etiqueta2 = new JLabel("B: ");
JLabel etiqueta3 = new JLabel("C: ");
JTextField cuadroTexto1, cuadroTexto2, cuadroTexto3;
cuadroTexto1 = new JTextField(" ");
cuadroTexto2 = new JTextField(" ");
cuadroTexto3 = new JTextField(" ");
JButton boton = new JButton("Calcular");
panel.add(etiqueta1);
panel.add(cuadroTexto1);
panel.add(etiqueta2);
panel.add(cuadroTexto2);
panel.add(etiqueta3);
panel.add(cuadroTexto3);
panel.add(boton);
this.getContentPane().add(panel, BorderLayout.NORTH);
this.validate();
}
// more code under...
在另一个.java文件中,我正在尝试:
public class Controlador implements ActionListener{
private Ventana vista;
private Datos modelo;
public Controlador( Ventana vista , Datos modelo){
this.vista = vista;
this.modelo = modelo;
}
//Inicia los valores del jFrame Ventana con los datos del MODELO "Datos".
public void iniciar_vista(){
vista.setTitle( "Demo" );
}
public void actionPerformed(ActionEvent e) {
modelo.setA( Integer.valueOf( vista.cuadroTexto1.getText() ) );
}
}
因此,我试图做的是在代码的最后一行访问“cuadroTexto1”,读取同意将其发送到另一个变量,但我不知道如何做
我不确定你是否有提供答案所需的所有信息。如果是这种情况,我将回答您的任何问题。您需要在构造函数之前声明cuadroTexto1
public class Ventana extends JFrame implements ActionListener {
JTextField cuadroTexto1; //declaration
public Ventana() {
setSize(500, 500);
setTitle("Ventana");
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel();
grafica();
您可能还需要为cuadroTexto1添加一个getter,具体取决于cuadroTexto1 java文件的位置您需要在构造函数之前声明cuadroTexto1
public class Ventana extends JFrame implements ActionListener {
JTextField cuadroTexto1; //declaration
public Ventana() {
setSize(500, 500);
setTitle("Ventana");
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel();
grafica();
您可能还需要为cuadroTexto1添加一个getter,具体取决于cuadroTexto1 java文件的位置