2015-05-18 49 views
2

我一直在試圖學習如何繪製到Jpanel的遊戲。我想從不同的課程(如管理地圖的類和管理玩家模型的課程)中抽取它。從單獨的類中繪製到一個面板

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Main 
{ 
public static void main (String[] args) 
{ 
    JFrame frame = new JFrame ("Java Game"); 
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
    frame.setSize (1000, 600); 
    JPanel panel = new JPanel(); 
    panel.setBackground (Color.WHITE); 
    Dimension size = new Dimension(1000,500); 
    panel.add (new Player()); // Class with paintComponent method. 
    panel.setPreferredSize(size); 
    panel.setBackground(Color.BLUE); 
    frame.getContentPane().add(panel); 
    frame.setVisible(true); 
} 
} 

下一個類

import java.awt.Color; 
import java.awt.Graphics; 
import javax.swing.JComponent; 

@SuppressWarnings ("serial") 
public class Player extends JComponent 
{ 
int x = 50; 
int y = 450; 
public void paintComponent (Graphics g) 
{ 
    super.paintComponent(g); 
    g.setColor (Color.BLACK); 
    g.fillRect (x, y, 50, 50); 
} 
} 

回答

1

你可能想擴展JPanel。它已經不透明瞭,它可以爲你處理背景顏色。同樣給你的面板一個尺寸,就像他們做的那樣here,那麼你可以做相對於尺寸的繪圖。

image

Player p = new Player(); 
p.setBackground(Color.cyan); 
frame.add(p); 
frame.pack(); 
frame.setVisible(true); 
… 
public class Player extends JPanel { 

    private static final int X = 320; 
    private static final int Y = 240; 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.BLACK); 
     g.fillRect(getWidth()/2 - 25, getHeight()/2 - 25, 50, 50); 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(X, Y); 
    } 
}