温度转换java小程序_温度转换小程序--JavaFX
作為一名Java語言的初學(xué)者,最近在學(xué)習(xí)JavaFX,看到CSDN上用swing實(shí)現(xiàn)GUI簡單功能的小程序居多,于是想著用JavaFX來實(shí)現(xiàn)下,選了個極為簡單的溫度轉(zhuǎn)換程序,折騰了快一天吧,總算是寫完了,雖然簡單,但還是想記錄下~~~
實(shí)現(xiàn)結(jié)果如下圖:
代碼思路:
用GridPane布局,將需要用的TextField、Label、RadioButton、Button實(shí)現(xiàn),并設(shè)置好位置
為兩個Button設(shè)置SetonAction方法
代碼如下:
package GUIs;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class TemperatureChange extends Application{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage mystage) throws Exception{
GridPane root = new GridPane();
//用CSS格式設(shè)置背景漸變色
root.setStyle("-fx-background-color:linear-gradient(to right,#00fffc,#fff600)");
Button btn1 = new Button("溫度轉(zhuǎn)換");
Button btn2 = new Button("退出");
Label lab1 = new Label("攝氏溫度 =");
Label lab2 = new Label("華氏溫度");
TextField txt1 = new TextField();
txt1.setPrefWidth(70);//設(shè)置寬度
TextField txt2 = new TextField();
txt2.setPrefWidth(50);
RadioButton rb1 = new RadioButton("攝氏轉(zhuǎn)華氏");
RadioButton rb2 = new RadioButton("華氏轉(zhuǎn)攝氏");
ToggleGroup tg = new ToggleGroup();
rb1.setToggleGroup(tg);
rb2.setToggleGroup(tg);
//將控件全部添加到布局中
root.add(txt1, 0, 0);
root.add(lab1, 1, 0);
root.add(txt2, 2, 0);
root.add(lab2, 3, 0);
root.add(rb1, 1, 1);
root.add(rb2, 2, 1);
root.add(btn1, 1, 2);
root.add(btn2, 2, 2);
root.setHgap(20);//水平間距
root.setVgap(35);//垂直間距
root.setAlignment(Pos.CENTER);//設(shè)置控件位于布局中央
btn1.setOnAction(new EventHandler(){
@Override
public void handle(ActionEvent event){
double tem1;
double tem2;
double c ;//攝氏度
double f;//華氏度
if(rb1.isSelected()){//單選按鈕1被選中時(shí)
tem1 = Double.valueOf(txt1.getText()) ;
f=1.8*tem1+32;
txt2.setText(String.valueOf(f).substring(0, 7));
}
if(rb2.isSelected()){//單選按鈕2被選中時(shí)
tem2 = Double.valueOf(txt2.getText()) ;
c=5*(tem2-32)/9;
txt1.setText(String.valueOf(c).substring(0, 7));
}
}
});
btn2.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
System.exit(0);
}
});
Scene scene = new Scene(root, 400, 250);
mystage.setTitle("TemperatureChange");//設(shè)置標(biāo)題
mystage.getIcons().add(new Image("Java.png"));//添加圖標(biāo)
mystage.setScene(scene);
mystage.show();
}
}
標(biāo)簽:轉(zhuǎn)換,--,javafx,JavaFX,scene,add,new,import,root
來源: https://blog.csdn.net/m0_50115641/article/details/111144826
總結(jié)
以上是生活随笔為你收集整理的温度转换java小程序_温度转换小程序--JavaFX的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: S3C6410裸机AC97驱动
- 下一篇: 平面设计界的九阳真经