2017-02-17 41 views
-2

您好我想提出,其中用户从选择的28挑选4个数字乐透GUI我目前做的方式是通过如下爪哇GUI添加按钮与一个for循环

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循环 将操作添加到每个按钮,因为这看起来更合乎逻辑?
  • 还有一种方法可以将每个数字添加到数组中吗?

回答

0

上的每个按钮可以设置一个动作命令:

button.setActionCommand("1"); 

,你可以得到,使用你的动作事件后的值:

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 
    } 
+0

我可以用这个产生多少个按钮?他需要生成28个按钮,每个人都应该有一个事件,所以你的答案只有一个按钮:) –

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(); 
+0

谢谢你会看看两个答复。我如何将它添加到数组? – Bryan

+0

(1-)这是一个JavaFX答案,而不是Swing答案。 – camickr

1

创建可以由所有的按钮被共享的单个动作。然后Action将获得按钮的文本,然后进行一些处理。

结账setText method with panel and button。这个例子将告诉你如何:

  1. 创建一个单一的ActionListener由每个按钮
  2. 共享“追加”文本到文本字段,而不是替换文本
  3. 使用键盘映射,所以用户也可以只输入号码