我有2个类,一个类是我的GUI框架查看器。另一个是我正在尝试用于我的项目的一个类。 LabeledBar类提供了一种绘制方法。我将在我的FrameViewer类中有一个LabeledBars的ArrayList。我想遍历该列表并创建一个持有这些条的新面板。我无法弄清楚如何在这个框架上绘制这些条。如何创建使用从一个类中绘制方法到另一个类中的JPanel
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
/** LabeledBar is a rectangle with an interior label.
*
*
*/
public class LabeledBar
{
private int xLeft;
private int yTop;
private int width;
private int height;
private String label;
private Color color;
/** Construct this object from the specified dimensions.
* @param x x coordinate of the upper-left corner of this bar.
* @param y y coordinate of the upper-left corner of this bar.
* @param aWidth width of the bar in pixels.
* @param label the text to be displayed inside the bar.
* @param color desired color of the lines of the bar.
*/
public LabeledBar(int x, int y, int aWidth, String label, Color color)
{
xLeft = x;
yTop = y;
width = aWidth;
height = 20;
this.label = label;
this.color = color;
}
/** Draw this bar on the supplied graphics context.
* @param g2 the context on which to draw this bar.
*/
public void draw(Graphics2D g2)
{
Rectangle leftRectangle = new Rectangle(
xLeft, yTop,
width, height);
g2.setColor(color);
g2.draw(leftRectangle);
g2.drawString(label, xLeft+height/4, yTop+height*3/4);
}
}
这是我从我的另一个类尝试创建一个新的JFrame的方法,其中包括标签栏。
private void paintBars()
{
Graphics2D g = (Graphics2D)labeledBarsFrame.getGraphics();
for (LabeledBar element: bars)
{
element.draw(g);
}
//labeledBarsFrame.add(g);
}
查找M-V-C或Model-View-Controller,并以这种方式构建您的程序。切勿使用通过在组件上调用'getGraphics()'获得的Graphics对象进行绘制。而是在JPanel的paintComponent方法中绘制。阅读Swing图形教程,因为猜测这些东西是学习如何去做的不好方法。您可以在这里找到Swing教程和其他Swing资源的链接:[Swing Info](http://stackoverflow.com/tags/swing/info) –
问题解决后,您不会删除问题的文本。你“接受”帮助解决问题的答案,让人们知道问题已经解决。 – camickr
问题文字回滚。 Swager,请不要污蔑你的问题。此网站不是个人帮助网站,而是问答网站,其中提供了常见问题和答案,以供所有人查看,并为所有人提供帮助。通过削弱你的问题,你对未来的访问者完全没有帮助。 –