如何设置在 JavaFX 中动态生成的 Button 的属性

问题描述 投票:0回答:1

我正在创建一个基于数据库数据动态生成

Button
的应用程序。现在我有两个问题。

  1. 动态创建的
    Button
    是超级通用的,它们看起来与其余的格格不入 我的应用程序,那么我如何设置文本字体、背景颜色、大小和填充 动态创建的按钮?
  2. 如何在所有新创建的按钮上设置
    ActionEvent

以下是我的程序正在执行的操作的上下文:我的数据库中有一个表(名为 TABLEDETAILS),其中有一列名为“NoTable”,用于保存餐厅中的餐桌总数。现在,当按下Table Model按钮时,它会生成一个按钮(代表一个表格)。

public class TableViewController {

    PreparedStatement pst = null;
    ResultSet rs = null;
    Connection Conn = MySqlConnet.ConnectDB();

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private HBox TableLayout = new HBox(10);

    @FXML
    void flowLayout1(ActionEvent event) {

    }

    @FXML
    void flowLayout2(ActionEvent event) {

    }

    @FXML
    void flowLayout3(ActionEvent event) {

    }

    @FXML
    void tableModel(ActionEvent event) throws SQLException {

        //TODO
        Conn = MySqlConnet.ConnectDB();
        String Sql = "SELECT * FROM tabledetails ";

        //our Collection to hold newly created Buttons
        List<Button> buttonlist = new ArrayList<>();

        try {
            pst = Conn.prepareStatement(Sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                int ListOfTable = rs.getInt("NoTable");
                for(int i = 0; i <= ListOfTable; i++) {
                    buttonlist.add(new Button("Table No. " + (int)(i + 1)));
                }
            }

            // remove all Buttons that are currently in the container
            TableLayout.getChildren().clear();
            //then add all Buttons that you just created
            TableLayout.getChildren().addAll(buttonlist);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            rs.close();
            pst.close();
        }
    }

    @FXML
    void initialize() {

    }
}

屏幕截图:

java javafx
1个回答
0
投票

For 循环多个按钮和字符串:如果单击另一个按钮,如何更改按钮文本和背景并恢复到默认设置?

    Button[] btns;
int btnClicked = 0;

private void buttonsClickStatus() {
  btns = new Button[]{btn1, btn2, btn3, ......., btn100};
  for(int i = 0; i < buttons.length; ++i) {
    //default buttons
    btns[i].setText("Not clicked");
    btns[i].setTextColor(Color.WHITE);
    btns[i].setBackgroundResource(R.drawable.purple);
    int j = i; 
    btns[i].setOnClickListener(v -> {
      btnClicked = j;
      for(int k = 0; k < buttons.length; ++k) {
        if(btnClicked == k) {
          //After specific button clicked
          btns[k].setText("Clicked "+k);
          btns[k].setTextColor(Color.GREEN);
          btns[k].setBackgroundResource(R.drawable.yellow);
        } else {
          //Remaining buttons set to default
          btns[k].setText("Not clicked");
          btns[i].setTextColor(Color.WHITE);
          btns[i].setBackgroundResource(R.drawable.purple);
        }
      }
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.