1

したがって、testPanel と testFrame の 2 つのクラスがあります。すべてのボタンは testPanel クラスにあります。testFrame クラスの Jbuttons に ActionListeners を追加したいと考えています。どうすればこれを行うことができますか?

テストパネル:

public class testPanel extends JPanel{

JLabel codeLbl = new JLabel("Code");
JLabel titleLbl = new JLabel("Title");
JLabel priceLbl = new JLabel("Price");

JTextField codeTxt = new JTextField(20);
JTextField titleTxt = new JTextField(20);
JTextField priceTxt = new JTextField(20);

JButton addBtn = new JButton("Add");
JButton updateBtn = new JButton("Update");
JButton delBtn = new JButton("Delete");
JButton exitBtn = new JButton("Exit");
JButton firstBtn = new JButton("First");
JButton prevBtn = new JButton("Previous");
JButton nextBtn = new JButton("Next");
JButton lastBtn = new JButton("Last");

JPanel info = new JPanel();
JPanel buttons = new JPanel();

public testPanel(){
    info.setLayout(new GridLayout(3,2));

    info.add(codeLbl);
    info.add(codeTxt);
    info.add(titleLbl);
    info.add(titleTxt);
    info.add(priceLbl);
    info.add(priceTxt);

    buttons.setLayout(new GridLayout(2,4));

    buttons.add(addBtn);
    buttons.add(updateBtn);
    buttons.add(delBtn);
    buttons.add(exitBtn);
    buttons.add(firstBtn);
    buttons.add(prevBtn);
    buttons.add(nextBtn);
    buttons.add(lastBtn);

    JPanel container = new JPanel();
    container.setLayout(new BorderLayout());

    container.add(BorderLayout.CENTER, info);
    container.add(BorderLayout.SOUTH, buttons);

    add(container);
}
}

テストフレーム:

 public class testFrame extends JFrame{
JPanel p = new testPanel();

public testFrame(){
    super("BLAH");        

    this.getContentPane().add(p);setVisible(true);
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args){
    new testFrame();
}

}

4

3 に答える 3

1

まず第一に、パネルのボタンへのパブリックアクセスを単に提供することに反対します。これは、管理と責任範囲に関する問題が多すぎることにつながります... IMHO

への何らかの参照が必要です。testPaneこれにより、 をアタッチする機能が提供されますActionListener。次に、それtestPaneがどのように行われるかを管理する必要があります。

于 2013-09-30T21:25:15.243 に答える
0



1. まず、JPanel を拡張するクラスを作成します。

2. そのクラスで、次のように setActionListener メソッドを定義します。

public void setButtonsActionListener(ActionListener listener){
   // and in here set your buttons action listeners

   button1.addActionListener(listener);
   button2.addActionListener(listener);
   ...

}

3. JFrame クラスで、パネルの setButtonsActionListener メソッドを ActionLister インターフェイスの匿名実装で呼び出します。

    thePanel.setButtonsActionListener(new ActionListener(){
        @Override
        void actionPerformed(ActionEvent e){
            // here do what you gotta do when the button is clicked
        }

    });
于 2013-09-30T21:31:24.510 に答える
-1

これを試すことができます (これには、testPanel クラスのインスタンスと、button1 を public に設定する必要があります。

testFrame.button1.setActionListener(new ActionListener(@Override public void actionPerformed(ActionEvent event){}});

または、アクション リスナーを設定する関数を testPanel 内に作成することもできます。

于 2013-09-30T21:35:39.073 に答える