我想使用paint方法將圖像添加到屏幕上?我不想使用JLabel,因爲我想自己設置位置。如何在屏幕上繪製圖像?
Board.class:
public class Board extends JPanel{
BufferedImage image;
public Board() {
try {
image = ImageIO.read(new File("C:\\Users\\alexa_000\\Pictures\\RocketShip.png"));
}catch(IOException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawImage(image, 0, 0, this);
}
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(),image.getHeight());
}
}
RType.class:
public class RType extends JFrame{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Panel panel = new Panel();
frame.setContentPane(panel);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
你在哪裏重寫這個'paint'方法?在擴展'JPanel'的類中? –
請發佈一個更完整的程序,一個我們可以運行並向我們展示什麼是不工作的,[sscce](http://sscce.org)。 –
這裏是一個很好的教程爲你:http://zetcode.com/tutorials/javaswingtutorial/painting/ –