我有一点问题。我创建了2个JFrame,在main主题中我想显示一个String名称。在另一个我可以提供我的名字。当我保存我的姓名'到变量名称,它不会在主框架中更新。如何更新此框架?
public class Main extends JFrame {
IFrame frame = new IFrame ("Main");
JButton button_name = new JButton("Enter your name");
IFrame frame_name = new IFrame ("What is your name?");
Point center =
GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint(); //Get center of screen
static Image Icon = Toolkit.getDefaultToolkit().getImage("Icon.png");
ButtonListener button_listen = new ButtonListener();
/**************************************************************************/
String name = new String();
JButton button_get_name = new JButton("OK");
JTextField field_name = new JTextField(15);
JPanel panel_name = new JPanel();
/**************************************************************************/
public Main(){
this.setIconImage(Icon);
button_name.addActionListener(button_listen);
button_get_name.addActionListener(button_listen);
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(4,1));
frame.add(new JLabel (name, SwingConstants.CENTER));
frame.add(button_name);
frame.add(new JLabel ("Table 2", SwingConstants.CENTER));
frame.add(panel_name);
frame.setBounds(center.x - 400 / 2, center.y - 400 / 2, 400, 400); //Set window in a center of screen
frame.setVisible(true);
/**********************************************************************/
panel_name.setBackground(Color.CYAN);
/**********************************************************************/
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main();
}
//Class responsible for detectin which button was pushed
public class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button_name){
CreateFrameName();
}
if (e.getSource() == button_get_name){
GetName();
}
}
}
//Creates a frame for name provide
public void CreateFrameName() {
int frame_name_width = 280;
int frame_name_height = 100;
frame.dispose();
frame_name.setBounds(center.x - frame_name_width / 2, center.y -
frame_name_height / 2, frame_name_width, frame_name_height);
frame_name.setLayout(new GridLayout(2,1));
frame_name.add(field_name);
frame_name.add(button_get_name);
frame_name.setAlwaysOnTop(true);
frame_name.setVisible(true);
}
public void GetName() {
name = field_name.getText();
frame_name.dispose();
frame.setVisible(true);
System.out.println(name);
}
}