Java - JFrame no responde

 
Vista:
sin imagen de perfil

JFrame no responde

Publicado por David (11 intervenciones) el 04/09/2014 14:53:37
Hola a todos! Estoy implementando un juego en Java SE. La clase Tauler (tablero en español) hereda de JPanel y la añado (add) al JFrame que creo en el método main (este main es sólo para pruebas, para ver si el tablero se ve bien en la pantalla). Me consta que la clase Tauler está bien implementada (porque en otra versión del programa se veía todo bien), pero el JFrame no se vé tal como debería. ¿Alguna observación?

La clase Tauler crea un tablero en pantalla con las fichas dibujadas sobre él.

Éste es el código para la clase Tauler (lo siento por quien no entienda los identificadores y comentarios, están en catalán)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package meandres5
 
public class Tauler extends JPanel {
 
    public static final int COSTAT_TAULER = 490;  // 490 és divisible entre 5 i entre 7,
                                                  // i els quocients són parells.
    public static final int QUADRES_COSTAT_5 = 5;  // 5 peces per costat
    public static final int QUADRES_COSTAT_7 = 7;  // 7 peces per costat
 
    private Peca[][] tauler;
    private Peca casellaBuidaCentre;
 
    private Meandres5 meandres;
 
    private int costatTauler;
    private int quadresPerCostat;
    private int costatPeca;
 
    public Tauler (int quadresPerCostat, Meandres5 meandres) throws Exception {
        costatTauler = COSTAT_TAULER;
        this.quadresPerCostat = quadresPerCostat;
        this.costatPeca = costatTauler / quadresPerCostat;
        this.meandres = meandres;
        tauler = new Peca[quadresPerCostat + 2][quadresPerCostat + 2];
        crearTaulerCentre();
        crearTaulerBandaBuidaOest();
        crearTaulerBandaBuidaEst();
        crearTaulerBandaBuidaNord();
        crearTaulerBandaBuidaSud();
        afegirPeces();
    }
 
    // CORRECTA!!!
    // Crea i posa les peces a la part del tauler que es veu.
    private void crearTaulerCentre() throws Exception {
        boolean balanca = true;
        int i;
        int n = 1;
        for (i = 1; i <= quadresPerCostat; i++) {
            for (int j = 1; j <= quadresPerCostat; j++) {
                if (balanca) {
                    tauler[i][j] = new PecaA(new PosicioMeandres(i, j, this), this, meandres, n);
                }
                else {
                    tauler[i][j] = new PecaB(new PosicioMeandres(i, j, this), this, meandres, n);
                }
                balanca = ( ! balanca);
                n++;
            }
        }
        i = (quadresPerCostat + 2) / 2;  // fila i columna del centre del tauler
        n = ((quadresPerCostat * quadresPerCostat) / 2) + 1; // num del centre
        casellaBuidaCentre = new CasellaBuida(new PosicioMeandres(i, i, this), this, meandres, n);
        tauler[i][i] = casellaBuidaCentre;
    }
 
    // SEMBLA CORRECTA
    // Posa caselles buides a la banda de l'oest, al marge, que no es veuen en pantalla;
    // serveixen per saber quan se surt del tauler.
    private void crearTaulerBandaBuidaOest() throws Exception {
        for (int i = 1; i <= quadresPerCostat; i++) {
            tauler[i][0] = new CasellaBuida(new PosicioMeandres(i, 0, this), this, meandres, 0);
        }
    }
 
    // SEMBLA CORRECTA
    // Posa caselles buides a la banda de l'est, al marge, que no es veuen en pantalla;
    // serveixen per saber quan se surt del tauler.
    private void crearTaulerBandaBuidaEst() throws Exception {
        for (int i = 1; i <= quadresPerCostat; i++) {
            tauler[i][quadresPerCostat + 1] = new CasellaBuida(
                    new PosicioMeandres(i, (quadresPerCostat + 1), this), this, meandres, 0);
        }
    }
 
    // SEMBLA CORRECTA
    // Posa caselles buides a la banda del nord, al marge, que no es veuen en pantalla;
    // serveixen per saber quan se surt del tauler.
    private void crearTaulerBandaBuidaNord() throws Exception {
        for (int i = 1; i <= quadresPerCostat; i++) {
            tauler[0][i] = new CasellaBuida(new PosicioMeandres(0, i, this), this, meandres, 0);
        }
    }
 
    // SEMBLA CORRECTA
    // Posa caselles buides a la banda del sud, al marge, que no es veuen en pantalla;
    // serveixen per saber quan se surt del tauler.
    private void crearTaulerBandaBuidaSud() throws Exception {
        for (int i = 1; i <= quadresPerCostat; i++) {
            tauler[quadresPerCostat + 1][i] = new CasellaBuida(
                    new PosicioMeandres((quadresPerCostat + 1), i, this), this, meandres, 0);
        }
    }
 
    // CORRECTA!!!
    // Afegeix les peces al panell per dibuixar-les.
    public void afegirPeces () {
        setLayout(new GridLayout(quadresPerCostat, quadresPerCostat));
        for (int i = 1; i <= quadresPerCostat; i++) {
            for (int j = 1; j <= quadresPerCostat; j++) {
                add(tauler[i][j]);
                tauler[i][j].setBounds(0, 0, costatPeca, costatPeca);
            }
        }
    }
 
    // PROVAR
    // Mou les peces que hi ha entre pos i la casella buida del centre del tauler.
    public void mourePeces (PosicioMeandres pos) throws Exception {
        Orientacio dir = trobarDireccio(pos);
        int n = trobarNombrePecesAMoure(dir, pos);
        moure(dir, pos, n);
    }
 
    // Troba la direcció en que cal moure les peces.
    private Orientacio trobarDireccio (Posicio pos) {
        Orientacio dir;
        if (pos.getFila() == casellaBuidaCentre.getPosicio().getFila()) {
            if (pos.getColumna() < casellaBuidaCentre.getPosicio().getColumna()) {
                dir = Orientacio.EST;
            }
            else {
                dir = Orientacio.OEST;
            }
        }
        else {
            if (pos.getFila() < casellaBuidaCentre.getPosicio().getFila()) {
                dir = Orientacio.NORD;
            }
            else {
                dir = Orientacio.SUD;
            }
        }
        return dir;
    }
 
    // Calcula el nombre de peces que es mouran
    private int trobarNombrePecesAMoure (Orientacio dir, Posicio pos) throws Exception {
        int n;
        if (dir == Orientacio.NORD || dir == Orientacio.SUD) {
            n = pos.getFila() - casellaBuidaCentre.getPosicio().getFila();
        }
        else if (dir == Orientacio.EST || dir == Orientacio.OEST) {
            n = pos.getColumna() - casellaBuidaCentre.getPosicio().getColumna();
        }
        else {
            throw new Exception("Error de programació: direcció no vàlida.");
        }
        n = Math.abs(n);  // treiem el signe si és negatiu.
        return n;
    }
 
    /** 
     * Mou efectivament les peces al tauler.
     * 
     * @param dir
     * @param pos
     * @param n
     * @throws Exception 
     */
    private void moure (Orientacio dir, PosicioMeandres pos, int n) throws Exception {
        int casellaBuidaFila = casellaBuidaCentre.getPosicio().getFila();
        int casellaBuidaColumna = casellaBuidaCentre.getPosicio().getColumna();
        Peca novaCasellaBuida = casellaBuidaCentre;
        novaCasellaBuida.setPosicio(pos);
        Peca p;
        if (dir == Orientacio.NORD) {
            for (int fila = 0; fila < n; fila++) {
                p = getPeca(new Posicio((casellaBuidaFila - fila - 1), casellaBuidaColumna));
                setPeca(new Posicio((casellaBuidaFila - fila), casellaBuidaColumna), p);
            }
        }
        else if (dir == Orientacio.SUD) {
            for (int fila = 0; fila < n; fila++) {
                p = getPeca(new Posicio((casellaBuidaFila + fila + 1), casellaBuidaColumna));
                setPeca(new Posicio((casellaBuidaFila + fila), casellaBuidaColumna), p);
            }
        }
        else if (dir == Orientacio.EST) {
            for (int columna = 0; columna < n; columna++) {
                p = getPeca(new Posicio(casellaBuidaFila,(casellaBuidaColumna + columna + 1)));
                setPeca(new Posicio(casellaBuidaFila, (casellaBuidaColumna + columna)), p);
            }
        }
        else if (dir == Orientacio.OEST) {
            for (int columna = 0; columna < n; columna++) {
                p = getPeca(new Posicio(casellaBuidaFila, (casellaBuidaColumna - columna - 1)));
                setPeca(new Posicio(casellaBuidaFila, (casellaBuidaColumna - columna)), p);
            }
        }
        else {
            throw new Exception("Error de programació: direcció no vàlida.");
        }
        setCasellaBuidaCentre(novaCasellaBuida);
    }
 
    public ParellPecaOrientacio seguentPeca (ParellPecaOrientacio ppo) throws Exception {
        Peca pecaEntrada, pecaSortida;
        Orientacio direccioEntrada, direccioSortida, novaDireccioEntrada;
        int fila, columna;
 
        pecaEntrada = ppo.getPeca();
        direccioEntrada = ppo.getDireccio();
        fila = pecaEntrada.getPosicio().getFila();
        columna = pecaEntrada.getPosicio().getColumna();
        if ((fila < 1) || (fila > getQuadresPerCostat()) || (columna < 1) ||
                (columna > getQuadresPerCostat())) {
            throw new Exception("Error de programació: fila o columna fora de rang.");
        }
        if (pecaEntrada instanceof CasellaBuida) {
            throw new Exception("Error de programació: peca no pot ser del tipus CasellaBuida");
        }
        else {
            direccioSortida = pecaEntrada.trobarNovaDireccio(direccioEntrada);
            if ((direccioEntrada == Orientacio.NORD) || (direccioEntrada == Orientacio.SUD)){
                if (direccioSortida == Orientacio.EST) {
                    columna++;
                }
                else if (direccioSortida == Orientacio.OEST) {
                    columna--;
                }
                else {
                    throw new Exception("Error de programació: direccioSortida fora de rang.");
                }
            }
            if (direccioEntrada == Orientacio.EST || direccioEntrada == Orientacio.OEST) {
                if (direccioSortida == Orientacio.NORD) {
                    fila--;
                }
                else if (direccioSortida == Orientacio.SUD) {
                    fila++;
                }
                else {
                    throw new Exception("Error de programació: direccioSortida fora de rang.");
                }
            }
            else {
                throw new Exception("Error de programació: direccioEntrada fora de rang.");
            }
        }
        pecaSortida = getPeca(new PosicioMeandres(fila, columna, this));
        novaDireccioEntrada = pecaEntrada.traduirDirSortidaADirEntrada(direccioSortida);
 
        return new ParellPecaOrientacio(pecaSortida, novaDireccioEntrada);
    }
 
    public Peca getPeca (Posicio pos) {
        return tauler[pos.getFila()][pos.getColumna()];
    }
 
    public void setPeca (Posicio pos, Peca p) {
        tauler[pos.getFila()][pos.getColumna()] = p;
    }
 
    public Peca getCasellaBuidaCentre () {
        return casellaBuidaCentre;
    }
 
    public void setCasellaBuidaCentre (Peca p) throws Exception {
        if (p instanceof CasellaBuida) {
            casellaBuidaCentre = p;
        }
        else {
            throw new Exception("Error de programació: la casella no és buida.");
        }
    }
 
    public int getCostatTauler () {
        return costatTauler;
    }
 
    public int getQuadresPerCostat () {
        return quadresPerCostat;
    }
 
    public int getCostatPeca () {
        return costatPeca;
    }
 
    // Mètode per a proves:
    // NO FUNCIONA BÉ
    public PosicioMeandres crearPosicioJugableAleatoria () throws Exception {
        Random r = new Random();
        int fila, columna;
        do {
            fila = r.nextInt(quadresPerCostat) + 1;
            columna = r.nextInt(quadresPerCostat) + 1;
        } while ((fila != casellaBuidaCentre.getPosicio().getFila())
                ^ (columna != casellaBuidaCentre.getPosicio().getColumna()));
        return new PosicioMeandres(fila, columna, this);
    }
 
    // Mètode per a proves:
    public void canviarTauler (Tauler t) {
        remove(this);
        add(t);
        t.setBounds(100, 100, Tauler.COSTAT_TAULER, Tauler.COSTAT_TAULER);
    }
 
    // ********** AQUÍ TIENE QUE ESTAR EL FALLO *****************
    // ATENCIÓ: main DE PROVES, NO ÉS L'ENTRADA DE L'APLICACIÓ!!!
    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable () {
            @Override
            public void run () {
                try {
                    Meandres5 meandres = new Meandres5();
                    Tauler tauler = new Tauler(Tauler.QUADRES_COSTAT_5, meandres);
                    JFrame jf = new JFrame();
                    jf.setSize(800, 750);
                    jf.setLayout(null);
                    jf.add(tauler);
                    tauler.setBounds(50, 50, Tauler.COSTAT_TAULER, Tauler.COSTAT_TAULER);
                    jf.validate();
                    jf.pack();
                    jf.setVisible(true);
                    PosicioMeandres pos;
                    while (true) {
                        pos = tauler.crearPosicioJugableAleatoria();  // No funciona bé.
                        System.out.println(pos);
                        TimeUnit.SECONDS.sleep(10);
                        tauler.mourePeces(pos);
                        tauler.afegirPeces();
                        tauler.canviarTauler(tauler);
                        TimeUnit.SECONDS.sleep(10);
                   }
                }
                catch (Exception ex) {
                    System.err.println(ex);
                    System.exit(1);
                }
            }
        });
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

JFrame no responde

Publicado por Tom (1831 intervenciones) el 04/09/2014 15:46:27
Hay varias formas de hacerlo ... pero prueba algo como:

1
2
3
4
5
JFrame jf = new JFrame();
  jf.setPreferredSize(new Dimension(800, 750));
  jf.getContentPane().setLayout(null);
  jf.add(tauler);
  ...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

JFrame no responde

Publicado por David (11 intervenciones) el 09/09/2014 19:46:27
No funciona.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar