Я пытался поменять порядок tetris.initGamePanel(); и тетрис .initWindow(); в
Код: Выделить всё
public static void main(String[] args){
Tetris tetris = new Tetris();
tetris.initGamePanel();
tetris.initWindow();//Why the order matters???
//tetris.initGamePanel();
}
Я попытался отладить код и обнаружил, что остальная часть кода
Код: Выделить всё
public void initGamePanel() {
JPanel game_main = new JPanel();
game_main.setLayout(new GridLayout(game_x,game_y,1,1));
//initialize game panel
for(int i = 0; i < text.length; i++) {
for (int j = 0; j < text[i].length; j++) {
//create a new JTextArea Object that contains parameter i and j
text [i][j] = new JTextArea();
text [i][j].setBackground(Color.white);
text [i][j].addKeyListener(this);
text [i][j].setEditable(false);
if(j == 0 || j == text[i].length-1 || i == text.length-1) {
text [i][j].setBackground(Color.MAGENTA);
data [i][j] = 1;
}
game_main.add(text[i][j]);
}
}
this.setLayout(new BorderLayout());
this.add(game_main,BorderLayout.CENTER);
}
Код: Выделить всё
public void initGamePanel(){
JPanel game_main = new JPanel();
Это весь фрагмент кода:
Код: Выделить всё
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Tetris extends JFrame implements KeyListener {
private static final int game_x = 24;
private static final int game_y = 12;
public Tetris(){
text = new JTextArea[game_x][game_y];
data = new int[game_x][game_y];
//initGamePanel();
}
JTextArea[][] text;
int [][] data;
public void initWindow(){
this.setSize(400,800);
this.setLocationRelativeTo(null);//align to the center if the component is set to null
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle("Tetris");
}
public void initGamePanel(){
JPanel game_main = new JPanel();
game_main.setLayout(new GridLayout(game_x,game_y,1,1));
//initialize game panel
for(int i = 0; i < text.length; i++){
for (int j = 0; j < text[i].length; j++){
//create a new JTextArea Object that contains parameter i and j
text [i][j] = new JTextArea();
text [i][j].setBackground(Color.white);
text [i][j].addKeyListener(this);
text [i][j].setEditable(false);
if(j == 0 || j == text[i].length-1 || i == text.length-1 ){
text [i][j].setBackground(Color.MAGENTA);
data [i][j] = 1;
}
game_main.add(text[i][j]);
}
}
this.setLayout(new BorderLayout());
this.add(game_main,BorderLayout.CENTER);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args){
Tetris tetris = new Tetris();
tetris.initGamePanel();
tetris.initWindow();//Why the order matters???
//tetris.initGamePanel();
}
}
Подробнее здесь: https://stackoverflow.com/questions/770 ... as-created