gpt4 book ai didi

java - java swing的 Action 监听器

转载 作者:行者123 更新时间:2023-12-01 11:37:00 25 4
gpt4 key购买 nike

我一直在尝试使用 swing 广告创建一个窗口,我必须将按钮放在右侧,这就是我使用 boxlayout 的原因,但我找不到在我拥有的按钮上使用 ActionListener 的方法。这就是我正在开发的程序:

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();
}
}

最佳答案

您不应将按钮直接添加到面板中,而应实例化它们,然后向它们添加 ActionListener 或您想要对它们执行的任何其他操作。示例:

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

然后您可以将按钮添加到数组中:

boxes[1].add(ajouterButton);

然后对所有按钮执行相同的操作。

关于java - java swing的 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com