【发布时间】:2018-01-17 10:24:52
【问题描述】:
我刚开始在 java 中使用接口,我可以只拥有一个窗口并做我需要的事情。但我现在想将两个窗口链接在一起,例如
第 1 帧打开。 用户选择 button1(输入数据)。 第 2 帧打开,因此用户可以输入数据。
第 1 帧的代码:
import javax.swing.*;
public class Task_3 extends JFrame {
private Button btn1, btn2, btn3;
public Task_3(){
setLayout(new FlowLayout());
btn1 = new Button("Enter data");
add(btn1);
btn2 = new Button("Check who is going");
add(btn2);
btn3 = new Button("View costs");
add(btn3);
setTitle("Event Costs");
setSize(280, 150);
setVisible(true);
// close the window
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); //calling the method is a must
}
});
}
public static void main(String[] args){
new Task_3();
}
}
第 2 帧的代码:
import java.awt.*;
import java.awt.event.*;
public class Task1GUI extends Frame implements ActionListener {
private Label lblInput;
private Label lblOutput;
private TextField tfInput;
private TextField tfOutput;
private int sum = 0;
public Task1GUI(){
setLayout( new FlowLayout());
lblInput = new Label("Enter number of students: ");
add(lblInput);
tfInput = new TextField(5);
add(tfInput);
tfInput.addActionListener(this);
lblOutput = new Label("The cost per student is: ");
add(lblOutput);
tfOutput = new TextField(20);
tfOutput.setEditable(false);
add(tfOutput);
setTitle("Task1GUI");
setSize(350, 120);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); //calling the method is a must
}
});
}
public static void main(String[] args){
new Task1GUI();
}
@Override
public void actionPerformed(ActionEvent evt){
int numOfStudents = Integer.parseInt(tfInput.getText());
int coachCost = 550;
int entrycost = 30;
int totalcost;
int numFree;
int Discount;
int costPerPerson;
if(numOfStudents<45){
totalcost = coachCost+(numOfStudents*30);
numFree = numOfStudents/10;
Discount = numFree*30;
costPerPerson = (totalcost-Discount)/numOfStudents;
tfInput.setText("");
tfOutput.setText(costPerPerson+"");
}
else{
tfOutput.setText("Too mant students entered");
}
}
}
基本上,我需要一些帮助来将这两个程序链接在一起,以便用户可以打开第一帧选择他们想要执行的操作。
直到最近我才使用控制台,所以如果我的代码不完美,我深表歉意,但我非常感谢任何帮助。
如果这有帮助的话,我最终希望这个程序 https://repl.it/repls/FondAptXeme 有一个 GUI。
谢谢
【问题讨论】:
-
您的具体问题是什么?
-
我想让用户从第一个窗口中选择一个按钮,然后依次打开第二个窗口,他们可以在其中输入数据。
-
你在实现这个时遇到了什么问题?我明白你想要什么,这是我不明白的地方。
-
我不知道如何实现它。我可以创建单独的窗口,但如果有意义的话,不要将它们链接在一起。
-
为什么你认为两者之间存在差异?