2013-05-13 5 views
0

Непонятно, как перерисовать JPanel в моем существующем коде. Я также не понимаю, как называется paintComponent. Во-первых, я просто хотел бы очистить JPanel, но я даже не могу этого сделать.Повторная перепрофилировка JPanel не работает

Я хочу, чтобы можно было нажать кнопку «Далее» и перерисовать JPanel, учитывая изменение в сетке, с которой я читаю цвета. У меня возникли проблемы с изменением JPanel вообще через вызовы, revalidate(), removeAll() и repaint() на мои плейлисты JPanel.

Я называю это и ничего не происходит с существующими JPanel ниже из тетрис сетки (плитка) (на фото) ..

В коде ниже я есть вложенный класс, который расширяет JPanel и функции установки создает окно взяв в 2d решетку arraylist и построим исходную сетку.

Как по крайней мере, ясно, что JPanel или даже лучше перерисовывать с новой сеткой ... Я думал, метод:

public void redraw(Grid g) { 
     removeAll(); 
        getColor(); //gets new grid of tiles 
        repaint(); 
     revalidate(); 
    } 

Внутри вложенного класса JPanel, но это не кажется, что изменить JPanel даже не очищают текущий чертеж.

Tetris Board reading in original grid

public class BoardGraphics { 

    public ArrayList<ArrayList<Color>> colours; 

    private final int width; 

    private int height; 

    private JFrame display; 

    private TetrisSquares tiles; 

    private Container c; 

    public BoardGraphics(int width, int height, 
     ArrayList<ArrayList<Integer>> grid) { 
     this.width = width; 
     this.height = height; 
     colours = new ArrayList<ArrayList<Color>>(width); 
     setColor(grid); 
     setup(); 
    } 

    public void setup() { 
     System.out.println("Let the Tetris Begin"); 
     display = new JFrame("Tetris Agent"); 



     final TextArea welcome = new TextArea("Welcome to Tetris", 2, 10, 
       TextArea.SCROLLBARS_NONE); 

     welcome.setBackground(Color.black); 
     welcome.setForeground(Color.red); 
     welcome.setFont(new Font("monospaced", 0, 11)); 
     welcome.setEditable(false); 

     Button btnStart = new Button("Next Move"); 
     btnStart.setFocusable(false); 



     tiles = new TetrisSquares(TetrisBoard.BOARD_WIDTH, height); 

     c = new Container(); 
     c.setLayout(new BorderLayout()); 
     c.add(welcome, BorderLayout.NORTH); 
     c.add(tiles); 
     c.add(btnStart,BorderLayout.SOUTH); 

     btnStart.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
      tiles.removeAll(); 
      tiles.revalidate(); 
      } 
     }); 


     final Container main = new Container(); 

     main.setLayout(new GridLayout(1, 2)); 
     display.add(c); 



     display.pack(); 

     display.addWindowListener(new WindowAdapter() { 
      public void windowClosing(WindowEvent e) { 
       System.exit(0); 
      } 
     }); 

     display.setVisible(true); 
    } 

    public ArrayList<ArrayList<Color>> getBoard() { 
     return colours; 
    } 

    public void setColor(ArrayList<ArrayList<Integer>> grid) { 
     ListIterator<Integer> li; 

     for (int i = 0; i < width; i++) { 
      colours.add(new ArrayList<Color>()); 
      li = grid.get(i).listIterator(); 
      for (int j = 0; j <= height; j++) { 
       int n = 0; 
       if(li.hasNext()) { 
        n = li.next(); 

       } 
       switch (n) { 
       case 1: 
        colours.get(i).add(Color.red); 
        break; 
       case 2: 
        colours.get(i).add(Color.pink); 
        break; 
       case 3: 
        colours.get(i).add(Color.orange); 
        break; 
       case 4: 
        colours.get(i).add(Color.yellow); 
        break; 
       case 5: 
        colours.get(i).add(Color.green); 
        break; 
       case 6: 
        colours.get(i).add(Color.cyan); 
        break; 
       case 7: 
        colours.get(i).add(Color.blue); 
        break; 
       default: 
        colours.get(i).add(Color.gray); 
        break; 
       } 
      } 
     } 
    } 



    public class TetrisSquares extends JPanel { 

     public int width; 
     public int height; 

     public TetrisSquares(int width, int height) { 
      this.width = width; 
      this.height = width; 
      this.setPreferredSize(new Dimension(width * 20, height * 20)); 
     } 

     public void redraw() { 
      removeAll(); 
      //add your elements 
      //revalidate(); 
      //repaint(); 
     } 


     public void paintComponent(Graphics g) { 

      super.paintComponent(g); 

      Graphics2D graphics = (Graphics2D) g; 
      graphics.setColor(Color.BLACK); 
      /* 
      * tiles.width = getSize().width/width; tiles.height = 
      * getSize().height/800; 
      * 
      * insets.left = (getSize().width - width * tiles.width)/2; 
      * insets.right = insets.left; insets.top = 0; insets.bottom = 
      * getSize().height - height * tiles.height; 
      */ 
      Dimension size = getSize(); 
      Insets insets = getInsets(); 

      int w = size.width - insets.left - insets.right; 
      int h = size.height - insets.top - insets.bottom; 

      int tileWidth = w/width; 
      int tileHeight = w/width; 

      ListIterator<Color> li; 

      for (int i = 0; i < width; i++) { 
       li = colours.get(i).listIterator(); 
       int n = 20; 

       while(li.hasNext()) { 
        --n; 
        int x = (int) (i * tileWidth); 
        int y = (int) (n * tileHeight); 
        graphics.setColor(li.next()); 
        graphics.fillRect(x, y, tileWidth, tileHeight); 
        graphics.setColor(Color.black); 
        graphics.drawRect(x, y, tileWidth, tileHeight); 
       } 
      } 

     } 

    } 

} 
+1

Для лучшей помощи раньше, опубликовать [SSCCE] (HTTP: //sscce.org/). –

ответ

3

Начните с того, прочитанный через Painting in AWT and Swing, чтобы получить лучшее понимание системы окраски.

removeAll удаляет все дочерние элементы из контейнера, это на самом деле не собирается, чтобы помочь вам в этой ситуации ...

revalidate сделок с подсистемой компоновки и обновления иерархии контейнера в ответ на изменения в содержимое контейнера, опять же, на самом деле не собирается помогать ...

в вас paintComponent метод, вы ссылаетесь на ArrayList под названием colours, который используется краска квадратов. Вам нужно сбросить этот список, чтобы остановить метод paintComponent от заполнения цветов

redaw Ваш метод должен выглядеть более что-то вроде ...

public void redraw() { 
    colours.clear(); 
    repaint(); 
} 
Смежные вопросы