我知道这没有被问到,我不应该那样做,但我无法抗拒……为什么要为此使用对话框?到目前为止,我还没有编写任何带有 swing 的程序,但是让事情运行起来似乎要好得多,例如滥用JTextField
作为彩色框,然后将它们堆叠在矩阵布局中,例如:
static int MATRIX_SIZE = 15;
static int CELL_SIZE = 20;
static Color ACTIVE = new Color(255, 128, 128);
static Color INACTIVE = new Color(0, 127, 127);
static JComponent items[][] = new JComponent[MATRIX_SIZE][MATRIX_SIZE];
// here we should use something more appropriate than dummy text fields
private static JComponent createItem() {
JTextField item = new JTextField("");
Dimension d = new Dimension(CELL_SIZE, CELL_SIZE);
item.setPreferredSize(d);
item.setBackground(INACTIVE);
item.setEditable(false);
item.setBorder(new EmptyBorder(0, 0, CELL_SIZE, CELL_SIZE));
return item;
}
private static void createMatrixView() {
JFrame frame = new JFrame("Show Pixels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent panel = new JPanel();
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
for (int i = 0; i < MATRIX_SIZE; i++) {
for (int j = 0; j < MATRIX_SIZE; j++) {
items[i][j] = createItem();
c.gridx = i;
c.gridy = j;
panel.add(items[i][j], c);
}
}
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
private static void update(boolean[][] values) {
for (int i = 0; i < MATRIX_SIZE; i++) {
for (int j = 0; j < MATRIX_SIZE; j++) {
items[i][j].setBackground(values[i][j] ? ACTIVE : INACTIVE);
}
}
}
public static void main(String[] args) {
createMatrixView();
boolean[][] matrix = new boolean[MATRIX_SIZE][MATRIX_SIZE];
matrix[0][0] = true;
matrix[0][2] = true;
matrix[1][1] = true;
matrix[2][0] = true;
matrix[2][2] = true;
update(matrix);
}