我正在尝试创建一个简单的程序,当我按下一个按钮时,会出现新的文本,但是我不知道该怎么做(我想这很简单)。
我现在拥有的代码是:
import java.awt.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button ("Terminate Program");
Button b2 = new Button ("Start");
b1.setBounds(50,50,50,50);
b2.setBounds(50,50,50,50);
b1.addActionListener(e-> System.exit(0));
Label txt = new Label ("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500,300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[]){
ConsumptionGUI frame1= new ConsumptionGUI();
} //end main
基本上,在此之后,我设法创建了一个带有2个按钮和中间一些文本的框架。 我真的很难从这里继续。
我需要该程序首先通过按一个按钮启动,然后打印一些新文本(例如“请输入您的汽车速度”),然后保存此信息(以简单的公式使用)。 之后,程序需要显示使用的公式并打印计算出的值。
有人可以帮忙吗?
谢谢
答案 0 :(得分:0)
要获得用户输入,可以像下面的代码一样实现Dialog
。您也可以使用另一个类似的对话框来显示公式和结果。
import java.awt.*;
import java.awt.event.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button("Terminate Program");
Button b2 = new Button("Start");
//b1.setBounds(50, 50, 50, 50); // Unnecessary
//b2.setBounds(50, 50, 50, 50); // Unnecessary
b1.addActionListener(e -> System.exit(0));
b2.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
InputDialog dialog = new InputDialog(fr);
dialog.setVisible(true);
System.out.println("User inputted speed = " + dialog.getSpeed());
}
});
Label txt = new Label("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500, 300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[])
{
ConsumptionGUI frame1 = new ConsumptionGUI();
} //end main
}
class InputDialog extends Dialog
{
private int speed;
InputDialog(Frame owner)
{
super(owner, "Input", true);
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
dispose();
}
});
TextField textField = new TextField(20);
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String speedString = textField.getText();
speed = !speedString.isEmpty() ? Integer.parseInt(speedString) : 0;
dispose();
}
});
setLayout(new GridLayout(3, 1));
add(new Label("Please enter your car's speed"));
add(textField);
add(okButton);
pack();
}
int getSpeed()
{
return speed;
}
}