У меня есть проект, в котором у меня есть несколько компонентов. Проблема в том, что при выполнении команды repaint () JLabels не окрашиваются. Я хочу прояснить, что это НЕ проблема, что есть графика, на которой нарисовано или что-то еще Очевидно, что в repaint (), когда я заставляю JLabel перерисовывать, они не рисуют, пока вы не измените цепочку JLabel.
Инициализация JLabel и определение его параметров:
puntuacionL.setFont(new Font("Marker Felt", Font.PLAIN, 20));
puntuacionL.setBounds(710, 212, 150, 30);
puntuacionL.setOpaque(true);
puntuacionL.setBackground(Color.CYAN);
puntuacionL.setForeground(Color.white);
puntuacionL.setVisible(true);
comoJugar.setFont(new Font("Marker Felt", Font.PLAIN, 20));
comoJugar.setBounds(710, 245, 150, 30);
comoJugar.setOpaque(true);
comoJugar.setBackground(Color.CYAN);
comoJugar.setForeground(Color.white);
comoJugar.setVisible(true);
Я пробовал два варианта принудительного переопределения JLabel:
1. mietiqueta.setText("whatever")
.
В этой опции я переопределяю строку метки repaint ()
.
2.
Перекрасить компонент: mietiqueta.paintComponent(g)
Я бы загрузил снимок результата, который был бы очень полезен, но вам нужно как минимум 10 очков репутации.
Метод Repaint ():
@Override
public void update(Graphics g){
paint(g);
}
@Override
public void paint(Graphics g) {
if (offGraphics == null) {
offImage = createImage(900,900);
offGraphics = (Graphics2D) offImage.getGraphics();
}
puntuacionL.setText(" Puntuación: "+Integer.toString(puntuacion));
comoJugar.setText(" Pulsa H para ayuda");
Graphics2D g2d = (Graphics2D) g;
puntoIncialBala();
Image fondo = new ImageIcon(getClass().getResource("/imagenes/fondo.jpeg")).getImage();
Image img2 = new ImageIcon(getClass().getResource("/imagenes/fondoMapa.png")).getImage();
offGraphics.drawImage(img2, 30, 30, this);
int posVidaX = 710;
offGraphics.setColor(Color.CYAN);
offGraphics.fillRoundRect(710, 30, 150, 100, 10, 10);
for (int k = 0; k < vidas; k++) {
Image vida = new ImageIcon(getClass().getResource("/imagenes/vida.png")).getImage();
offGraphics.drawImage(vida, posVidaX, 50, this);
posVidaX = posVidaX + vida.getWidth(this);
}
timeLabel.paintComponents(g);
for (int k = 0; k < arrayCasilla.size(); k++) {
offGraphics.drawImage(arrayCasilla.get(k).getImg(), (int) arrayCasilla.get(k).getY(), (int) arrayCasilla.get(k).getX(), this);
}
Image img = new ImageIcon(getClass().getResource("/imagenes/BalaCanon.png")).getImage();
if (flagBala == true) {
//puntuacionL.setText(" Puntuación: "+Integer.toString(puntuacion));
if (pintarCasilla == true) {
puntuacionL.setText(" Puntuación: "+Integer.toString(puntuacion));
comoJugar.setText(" Pulsa H para ayuda");
queHayCasilla();
if (casilla[x][y].getTipo().compareTo("cangrejo") == 0) {
puntuacion = puntuacion + 1;
} else if (casilla[x][y].getTipo().compareTo("ron") == 0) {
posVidaX = 710;
//puntuacion = puntuacion + 1;
vidas--;
if (vidas == 0) {
timer.stop();
etiquetaFin.setVisible(true);
finalizar.setVisible(true);
contenedorFinal.setVisible(true);
}
offGraphics.setColor(Color.CYAN);
offGraphics.fillRoundRect(710, 30, 150, 100, 10, 10);
for (int k = 0; k < vidas; k++) {
Image vida = new ImageIcon(getClass().getResource("/imagenes/vida.png")).getImage();
offGraphics.drawImage(vida, posVidaX, 50, this);
posVidaX = posVidaX + vida.getWidth(this);
}
} else if (casilla[x][y].getTipo().compareTo("cofre") == 0) {
puntuacion = puntuacion + 2;
}
if (posY[y] < 441) {
arrayCasilla.add(casilla[x][y]);
}
for (int k = 0; k < arrayCasilla.size(); k++) {
if (posY[y] < 441) {
offGraphics.drawImage(arrayCasilla.get(k).getImg(), (int) arrayCasilla.get(k).getY(), (int) arrayCasilla.get(k).getX(), this);
}
}
animacion.stop();
if (!animacion.isRunning()) {
i = 0;
}
pintarCasilla = false;
flagBala = false;
} else {
offGraphics.drawImage(img, (int) x1, (int) x2, this);
}
}
try {
imgB = ImageIO.read(getClass().getResource("/imagenes/canon.png"));
} catch (IOException ex) {
Logger.getLogger(PanelCanon.class.getName()).log(Level.SEVERE, null, ex);
}
offGraphics.setColor(Color.gray);
offGraphics.fillRect(30, 720, 646, 122);
AffineTransform tx = AffineTransform.getRotateInstance(Math.PI / 2 - anguloRotacion, imgB.getWidth(this) / 2, imgB.getHeight(this) / 2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
tx.rotate(Math.PI / 2 - anguloRotacion);
System.out.println(tx.toString());
offGraphics.drawImage(op.filter(imgB, null), 360, 740, null);
g2d.drawImage(offImage, 0, 0, this);
puntuacionL.setText(" Puntuación: "+Integer.toString(puntuacion));
comoJugar.setText(" Pulsa H para ayuda");
System.out.println("Posicion bala x" + x1);
System.out.println("Posicion bala y: " + x2);
}
У меня есть таймер, который может каким-то образом мешать, этот таймер отвечает за управление обратным отсчетом.
Код таймера:
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (seconds == 0 && minutes == 0) {
timer.stop();
etiquetaFin.setVisible(true);
finalizar.setVisible(true);
contenedorFinal.setVisible(true);
} else if (seconds > 0) {
seconds--;
} else if (minutes > 0) {
minutes--;
seconds = 59;
}
revalidate();
//puntuacionL.paintImmediately(710, 212, 150, 30);
//puntuacionL.setText(" Puntuación: "+Integer.toString(puntuacion));
//comoJugar.setText(" Pulsa H para ayuda");
timeLabel.setText(" "+timeFormatter.format(minutes) + ":" + timeFormatter.format(seconds));
}
});
timer.start();
И вот тут происходит волшебство, и я больше ничего не понимаю. Как вы можете видеть внутри события, я прокомментировал строки:
puntuacionL.setText(" Puntuación: "+Integer.toString(puntuacion));
comoJugar.setText(" Pulsa H para ayuda");
Если в рамках таймера я переопределяю метки с помощью строки, отличной от paint ()
, они окрашиваются, но, конечно, это не работает для меня, поскольку я хочу, чтобы строка не изменялась.
Я не поместил весь класс, потому что он довольно большой, но если кому-то все еще нужен полный контекст, с удовольствием отредактирую вопрос и вставлю весь код.