2016-05-31 26 views
-1

我有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); 
} 
+1

查找M-V-C或Model-View-Controller,并以这种方式构建您的程序。切勿使用通过在组件上调用'getGraphics()'获得的Graphics对象进行绘制。而是在JPanel的paintComponent方法中绘制。阅读Swing图形教程,因为猜测这些东西是学习如何去做的不好方法。您可以在这里找到Swing教程和其他Swing资源的链接:[Swing Info](http://stackoverflow.com/tags/swing/info) –

+0

问题解决后,您不会删除问题的文本。你“接受”帮助解决问题的答案,让人们知道问题已经解决。 – camickr

+0

问题文字回滚。 Swager,请不要污蔑你的问题。此网站不是个人帮助网站,而是问答网站,其中提供了常见问题和答案,以供所有人查看,并为所有人提供帮助。通过削弱你的问题,你对未来的访问者完全没有帮助。 –

回答

3

我想通过该列表进行迭代并创建一个新的面板保持这些酒吧。我无法弄清楚如何在这个框架上绘制这些条。

结账Custom Painting Approaches

DrawOnComponent例子应该让你开始朝正确的方向发展。它显示了如何绘制在ArrayList中找到的自定义对象。

基本上,您需要创建一个JPanel并覆盖paintComponent(...)以迭代您的ArrayList并在每个对象上调用draw(...)方法。面板然后被添加到框架。

+0

不接受答案的原因是什么? – camickr

相关问题