2015-04-25 89 views
0

我一直在嘗試創建一個窗口使用擺動廣告我必須把按鈕放在右側這就是爲什麼我用boxlayout,但我找不到在我有按鈕上使用ActionListener的方法。這就是我的工作程序:ActionListener java swing

public class Fenetre2 extends JFrame { 

private JSplitPane splitPan=null; 

    public Fenetre2(){ 
     JPanel pan = new JPanel(); 

     // CARACTERISTIQUE FENETRE 
     this.setTitle("Gestion Employe"); 
     this.setSize(800, 400); 
     this.setLocationRelativeTo(null); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     pan.setBackground(Color.white); 
     this.setContentPane(pan); 
     // ADD BUTTON 
     Container c = getContentPane(); 
     c.setLayout(new BorderLayout(30, 30)); 
     Box boxes[] = new Box[ 4 ]; 
     boxes[ 0 ] = Box.createHorizontalBox(); 
     boxes[ 1 ] = Box.createVerticalBox(); 
     boxes[ 2 ] = Box.createHorizontalBox(); 
     boxes[ 3 ] = Box.createVerticalBox(); 
     // create strut and add buttons to boxes[ 1 ] 
     boxes[ 1 ].add(new JButton("ajouter")); 
     boxes[ 1 ].add(new JButton("suprimer")); 
     boxes[ 1 ].add(new JButton("afficher")); 
     c.add(boxes[ 1 ], BorderLayout.EAST); 
     //TREE 
     DefaultMutableTreeNode root = new DefaultMutableTreeNode("STRUCTURE EMPLOYE"); 
     //create the child nodes 
     DefaultMutableTreeNode PDGNode = new DefaultMutableTreeNode("PDG"); 
     DefaultMutableTreeNode departement1Node = new DefaultMutableTreeNode("departement 1"); 
     departement1Node.add(new DefaultMutableTreeNode("CHEF DEPARTEMENT")); 
     departement1Node.add(new DefaultMutableTreeNode("EMPLOYEE1")); 
     departement1Node.add(new DefaultMutableTreeNode("EMPLOYEE2")); 
     departement1Node.add(new DefaultMutableTreeNode("EMPLOYEE3")); 


     //add the child nodes to the root node 
     root.add(PDGNode); 
     PDGNode.add(departement1Node); 
     JTree tree = new JTree(root); 
     this.add(tree); 
     JScrollPane scroll=new JScrollPane(tree); 
     splitPan=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll,new JLabel("aaaaa")); 
     splitPan.setSize(this.getMaximumSize()); 
     add(splitPan); 

     this.setVisible(true);   
    } 
    public static void main (String args []){ 

     Fenetre2 fen = new Fenetre2(); 
    } 
} 
+0

我建議你閱讀這個關於如何使用按鈕的http://docs.oracle.com/javase/tutorial/uiswing/components/button.html。 – Sybren

+0

如果你使用java 8,你可以使用lambdas:'button.addActionListener(action - > {/ * your code * /});'' –

回答

1

不要添加按鈕直接進入面板,而是他們實例化,然後添加一個ActionListener他們或任何其他你想與他們做。例如:

JButton ajouterButton = new JButton("ajouter"); 
ajouterButton.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent event) { 
     // code goes here 
    } 
}); 

然後你就可以將按鈕添加到您的數組:

boxes[1].add(ajouterButton); 

然後做同樣的事情,所有按鈕。

0

您正在查找的按鈕實例存儲在方框[1]中,因此您可以簡單地執行boxes[1].addActionListener(...);