2017-02-17 63 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. 使用鍵盤映射,所以用戶也可以只輸入號碼