//New to java swing and need help getting the text in the first Jtextfield to display in the //second second jtextfield???? Im young and just starting out in java and need some help. below is the code i have done already thanks
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class lab4 extends JFrame implements ActionListener {
int numClicks = 0;
String text = null;
public lab4() {
setSize(1200, 700);
setVisible(true);
JButton button = new JButton("Hello i am a button");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
panel.add(button);
this.add(panel);
JMenuBar menubar = new JMenuBar();
this.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem open = new JMenuItem("Open File");
file.add(open);
final JTextField myField = new JTextField(10);
myField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = myField.getText();
//System.out.println("Hello");
}
});
final JTextField myField2 = new JTextField(10);
yField2.setText(myField.getText());
panel.add(myField);
panel.add(myField2);
setVisible(true);
}
}
public static void main(String[] args) {
new lab4();
}
public void actionPerformed(ActionEvent e) {
numClicks++;
System.out.println("The button has been clicked " + numClicks + " times");
}
}
Yes, you are doing ok. If more then one work going to happen in sequence on one action event, then you need to put the sequence inside the corresponding actionPerformed
function. So:
myField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String text = myField.getText();
myField2.setText(text);
}
});
JComponents listeners mean that they will listen and respond only when an action event occur. They will be notified by the instance of ActionListener
registered to event source(JCompnent
) with addActionListener()
function as you have done.
One more thing to note: you can't access a field in any statement before even declaring it. Compiler's need to know the information about the field before doing anything with it. So you must declare myField2
before the accessing-code of it, such as, myField1
's anonymous class
ActionListener
actionPerformed
function.
Tutorial Resources: