java - 改进 JFrame 和 JPanel 之间的通信

标签 java swing user-interface jframe jpanel

我正在开发一款小游戏,需要在主 JFrame 和名为 gamepanJPanel 之间进行通信。

游戏要求用户通过单击包含字母的按钮来找到隐藏的单词。

我的JFrame 包含gamepanscorepanmenus 和其他内容...

我的gamepan包含我的buttonsArrayListener,隐藏的单词和其他东西......

问题是,当用户找到隐藏的单词时,我需要告诉我的 JFrame 他这样做了,这样稍后就可以重新绘制 gamepan,创建一个新单词。 ...

我所做的是:我在我的游戏盘中添加了一个 boolean 值,它告诉我的单词是否被找到,并在我的游戏盘中添加了一个MouseListener gamepan,所以每次我移动鼠标时,JFrame 都会测试是否找到该单词 然后在我的 gamepan 中添加 setter ,如果找到隐藏单词,我可以使用 JFrame 再次初始化事物。

我发现添加 MouseListener 并不是非常有效,因为我必须移动鼠标才能进行更改,并且每次鼠标移动都会进行无用的处理...

我想知道是否有比添加 MouseListener 更好的解决方案?我还想知道我是否在 gamepan 中添加了 setter 来为新单词设置其变量。

这是我的代码

游戏盘代码

public class GamePanel extends JPanel{
private JPanel leftPan = new JPanel();
private JPanel rightPan = new JPanel();
private String[] letters =     {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",};
private JButton Button[] = new JButton[26];

private JLabel label1;
private JLabel label2;
private JLabel label3;
private ActionListener buttonListener;
private JOptionPane jop = new JOptionPane();

private Word randWord = new Word(); // mot aléatoire
private TreatedWord tWord = new TreatedWord(randWord.getRandWord());// mot  aléatoire traité ( etoiles et tout ça )
private char clickedButton;// lettre tappée
private boolean motTrouvé = false; // pour informer la classe Fenetre si le mot a été retrouvé ou pas on utilise ce boolean avec son getter et setter ( a savoir que cette classe est informée si le mot est trouvé ou pas via l'objet tWord)


private final List<CustomListener> customListener = new LinkedList<>(); //On crée une liste de CustomListener pour en ajouter autant qu'on veut(Via addCustomListener)

public GamePanel(){
    this.setBackground(Color.white);
    initGamePan();
    initListeners();
    this.setLayout(new BorderLayout());
    this.add(leftPan,BorderLayout.WEST);
    this.add(rightPan,BorderLayout.EAST);
}

public void initGamePan(){
    rightPan.add(new JLabel(new ImageIcon("131869.jpg")));
    label1 = new JLabel("Nombre de mots trouvés : 0");
    label1.setHorizontalAlignment(JLabel.CENTER);
    label1.setFont(new Font("arial",Font.BOLD,20));
    label1.setPreferredSize(new Dimension(300,50));

    label2 = new JLabel("Score Actuel : 0 point");
    label2.setHorizontalAlignment(JLabel.CENTER);
    label2.setFont(new Font("arial",Font.BOLD,20));
    label2.setPreferredSize(new Dimension(300,50));

    label3 = new JLabel(tWord.getStars());
    label3.setHorizontalAlignment(JLabel.CENTER);
    label3.setFont(new Font("arial",Font.BOLD,30));
    label3.setForeground(Color.blue);
    label3.setPreferredSize(new Dimension(450,50));

    leftPan.add(label1);
    leftPan.add(label2);
    leftPan.add(label3);
    for(int i=0;i<letters.length;i++){
        Button[i]= new JButton(letters[i]);
        leftPan.add(Button[i]);
    }

    leftPan.setPreferredSize(new Dimension(460,650));
    leftPan.setBackground(Color.WHITE);
    rightPan.setPreferredSize(new Dimension(420,650));
    rightPan.setBackground(Color.WHITE);
}

public void initListeners(){
    buttonListener= new ActionListener(){

        public void actionPerformed(ActionEvent arg0) {
            clickedButton = ((JButton)(arg0.getSource())).getText().charAt(0); // on prend le bouton cliqué, on le convertis en string puis en char
            label3.setText(tWord.treatedWord(clickedButton));// on donne a la methode tretedWord de l'objet tWord le char clickedbutton pour faire le traitement sur le mot mystère
            ((JButton)(arg0.getSource())).setEnabled(false);

            if(tWord.isFound()==true){
                jop.showMessageDialog(null, "Bravo t'a trouvé le mot !", "U don't Say B|", JOptionPane.INFORMATION_MESSAGE);
                motTrouvé = true;

            }
        }

    };
    for(int i=0;i<letters.length;i++){
        Button[i].addActionListener(buttonListener);
    }

}


public void setNewWord(){
    this.randWord = new Word();
    this.tWord = new TreatedWord(randWord.getRandWord());
    this.label3.setText(tWord.getStars());
}
public void resetButtons(){
    for(JButton B : this.Button){
        B.setEnabled(true);
    }
}


 public void addCustomListener(final CustomListener listener) {
        this.customListener.add(listener);
    }

 public void notifyWordFound(/* any data you could use */) {
        for(final CustomListener listener : this.customListener) {
            listener.wordFound(/* any data you could use */);
        }
    }

}

MyJFrame代码:

公共(public)类 Fenetre 扩展 JFrame {

    private JMenuBar menu = new JMenuBar();
    private JMenu file = new JMenu("Fichier");
    private JMenuItem neew = new JMenuItem("Nouveau");
    private JMenuItem score = new JMenuItem("Score");
    private JMenuItem quit = new JMenuItem("Quitter");
    private JMenu about = new JMenu("About");
    private JMenuItem how = new JMenuItem("Règles");
    private JMenuItem who = new JMenuItem("Credit");
    private int i=1;
    private ScorePanel scorepan = new ScorePanel(900,650);
    private ReglesJeuPanel rgpan = new ReglesJeuPanel(900,650);
    private GamePanel gamepan = new GamePanel();
    private JPanel pan = new JPanel();
    private JPanel container = new JPanel();
    private JLabel label = new JLabel("------------------------SAMAIKOM------------------------");
    private JTextArea texte = new JTextArea(    "Vous avez sept coups pour trouver le mot caché. Si vous réussissez, on recommence !\n" +
            "Plus vous trouvez de mots, plus votre score augmente. Alors, à vous de jouer !\n" +
            "Proverbe :\t« Pas vu, pas pris !\n" +
                "\tPris ! PENDU ! »");
public Fenetre(){
    this.setTitle("Le Pendu ...");
    this.setSize(900, 650);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    initMenu();
    initAcceuilPan();
    initListeners();
    this.setContentPane(container);
}

private void initMenu(){
    file.add(neew);
    file.add(score);
    file.addSeparator();
    file.add(quit);
    file.setMnemonic('F');
    neew.setMnemonic('N');
    neew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,KeyEvent.CTRL_DOWN_MASK));
    score.setMnemonic('S');
    score.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,KeyEvent.CTRL_DOWN_MASK));
    quit.setMnemonic('Q');
    quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,KeyEvent.CTRL_DOWN_MASK));

    about.add(how);
    about.addSeparator();
    about.add(who);
    about.setMnemonic('A');
    how.setMnemonic('R');
    how.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,KeyEvent.CTRL_DOWN_MASK));
    who.setMnemonic('C');
    who.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,KeyEvent.CTRL_DOWN_MASK));

    menu.add(file);
    menu.add(about);
    this.setJMenuBar(menu);
}

private void initListeners(){
    score.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            container.removeAll();
            container.add(scorepan);
        }
    });
    quit.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });
    how.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            container.removeAll();
            container.add(rgpan);
        }
    });
    neew.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            gamepan.setNewWord();
            gamepan.resetButtons();
            container.removeAll();
            container.add(gamepan);
        }
    });

    gamepan.addCustomListener(new CustomListener(){

        public void wordFound() {
        }

    });

    gamepan.notifyWordFound();       // where to put this ?????


}

private void initAcceuilPan(){
    pan.setBackground(Color.white);
    pan.add(new JLabel(new ImageIcon("131868.jpg")));
    texte.setEditable(false);
    Font F1 = new Font("arial",Font.BOLD,20);
    Font F2 = new Font("arial",Font.BOLD,15);
    label.setFont(F1);
    texte.setFont(F2);
    container.setBackground(Color.white);
    container.add(label);
    container.add(pan);
    container.add(texte);
    //container.add(gamepan);

}


public static void main(String[] args) {
    Fenetre F1 = new Fenetre();
}

}

最佳答案

您可以使用一些在找到单词时发生的自定义事件:

public interface MyEventListener {
    public abstract void wordFound(/* any data you could use */);
}

然后让您的 GamePan 能够发出此类事件:

public class GamePan extends JPanel {
    private final List<MyEventListener> myEventListeners = new LinkedList<>();

    // Here, keep everything you already have

    public void addMyEventListener(final MyEventListener listener) {
        this.myEventListeners.add(listener);
    }

    private void notifyWordFound(/* any data you could use */) {
        for(final MyEventListener listener : this.myEventListeners) {
            listener.wordFound(/* any data you could use */)
        }
    }
}

找到单词后,只需调用 GamePan#notifyWordFound。 然后,注册一些更新方法,以便在发生此类事件时在 JFrame 中调用:

public class MyJFrame extends JFrame {
    // Here, keep everything you already have

    public JFrame() {
        // Here, keep everything you already have

        // Let's assume your ScorePanel instance is here:
        final ScorePanel scorePanel = new ScorePanel();

        this.gamePan.addMyEventListener(new MyEventListener() {
            @Override
            public void wordFound(/* any data you could use */) {
                // Update your application using any data you can use :)
                scorePanel.wordFound(/* any data you could use */);
            }
        });
    }
}

在这里,我们只需调用 ScorePanel#wordFound 方法,以便可以更新 ScorePanel

不要忘记,您可以通过所有这些方法传输您感兴趣的任何数据。例如,如果您想传输用户刚刚找到的单词,则可以将 MyEventListener#wordFound 方法声明如下:

public interface MyEventListener {
    public abstract void wordFound(final String word);
}

编辑:添加了与 ScorePanel 实例的一些交互,以回答评论中的其他问题:)

关于java - 改进 JFrame 和 JPanel 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21010495/

相关文章:

java - 使用 java 应用程序使用 pkcs#11 签署 pdf

java - 将 JLabel 添加到 JPanel

java - 在 showconfirmDialog 中使用工具提示

user-interface - 如何在 flutter 中夹住标签栏容器的边缘?

c# - 如何在 C# 中创建交互式(拖放内容)GUI

java - 从其他类 Android Java 调用静态方法

Java 文件 MD5 和 PHP md5_file 不同

java - 循环屏障等待方法不起作用

java - 插入符号位置设置为最后一行开头的文本区域 (JTextArea) 的自动文本滚动

java - 如何删除 Android 网格布局之间的空间