[英]Draw free hand in Java, add drawing to JPanel
In my class Test I create Three panels. 在我的课堂测试中,我创建了三个面板。 In my class Draw I draw by free hand.
在课堂绘画中,我徒手绘画。
I want to add my object d to centerPanel. 我想将我的对象d添加到centerPanel中。 When I do that nothing draws.
当我这样做时,什么也没画。 But if i add it to the frame (using getContentPane().add) it draws.
但是,如果我将其添加到框架(使用getContentPane()。add),则会绘制。 Does anyone knows where the problem is?
有谁知道问题出在哪里?
topPanel = new JPanel();
centerPanel = new JPanel();
bottomPanel = new JPanel();
Draw d = new Draw();
getContentPane().add(d, BorderLayout.CENTER); //This works
add(topPanel, BorderLayout.PAGE_START);
add(bottomPanel, BorderLayout.PAGE_END);
/* I WANT THIS TO WORK INSTEAD */
/* centerPanel.add(d); */ //How can I write this line of code?
/* add(topPanel, BorderLayout.PAGE_START); */
/* add(centerPanel, BorderLayout.CENTER); */
/* add(bottomPanel, BorderLayout.PAGE_END); */
Class Draw: 课程抽奖:
public class FreeHand extends JComponent, MouseListener, MouseMotionListener {
int x;
int y;
int posX;
int posY;
public FreeHand()
{
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
public void mousePressed(MouseEvent me) {
posX = me.getX();
posY = me.getY();
}
@Override
public void mouseDragged(MouseEvent me) {
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawLine(posX, posY, me.getX(), me.getY());
posX = me.getX();
posY = me.getY();
}
@Override
public void mouseMoved(MouseEvent me) {}
@Override
public void mouseClicked(MouseEvent me) {}
@Override
public void mouseEntered(MouseEvent me) {}
@Override
public void mouseExited(MouseEvent me) {}
@Override
public void mouseReleased(MouseEvent me) {}
}
getContentPane().add(d, BorderLayout.CENTER);
getContentPane()。add(d,BorderLayout.CENTER); //This works
//这有效
That works because the content pane uses a BorderLayout
and the layout manager will give all the available space to the Draw component when it is added to the CENTER. 之所以可行,是因为内容窗格使用
BorderLayout
,并且布局管理器在将Draw组件添加到CENTER时将为其提供所有可用空间。
centerPanel.add(d);
add(centerPanel, BorderLayout.CENTER);
This doesn't work because the BorderLayout will give all the space to the "centerPanel". 这是行不通的,因为BorderLayout会将所有空间分配给“ centerPanel”。 But the "centerPanel uses a FlowLayout and by default the FlowLayout will respect the preferred size of any component added to it. Your Draw class doesn't have a preferred size so the size is zero.
但是“ centerPanel使用FlowLayout,默认情况下,FlowLayout将遵循添加到其中的任何组件的首选大小。您的Draw类没有首选大小,因此大小为零。
You can change the layout manager of the centerPanel to also use a BorderLayout or you can override the getPreferredSize()
method of your Draw class to return the appropriate preferred size of your panel. 您可以将centerPanel的布局管理器更改为也使用BorderLayout,或者可以重写Draw类的
getPreferredSize()
方法以返回面板的适当首选大小。
The question is why do you want to create an extra "centerPanel" when you don't need it? 问题是,为什么在不需要时要创建一个额外的“ centerPanel”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.