0
我有以下代碼:paint()方法的paintComponent不會被調用在JPanel的
package hra;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class HerniPole extends JPanel implements KeyListener
{
public int velikostPole;
HerniPole(int velikostPole)
{
this.velikostPole = velikostPole;
Color background = new Color(187, 173, 163);
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
{
System.err.println("Error!");
}
}
});
JFrame frame = new JFrame();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setTitle("2048");
frame.getContentPane().setBackground(background);
frame.setSize(450, 450);
frame.addKeyListener(this);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public void paintComponent(Graphics g)
{
System.out.println("xD");
g.setColor(Color.BLACK);
g.drawRect(20, 20, 20, 20);
g.setColor(Color.yellow);
}
@Override
public void keyTyped(KeyEvent ke)
{
System.out.println(ke.getKeyCode());
}
@Override
public void keyPressed(KeyEvent ke)
{
}
@Override
public void keyReleased(KeyEvent ke)
{
}
}
和的paintComponent()不會被調用,也甚至重繪()。我究竟做錯了什麼?我試過在StackOverflow上找到的所有東西,但沒有任何工作。如何解決這個問題?謝謝。
您創建一個JFrame,並使其可見之前的某個地方。但是你沒有添加任何組件。也許你應該創建一個HerniPole的實例並將其添加到你的JFrame中? – VGR