2015-09-27 53 views
0

我是一个初学者程序员,所以我不知道所有的vocab,但我理解java的一些基本知识。绘制到GUI从使用另一个类的主要在Java

所以我想从使用另一个类的主要GUI中绘制。我知道我不是非常具体,但这是我的代码,我会尽力解释我想要做的。

这是我的主要

import javax.swing.*; 
    import java.awt.*; 

public class ThisMain { 


public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    JFrame theGUI = new JFrame(); 
    theGUI.setTitle("GUI Program"); 
    theGUI.setSize(600, 400); 
    theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    ColorPanel panel = new ColorPanel(Color.white); 
    Container pane = theGUI.getContentPane(); 
    pane.add(panel); 
    theGUI.setVisible(true); 



    } 
} 

这是我的其他类

import javax.swing.*; 
import java.awt.*; 
public class ColorPanel extends JPanel { 
    public ColorPanel(Color backColor){ 
    setBackground(backColor); 

} 

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 

} 
} 

我试图用线

ColorPanel panel = new ColorPanel(Color.white); 

或者类似的东西使用的东西像

drawRect(); 

在主要,并在GUI中绘制。

这是我使用,我认为最接近于工作

import javax.swing.*; 
import java.awt.*; 

public class ThisMain { 


    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     JFrame theGUI = new JFrame(); 
     theGUI.setTitle("GUI Program"); 
     theGUI.setSize(600, 400); 
     theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     //I'm trying to draw a string in the JFrame using ColorPanel but i'm   Trying to do it from the main 
     ColorPanel panel = new ColorPanel(){ 
      public void paintComponent(Graphics g){ 
       super.paintComponent(g); 
       //This is the line I need to work using the ColorPanel in anyway 
       g.drawString("Hello world!", 20, 20); 
     }; 
     Container pane = theGUI.getContentPane(); 
     //The errors occur here 
     pane.add(panel); 
     theGUI.setVisible(true); 


    //and on these brackets 
    } 
} 
+0

'“或者类似的东西使用的东西一样......”' - 如何明确你想画的JPanel的?请尽可能详细,因为大多数解决方案将取决于这些细节。 –

+0

老实说我不知道​​我希望有人会知道该怎么做,因为我知道的是我应该使用那条线 – Winchester

+0

我不知道你想达到什么目的,为什么你有没有为你工作,因为它,你没有(真的)提出一个问题,或更重要的一点,问一个问题,我们可以回答 – MadProgrammer

回答

2

我真的不知道你在想什么做的(你还没有回答我的评论你的问题的代码澄清),但我想:

  • 给你的颜色面板一List<Shape>
  • 给它一个public void addShape(Shape s)方法,允许类的外部插入形状到这个列表中,然后调用repaint()
  • 而在ColorPanel的paintComponent方法中,遍历List,使用Graphics2D对象绘制每个Shape项目。

请注意,Shape是一个接口,所以您的List可以容纳Ellipse2D对象,Rectangle2D对象,Line2D对象,Path2D对象以及实现接口的其他对象的整个主机。另外,如果您想将每个图形与颜色相关联,则可以将这些项目存储在Map<Shape, Color>中。

0

你为什么不能编译通过这条线造成的原因:

颜色面板面板=新的颜色面板(Color.white);

因为ColorPanel类不包含在swing库中,因此您必须对其进行编码。这段代码扩展了JPanel并包含一个构造函数,它带有一个Color参数。当面板被实例化,并设置其背景色的构造函数运行:

import javax.swing.*; 
import java.awt.*; 

public class ColorPanel extends JPanel { 
    public ColorPanel(Color backColor) { 
    setBackground(backColor); 
    } 
} 
相关问题