2012-04-22 61 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