我是一个新手,但正在尝试用 Java/Swing 编写我的第一个 GUI。我已经对此进行了彻底的研究,主要使用 Javadoc,但我不明白为什么我的 JOptionPane 不显示我的两个 JTextField 中接受的输入。
请不要建议使用布局管理器,我想首先尝试使用我自己的坐标,并且将来可能会考虑布局管理器。
我只是在寻找正确方向的一个点,而不是有人为我做这件事。这是我的代码片段。
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);
}
}
}
最佳答案
当按下confirmNames时,您需要从JTextField中获取文本,否则它将在创建JTextField时立即从JTextField中获取文本。
if(e.getSource()==confirmNames) {
String firstName = myTextField.getText();
String surname = myTextField2.getText();
playerFullName = firstName + surname;
JOptionPane.showMessageDialog(f3, "This works" + playerFullName);
}
关于java - 如何在 JOptionPane 消息中显示 JTextfield 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38012717/