簡體   English   中英

單選按鈕更改 Java 中的背景顏色

[英]RadioButton to change background color in Java

伙計們,我只是想創建 3 個單選按鈕來改變我在 JavaFX 中的背景顏色。 我被卡住了,我在 updateBackGround() 方法中遇到了這個錯誤“找不到符號”,特別是“pane1.setBackground(new ....”)

Java 找不到“pane1”符號。 請幫我。 太感謝了。 下面是我的代碼。

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;

public class Project2 extends Application
{
   public RadioButton RedButton;
   public RadioButton BlueButton;
   public RadioButton GreenButton;

   public static void main(String[] args) {
      launch(args);
   }

   public void start(Stage primaryStage)
   {
      Pane myPane1 = pane1();   
      Scene scene1 = new Scene(myPane1);    
      primaryStage.setScene(scene1);    
      primaryStage.setTitle("HAI VO");
      primaryStage.show();
   }

   public Pane pane1()
   {
     ToggleGroup group1 = new ToggleGroup();

     RedButton = new RadioButton("RED");
     RedButton.setToggleGroup(group1);
     RedButton.setOnAction(event -> updateBackGround());

     BlueButton = new RadioButton("BLUE");
     BlueButton.setToggleGroup(group1);
     BlueButton.setOnAction(event -> updateBackGround());

     BlueButton.setSelected(true);

     GreenButton = new RadioButton("Green");
     GreenButton.setToggleGroup(group1);
     GreenButton.setOnAction(event -> updateBackGround());

     GridPane pane1 = new GridPane();

     pane1.add(RedButton,5,0);
     pane1.add(GreenButton,10,0);
     pane1.add(BlueButton,20,0);

     pane1.setHgap(5);
     pane1.setVgap(5);

     pane1.setPadding(new Insets(20,20,20,20));

     updateBackGround();
     return pane1;
   } 

   public void updateBackGround()
   {
      if (RedButton.isSelected()) {
          pane1.setBackground(new Background(new BackgroundFil(Color.RED,CornerRadii.EMPTY, Insets.EMPTY)));
      }

      if (BlueButton.isSelected()) {
          pane1.setBackground(new Background(new BackgroundFill(Color.BLUE,CornerRadii.EMPTY, Insets.EMPTY)));
      }

      if (GreenButton.isSelected()) {
          pane1.setBackground(new Background(new BackgroundFill(Color.GREEN,CornerRadii.EMPTY, Insets.EMPTY)));        
      }

   }
}
`

您有一個方法pane1() ,它返回一個Pane ,並且在該方法中您有一個局部變量pane1 ,它是一個GridPane

稍后,在updateBackground()中,您引用了沒有括號的pane1 ,它看起來像對 class 成員或局部變量的引用——但在 updateBackground 中既沒有 class 成員,也沒有名為 pane1 的變量。

updateBackground 沒有看到在pane1()方法中聲明的pane1變量。 它也看不到在start()中創建的myPane1窗格,只能通過從scene1 (scene1)中設置的 scene1 中檢索它來訪問它

這主要是 Java 的作用域規則的問題,並不特定於 JavaFX。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM