Java GUI使用for循环添加按钮

时间:2017-02-17 13:52:10

标签: java swing user-interface

嗨我正在制作一个乐透gui,用户从28的选择中选择4个数字。我目前的方式如下

private void no1InputButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
    numberSelectionList.add("1");
}                                              

private void no2InputButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
     chosenNumDisplayLabel.setText(chosenNumDisplayLabel.getText()+" 2");
}                                              

private void no3InputButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
     chosenNumDisplayLabel.setText(chosenNumDisplayLabel.getText()+" 3");
}        
通过28个数字等等。

  • 有没有办法通过for循环将操作添加到每个按钮 因为这似乎更符合逻辑?
  • 还有办法将每个数字添加到数组中吗?

3 个答案:

答案 0 :(得分:1)

创建一个可由所有按钮共享的Action。然后,Action将简单地获取按钮的文本,然后进行一些处理。

结帐setText method with panel and button。此示例将向您展示如何:

  1. 创建一个由每个按钮共享的ActionListener
  2. "附加"文本到文本字段而不是替换文本
  3. 使用键绑定,这样用户也可以输入数字

答案 1 :(得分:0)

在每个按钮上,您可以设置一个动作命令:

 button.setActionCommand("1");

然后您可以使用ActionEvent获取该值:

 evt.getActionEvent();

更完整:

  ActionListener listener = new ActionListener()
  {
     @Override
     public void actionPerformed(ActionEvent e)
     {
        System.out.println(e.getActionCommand()+" clicked");
     }
  };

  int howMuchYouWant = 32;
  for(int i = 0; i<howMuchYouWant; i++)
  {
     JButton button = new JButton(""+(i+1));
     button.setActionCommand(""+i);
     button.addActionListener(listener);
     //add to whatever gui you want here
  }

答案 2 :(得分:0)

您可以在JavaFX中执行类似的操作:

    content = new VBox(5);
    ScrollPane scroller = new ScrollPane(content);
    scroller.setFitToWidth(true);


while (condition==true)
{
  AnchorPane anchorPane = new AnchorPane();
  anchorPane.setPrefHeight(183.0);
  anchorPane.setPrefWidth(600.0);
 Label label1 = new Label ("something with meaning");
 Label labe2 = new Label ("something with more meaning");            
 Button button = new Button("button with meaning");
 anchorPane.getChildren().addAll(label1,label2,button);
 content.getChildren().add(anchorPane);

}

最后:

Scene scene = new Scene(new BorderPane(scroller, null, null, addButton, null), 400, 400);
    primaryStage.setScene(scene);
    primaryStage.show();