我有2个类,一个类是我的GUI frameviewer。另一个是我试图用于我的项目的类。 LabeledBar类提供了draw方法。我将在我的FrameViewer类中有一个LabeledBars的ArrayList。我想遍历该列表并创建一个包含这些栏的新面板。我无法弄清楚如何将这些条形图绘制到该框架上。
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,其中包含labeledBars。
private void paintBars()
{
Graphics2D g = (Graphics2D)labeledBarsFrame.getGraphics();
for (LabeledBar element: bars)
{
element.draw(g);
}
//labeledBarsFrame.add(g);
}
答案 0 :(得分:3)
我想遍历该列表并创建一个包含这些栏的新面板。我无法弄清楚如何将这些条形图绘制到该框架上。
DrawOnComponent
示例应该让您开始朝着正确的方向前进。它显示了如何绘制在ArrayList中找到的自定义对象。
基本上,您需要创建JPanel
并覆盖paintComponent(...)
以迭代ArrayList
并在每个对象上调用draw(...)
方法。然后将面板添加到框架中。