我正在尝试将图形元素传递给链。我需要能够绘制一些不同的骰子并为每个实例返回正确的骰子。我可以编译这个,但我不知道我是否正确地这样做。我想将图形组件传递给要显示的面板。
我的缩短涂料类
import java.awt.*;
import javax.swing.*;
class DiePaint extends JPanel
{
Graphics g;
public Graphics dieSwitch(int inInt)
{
return die1();
}
private Graphics die1()
{
//reset drawing
repaint();
//draw a die with 1 pip
g.setColor(Color.BLACK);
g.drawRect(0,0,50,50);
g.drawOval(24,24,2,2);
g.fillOval(24,24,2,2);
//return graphic
return g;
}
}
我正试图用来调用它的另一个类的方法。
private void setDie()
{
//set die labels
die1P.paint(drawDie.dieSwitch(game.getDie(0)));
}
答案 0 :(得分:2)
“我想将图形组件传递给要显示的面板。”
不,你不。
您需要了解如何Perform Custom Painting。您需要在面板中使用paintComponent
方法
@Override
protected void paintComponent(Graphic s) {
super.paintComponent(g);
// draw here
}
您没有像在这里paint
die1P.paint(drawDie.dieSwitch
如果您希望能够设置正在绘制的内容,则可以使用用于绘制的Die
对象。像
class Die {
public void draw(Graphics g) {
// draw die here
}
}
然后在您的小组类中,setter
对象的Die
将重新显示新的Die
。您可能希望有办法区分每个骰子。将一些参数传递给构造函数来执行此操作。然后绘制一个模具。
public class DiePanel extends JPanel {
private Die die;
public void setDie(Die die) {
this.die = die;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (die != null) {
die.draw(g);
}
}
}
您也可以想要Die
一个界面,这样您就可以实现差异Die
对象,例如DieOne
,DieTwo
等。像< / p>
public interface Die {
void Draw(Grapchis g);
}
public class DieOne {
@Override
public void draw(Graphics g) {
// draw die one
}
}
当您致电setDie()
时,您可以传递特定的Die
,例如
DieOne dieOne = new DieOne();
...
diePanel.setDie(dieOne);
答案 1 :(得分:1)
是的,您可以使用BufferedImage传递绘制的组件....首先,您在此BufferedImage上绘制图形,然后传递此图像,然后将此图像绘制到Panel ...以下是代码:
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
class DiePaint extends JPanel
{
int width=500; int height=500; //you can change as requred
BufferedImage buffg=new BufferedImage(width,height , BufferedImage.TYPE_INT_ARGB);
Graphics g;
public BufferedImage dieSwitch(int inInt) //change return type to BufferedImage
{
return die1();
}
private BufferedImage die1() // change return type to BufferedImage
{
g=buffg.getGraphics(); //get Graphics from buffg..
//reset drawing
repaint();
//draw a die with 1 pip
g.setColor(Color.BLACK); //draw all the component on buffg using its Graphics g
g.drawRect(0,0,50,50);
g.drawOval(24,24,2,2);
g.fillOval(24,24,2,2);
//return graphic
return buffg;
}
}
现在一旦你得到这个&#34; buffg&#34;现在你可以在任何面板上绘制.....
JPanel p=new JPanel(){
@Override
public void paint(Graphics g){
g.drawImage(drawDie.dieSwitch(game.getDie(0))); //get & draw Image
}
};