[英]How to make a JFrame window appear only after I press the JButton of the previous JFrame window?
我的程序是关于一家超级市场的。 当我编译程序时,JFrame窗口“ f1”和“ f2”都出现在屏幕上。 但是我希望首先显示JFrame窗口'f1',然后单击'f1'窗口的JButton'b1'之后,我希望JFrame窗口'f2'出现。 下面是我程序的delivery()方法:
public static void delivery()
{
final JFrame f1 = new JFrame("Name");
GridLayout grid = new GridLayout(20, 40, 10, 8);
f1.setLayout(grid);
f1.setVisible(true);
f1.setSize(600,200);
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setLocation(700,450);
JPanel p1 = new JPanel();
final JLabel l1 = new JLabel("Enter your name: ");
final JTextField jt1 = new JTextField(20);
JButton b1 = new JButton("Ok");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input1 = jt1.getText();
f1.dispose();
}
});
p1.add(b1);
p1.add(l1);
p1.add(jt1);
f1.add(p1);
final JFrame f2 = new JFrame("Address");
f2.setVisible(true);
f2.setSize(600,200);
f2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f2.setLocation(700,450);
JPanel p2 = new JPanel();
final JLabel l2 = new JLabel("Enter your address: ");
final JTextField jt2 = new JTextField(20);
JButton b2 = new JButton("Ok");
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input2 = jt2.getText();
f2.dispose();
}
});
p2.add(b1);
p2.add(l2);
p2.add(jt2);
f2.add(p2);
JOptionPane.showMessageDialog(null, "The ordered stuff will be delivered to " +input1+ " who lives in: " +input2 , "Delivery" , JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null, "Thank you for shopping at Paradise 24/7. Hope to see you again." , "Shopping Done!" , JOptionPane.PLAIN_MESSAGE);
}
使框架出现的代码行是这个
f1.setVisible(true);
您的投放方式中的两个框架都具有此功能。
为了使一个在另一个更改之后出现,以便在按钮的代码中将一个设置为可见,而另一个设置为未设置(即,尽管您显然必须在此之前声明f2)
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input1 = jt1.getText();
f1.dispose();
//f1.setVisible(false); // or dispose if you no longer need it
f2.setVisible(true);
}
});
只是一个建议:更好的方法可能是使用JDialog 。 这将允许您从用户等待响应的表单中获取输入,然后提示下一个输入。 单击此处获取对话框教程
在为框架/面板添加组件时,您可能还需要查看一些布局。 GridLayout , BorderLayout , FlowLayout
只需添加代码f2.setVisible(true);
在Button的actionPerformed()
中。
例如
f1.setBounds(whatever);
f2.setBounds(whatever);
//add button in JFrame and actionListener
f1.setVisible(true);
f2.setVisible(false);
actionPerformed(ActionEvent e)
{
f2.setVisible(true);
}
然后,您必须先阅读JavaDocs并阅读一些适用于Java初学者的优秀电子书,例如Java 2 Complete Reference,O'Really-Java Swing将对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.