2012-04-22 94 views
1

我有,我想提出Jbuttons中的標題列表。我想,當我點擊一個特定的按鈕,我得到的文字。我在網上搜索,並嘗試了一些東西,但他們給予列表中的隨機標題,而不是我點擊的那個。請讓我知道我犯了什麼錯誤。任何形式的幫助將不勝感激。謝謝,如何獲得特定的Jbutton點擊?

  for(String title:listOfTitles){ 
      button1.setText(title); 
      button1.setBounds(20,50,100,25); 
      button1.setBorderPainted(true); 
      button1.setFocusPainted(true); 
      button1.setContentAreaFilled(false); 
      button1.setOpaque(false); 
      button1.setBackground(Color.lightGray); 
      button1.setBounds(5,i,100,100); 
      button1.addMouseListener(new java.awt.event.MouseAdapter() { 
       public void mouseClicked(java.awt.event.MouseEvent evt) { 
       jTextField3.setText(((button1) evt.getSource()).getText()); 
      } 

     }); 
     jPanel3.add(button1); 
     jPanel3.revalidate(); 
     jPanel3.repaint(); 
     i = i+15; 
    } 
+1

*「我有標題的列表。」 *相應的組件可能會是一個['JList'](http://docs.oracle.com/javase/7/docs/api/javax/swing/ JList.html)。 – 2012-04-22 17:26:22

回答

4

一般情況下,你不想一的MouseListener添加到Jbutton將。如果您已經閱讀了按鈕教程,那麼您肯定已經看到您應該使用ActionListeners。如果你這樣做,叫getActionCommand()傳遞到聽者的actionPerformed(...)方法ActionEvent對象上,你會得到你想要的字符串。

myButton.addActionListener(new ActionListener() { 
    actionPerformed(ActionEvent evt) { 
     System.out.println("Button's actionCommand: " + evt.getActionCommand()); 
    } 
}); 

法律聲明:此代碼沒有被編譯,也不測試並不意味着要複製和粘貼的解決方案,而是給你的ActionListeners是如何工作的想法,所以你可以使這個概念適應你的程序。

另外,請爲你需要知道的所有細節,其餘檢查出Swing JButton tutorial

+0

我是新來的Java,並高度讚賞,如果你給我一些code.thanks – user1276381 2012-04-22 17:17:15

+0

@ user1276381:見編輯和鏈接。 – 2012-04-22 17:18:28

+0

我嘗試這樣做,unsupprted異常出現,併產生隨機標題:button1.setActionCommand(button1.getText()); button1.addActionListener(新的ActionListener(){ @覆蓋 公共無效的actionPerformed(ActionEvent的五){ 字符串AC = e.getActionCommand(); 的System.out.println( 「按鈕的actioncommand:」 + AC); 拋出新的UnsupportedOperationException(「還不支持」。); } }); – user1276381 2012-04-22 17:58:14