2
我想寫一個更大的程序,但現在我卡住了,我無法弄清楚如何解決這個問題,這應該很容易。我創建了一個JLabel矩陣,當幀更新時,我從不同矩陣中設置每個JLabel的顏色。它似乎運作良好,但最後一個JLabel看起來很奇怪。無論在我的網格中有多少個JLabel,它總是在右下角看起來很奇怪。Java JLabel有白色中心當它應該填充
我用盡了一切辦法擺脫中間的白色小廣場,但沒有任何工程。
下面的代碼:
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.GridLayout;
import java.util.Arrays;
import javax.swing.text.*;
public class Tetris extends JPanel{
private int xsize = 10;
private int ysize = 21;
private JFrame tetrisFrame = new JFrame("Tetris");
private JLabel[][] tetrisField = new JLabel[xsize][ysize];
private byte[][] playGrid = new byte[xsize][ysize];
private byte[][] pieceL = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}};
private GridBagConstraints c = new GridBagConstraints();
public Tetris(){
tetrisFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
tetrisFrame.setPreferredSize(new Dimension(300, 600));
tetrisFrame.setLayout(new GridBagLayout());
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.NONE;
for (int x = 0; x < xsize; x++) {
for (int y = 0; y < ysize; y++) {
c.gridx = x;
c.gridy = y;
JLabel temp = new JLabel();
temp.setPreferredSize(new Dimension(20, 20));
temp.setOpaque(true);
temp.setBackground(new Color(0, 255, 0));
tetrisField[x][y] = temp;
tetrisFrame.add(temp, c);
}
}
tetrisFrame.add(this, c);
tetrisFrame.pack();
tetrisFrame.getContentPane().setBackground(new Color(120, 120, 120));
tetrisFrame.setVisible(true);
spawnPiece();
}
public void spawnPiece() {
for (int i = 0; i < 4; i++) {
playGrid[4+pieceL[i][0]][pieceL[i][1]] = 1;
}
}
public void paint(Graphics g) {
g.clearRect(0, 0, 500, 1050);
for (int x = 0; x < xsize; x++) {
for (int y = 0; y < ysize; y++) {
if (playGrid[x][y] == 1) {
tetrisField[x][y].setBackground(new Color(0, 0, 255));
} else {
tetrisField[x][y].setBackground(new Color(255, 0, 0));
}
}
}
}
}
白色顏色來自g.clearRect()
,如果刪除該行的中心是灰色的,與背景一樣。
我也有一個類來運行這個。它只創建一個Tetris類的新實例,啓動一個計時器並重新繪製。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.event.*;
import java.io.*;
public class Controller extends JPanel implements ActionListener {
private Tetris tetrisView;
private Timer test;
public Controller() {
tetrisView = new Tetris();
test = new Timer(100, this);
test.start();
}
public void actionPerformed(ActionEvent e) {
tetrisView.repaint();
}
public static void main(String[] args) {
new Controller();
}
}
我會嘗試,謝謝你發現我的錯誤!您是如何將組件移至JPanel的? – maxb 2015-02-05 14:09:04
我去了另一種方法,但你仍然回答我的原始問題。謝謝! – maxb 2015-02-08 23:30:15