我的节目是关于一家超市的。当我编译程序时,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);
您的交付方法中的两个框架都有此设置。
要使一个出现在另一个之后,请更改此设置,以便将一个设置为可见,而另一个在按钮 ie 的代码中取消设置(不过,显然您必须在此之前声明 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 。这将允许您获取用户等待响应的输入形式,然后提示进行下一个输入。 Click here for tutorial on Dialogs
在向框架/面板添加组件时,您可能还想查看一些布局。 GridLayout , BorderLayout , FlowLayout
关于java - 如何使 JFrame 窗口仅在我按下前一个 JFrame 窗口的 JButton 后才出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17399556/