هنا فى هذا ال code مصفوفة من نوع JButton و كل عنصر منها له حدث بسيط .
بدلاً من اللجوء لكتابة
if(e.getSource==buttons[0]){
// Type your code
}else if(e.getSource==buttons[1]){
// Type your code
}else if(e.getSource==buttons[2]){
// Type your code
}العناصر buttons [0] , buttons[1] , ..... الخ
تكون غير مفهومة لدى قارى ال code
لذا من خلال ال Enum تستطيع كل عنصر يكون له اسم واضح و ثابت و بالتالى يكون سهل الفهم . و خصوصاً إذا كان هناك العديد من الbuttons
انظر معنا :
--------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
enum Action {
START, HELP, EXIT;
}
class MainGame extends JFrame {
private JPanel mainPanel, buttonsPanel;
private Box mainButtonsBox;
private JButton[] buttons;
private Action[] buttonsNames;
private Action action;
public MainGame() {
createContainer();
buttonsNames = Action.values();
for (int i = 0; i < buttonsNames.length; ++i) {
action = buttonsNames;
createButtons(action);
}
getContentPane().add(mainPanel);
}
public static void main(String[] args) {
MainGame mainGame = new MainGame();
mainGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainGame.setSize(new Dimension(600, 300));
mainGame.setLocationRelativeTo(null);
mainGame.setExtendedState(MAXIMIZED_BOTH);
mainGame.setVisible(true);
}
private void createContainer() { // for createing container
/////////////////////MainPanel/////////////////////////////
mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(30, 30, 30, 30);
//////////////////////Box&Panel fro buttons/////////////////////////////////////
mainButtonsBox = Box.createHorizontalBox();
buttonsPanel = new JPanel(new GridLayout(3, 1));
mainButtonsBox.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
mainButtonsBox.setPreferredSize(new Dimension(400, 200));
mainButtonsBox.add(buttonsPanel);
///////////////////////////////////////////////////////////////////////////////
mainPanel.add(mainButtonsBox, c);
}
private void createButtons(Action action) {
buttons = new JButton[buttonsNames.length];
for (int i = 0; i < 1; ++i) {
buttons = new JButton(action.name());
buttons.addActionListener(listenerFor(action));
buttonsPanel.add(buttons);
}
}
private ActionListener listenerFor(Action action) {
switch (action) {
case START: // START BUTTON
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "START");
}
};
case HELP: // HELP BUTTON
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "HELP");
}
};
case EXIT: // EXIT BUTTON
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "EXIT");
}
};
}
return null;
}
}تعرضت لمشاكل حتى يخرج بهذا الشكل .
أتمنى من لديه طرق أخرى يعرضها حتى تعم الفائدة .
شكراً
