1

I tried to use the OS look and feel in my application but I get a problem in the display of the Buttons.

Basically I put the code In my JFrame from which I access to the GamePanel which I have the problem with.

Here is what the GamePanel looks like :

Image

These are not the windows buttons !

JFrame code :

public class Fenetre extends 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 JPanel cardcontainer = new JPanel();
        private CardLayout c1 = new CardLayout();
        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);
        initMenu();
        initAcceuilPan();
        initListeners();
        setLookAndFeel();
        this.setContentPane(cardcontainer);
    }
    private void setLookAndFeel(){
        try {
              //On force à utiliser le « look and feel » du système
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              //Ici on force tous les composants de notre fenêtre (this) à se redessiner avec le « look and feel » du système
              SwingUtilities.updateComponentTreeUI(this);
            }
            catch (InstantiationException e) {}
            catch (ClassNotFoundException e) {}
            catch (UnsupportedLookAndFeelException e) {}
            catch (IllegalAccessException e) {}
    }
    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) {
                c1.show(cardcontainer, "scorepan");
            }
        });
        quit.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        how.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                c1.show(cardcontainer, "rgpan");
            }
        });
        who.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {

                 JOptionPane.showMessageDialog(Fenetre.this, "\n\nChti had laplikatio hadi sawbha wa7d bnadem chdiiiid B|\n\nCopyright Haytham Benayed\n\nPeace and Love", "man ana ?", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        neew.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                gamepan.setNewWord();
                gamepan.resetButtons();
                c1.show(cardcontainer, "gamepan");
            }
        });

        gamepan.addCustomListener(new CustomListener(){

            public void wordFound() {
                    neew.doClick();
            }

            public void wordNotFound() {
                if(!ScorePanel.isScoreSuffisant())
                {
                    scorepan.resetScoreTotal();
                    c1.show(cardcontainer, "acceuilpan");
                }
                if(ScorePanel.isScoreSuffisant()){
                    scorepan.resetScoreTotal();
                    scorepan.initLeftPan();
                    c1.show(cardcontainer, "scorepan");
                }
            }

        });


    }

    private void initAcceuilPan(){
        pan.removeAll(); // si on ne met pas cette methode, apres la réinisialisation du container si le mot n'a pas été trouvé on trouve 2 images!
        pan.setBackground(Color.white);
        pan.add(new JLabel(new ImageIcon("src/data/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);
        cardcontainer.setLayout(c1);
        cardcontainer.add(container,"acceuilpan");
        cardcontainer.add(scorepan,"scorepan");
        cardcontainer.add(rgpan,"rgpan");
        cardcontainer.add(gamepan,"gamepan");

    }



}

GamePanel Code:

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 String mistakeslabel; // pour savoir si un traitement a été fais ou non sur le tWord ( pour les mistakes )
    private ActionListener buttonListener;

    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 int mistakes = 0;
    private int coups = 0;

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

        mistakeslabel=label3.getText();

        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(mistakeslabel.equals(label3.getText())){
                    mistakes++;
                    rightPan.removeAll();
                    switch(mistakes){
                    case 1 : rightPan.add(new JLabel(new ImageIcon("src/data/131870.jpg")));rightPan.revalidate();
                    break;
                    case 2 : rightPan.add(new JLabel(new ImageIcon("src/data/131871.jpg")));rightPan.revalidate();
                    break;
                    case 3 : rightPan.add(new JLabel(new ImageIcon("src/data/131872.jpg")));rightPan.revalidate();
                    break;
                    case 4 : rightPan.add(new JLabel(new ImageIcon("src/data/131873.jpg")));rightPan.revalidate();
                    break;
                    case 5 : rightPan.add(new JLabel(new ImageIcon("src/data/131874.jpg")));rightPan.revalidate();
                    break;
                    case 6 : rightPan.add(new JLabel(new ImageIcon("src/data/131875.jpg")));rightPan.revalidate();
                    break;
                    case 7 : rightPan.add(new JLabel(new ImageIcon("src/data/131876.jpg")));rightPan.revalidate();
                    break;
                    }
                }
                mistakeslabel=label3.getText();
                coups++;
                System.out.println(randWord.getRandWord());

                if(tWord.isFound()){
                    String S;
                    ScorePanel.motsTrouvé();
                    S=ScorePanel.updateScore(coups,mistakes);
                    JOptionPane.showMessageDialog(null, "Bravo t'a trouvé le mot "+randWord.getRandWord()+" !\n en "+coups+" coups et "+mistakes+" erreur"+(mistakes>1 ? "s" : "")+S, "U don't Say B|", JOptionPane.INFORMATION_MESSAGE);
                    label2.setText("Score Actuel : "+ScorePanel.getScoreTotal()+" Point"+(ScorePanel.getScoreTotal()>0 ?"s" : ""));
                    label1.setText("Nombre de mots trouvés : "+ScorePanel.getMotsTrouvés());
                    GamePanel.this.notifyWordFound(); // explications à la fin
                }
                if(mistakes==7){
                    if(!ScorePanel.isScoreSuffisant())
                    {
                        JOptionPane.showMessageDialog(null, "Score Insuffisant pour l'enregistrer ...", "hahahah wa l3iaaaan !", JOptionPane.INFORMATION_MESSAGE);
                    }
                    if(ScorePanel.isScoreSuffisant())
                    {
                        String Sc;
                        Sc=JOptionPane.showInputDialog(null,"Entrez un pseudo","Mabikch",JOptionPane.INFORMATION_MESSAGE);
                        ScorePanel.updateScoreLeftPan(Sc);
                    }
                    GamePanel.this.notifyWordNotFound();
                    mistakes=0;
                }
            }

        };
        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());
        this.mistakeslabel=label3.getText();
        this.mistakes=0;
        this.rightPan.removeAll();
        this.rightPan.add(new JLabel(new ImageIcon("src/data/131869.jpg")));
    }
    public void resetButtons(){
        for(JButton B : this.Button){
            B.setEnabled(true);
        }
    }


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

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

}
FrankelStein
  • 907
  • 2
  • 13
  • 30
  • Did you tried as explained in the docs? [Mighty Docs](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html) . Please show your code. – Eich Jan 14 '14 at 23:50
  • I edited my post to add the JFrame and the GamePanel code – FrankelStein Jan 14 '14 at 23:55
  • Set the look and feel in your main method. Where is your main method? – Eich Jan 15 '14 at 00:10
  • What problem? Can you paste a picture? Without more information the best advice I can give is to try to set a big enough [preferredSize](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setPreferredSize(java.awt.Dimension)) for the `JButtons` and set satisfactory gap for the [FlowLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html) that is used by default by your components. Else, choose a more appropriate [Layout Manager](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). – Anthony Accioly Jan 15 '14 at 00:21
  • it's a class apart, if I set it there then how do I proceed with the method `SwingUtilities.updateComponentTreeUI(this)` since Main is static and doesn't recognise the argument `this` ? – FrankelStein Jan 15 '14 at 00:22
  • 1
    FrankelStein, use this code http://stackoverflow.com/a/15084581/664577. But you only need it if you are changing the look and feel dynamically (after you have loaded swing components), else, just set the OS look and feel before creating any swing components (at your main method) and skip the calls to `updateComponenetTreeUI`; `setLookAndFeel` is good engough. – Anthony Accioly Jan 15 '14 at 00:26
  • 1
    Yeah, Anthony is right. You don't need to set ```updateComponentTreeUI``` when you set your L&F before initialization of your application :) – Eich Jan 15 '14 at 00:42
  • I changed size and gaps, I got nothing I deleted that Line, works Perfectly ! thanx Guys :) – FrankelStein Jan 15 '14 at 02:06

1 Answers1

0

you need to put theUIManager.setLookAndFeel before you add the buttons. I would put it in the main method as well as well as the buttons and setVisible. I do not normally make a method to set the LaF.