操纵不同Jpanel中的按钮

时间:2013-01-22 22:08:09

标签: java swing oop jpanel jbutton

我有各种各样的按钮面板。某些按钮应该调用一个方法来启动搜索数组列表,其他按钮应该调用将信息发送到不同JTextArea框的方法。 为每个按钮添加事件侦听器后,如何根据在actionPerformed方法中单击的按钮创建特定操作?下面是我的各种gui属性的代码,你可以看到有3种不同的JPanel,每个按钮需要执行不同的功能。我只需要知道如何确定单击了哪个按钮,以便将其链接到适当的方法(已经在另一个类中编写)。这需要if语句吗?如果我将其公开,我的其他类可以访问GUI上的按钮,还是有更有效的方法来执行此操作。

JPanel foodOptions;
JButton[] button= new JButton[4]; //buttons to send selected object to info panel
static JComboBox[] box= new JComboBox[4];

JPanel search;
JLabel searchL ;
JTextField foodSearch;
JButton startSearch; //button to initialize search for typed food name
JTextArea searchInfo;

JPanel foodProfile;
JLabel foodLabel;
JTextArea foodInfo;
JButton addFood; //but to add food to consumed calories list

JPanel currentStatus;
JLabel foodsEaten;
JComboBox foodsToday;
JLabel calories;
JTextArea totalKCal;
JButton clearInfo; //button to clear food history

3 个答案:

答案 0 :(得分:1)

根据人们的评论,你需要使用某种类型的听众,这里有一个真正的基本例子来帮助你入门,但是我会在大多数情况下在其他地方定义你的听众,而不是动态:

JButton startSearch = new JButton("startSearch");
        JButton addFood = new JButton("addFood");

        startSearch.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                //DO SEARCH RELATED THINGS

            }
        });

        addFood.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //DO FOOD ADD RELATED THINGS

            }
        });

答案 1 :(得分:1)

这样的事情:

JButton searchButton = new JButton("Start search");

searchButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
      // do some search here
   }
});

JButton addFoodButton= new JButton("Add food");

addFoodButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
      // add your food
   }
});

等等。如果您需要通过多个按钮重用行为,请创建ActionListener实例而不是使用匿名类,并将其多次分配给按钮。

答案 2 :(得分:1)

我想有很多方法可以做到这一点。我想你可以做到以下几点:

public class Myclass implements ActionListener
{
  private JButton b1,b2;
  private MyClassWithMethods m = new MyClassWithMethods(); 

  // now for example b1
  b1 = new JButton("some action");
  b1.setActionCommand("action1");
  b1.addActionListener(this);

  public void actionPerformed(ActionEvent e) {
     if ("action1".equals(e.getActionCommand())) 
    {
        m.callMethod1();
    } else {
       // handle other actions here
    }
   }
 }

您可以对更多按钮执行相同的操作,并测试哪个操作触发了事件,然后从您的类中调用相应的方法。