I am a newb, but trying to write my first GUI in Java/Swing. I have researched this thoroughly, mainly using the Javadoc, but I don't understand why my JOptionPane does not display the input accepted in my two JTextField's.
Please don't advise to use layout managers, I want to explore using my own co-ordinates first and might look at layout managers in the future.
I am just looking for a point in the right direction, not someone to do it for me. Here is my code snippet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
/**
*
* @author Darren Estcourt
*/
public class ManagerName implements java.io.Serializable , ActionListener
{
JFrame f3;
JLabel firstNameLabel , surnameLabel , fullName;
JButton confirmNames , quit;
String firstName , surname, playerFullName;
JTextField myTextField , myTextField2;
public ManagerName()
{
f3 = new JFrame("Create Profile");
f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstNameLabel = new JLabel("Please enter your first name");
firstNameLabel.setBounds(50,25,200,30);
f3.add(firstNameLabel);
myTextField = new JTextField(20); // or use 20 columns
f3.add(myTextField);
myTextField.setBounds(50,75,200,30);
myTextField.addActionListener(this);
String firstName = myTextField.getText();
surnameLabel = new JLabel("Please enter your surname");
surnameLabel.setBounds(50,125,200,30);
f3.add(surnameLabel);
confirmNames = new JButton("Submit Names");
confirmNames.addActionListener(this);
confirmNames.setBounds(50,225,200,30);
f3.add(confirmNames);
quit = new JButton("Quit");
quit.addActionListener(this);
quit.setBounds(50,325,200,30);
f3.add(quit);
myTextField2 = new JTextField(20);
f3.add(myTextField2);
myTextField2.setBounds(50,175,200,30);
myTextField2.addActionListener(this);
String surname = myTextField2.getText();
playerFullName = firstName + surname;
f3.setSize(500,500);
f3.setLayout(null);
f3.setVisible(true);
} // end managerName
public void setFrame(JFrame f3)
{
this.f3 = f3;
}
public JFrame getFrame()
{
return f3;
}
public String getManagerName()
{
return playerFullName;
}
@Override public void actionPerformed(ActionEvent e)
{
if(e.getSource()==confirmNames)
{
JOptionPane.showMessageDialog(f3, "This works" + playerFullName);
}
if(e.getSource()==quit)
{
System.exit(0);
}
}
}
You need to get the text from the JTextField when confirmNames is pressed, otherwise it would get the text from the JTextField right when it is created.
if(e.getSource()==confirmNames) {
String firstName = myTextField.getText();
String surname = myTextField2.getText();
playerFullName = firstName + surname;
JOptionPane.showMessageDialog(f3, "This works" + playerFullName);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.