2015-02-09 43 views
1

我做了一个名为Robit的类(故意拼错),它用paint(Graphics g)方法定义了一个正方形。我伸出的JFrame和所有工作正常,我只是无法得到平方绘制用油漆实例化一个类来制作一个正方形

import java.awt.*; 

public class Robit { 

int[] location = new int[4]; 
double[] vectors = new double[2]; 
Color mainColor; 

    public Robit(Color color, int x) { 
     mainColor = color; 
     switch (x) { 
      case 0: 
       location[0] = 50; 
       break; 
      case 1: 
       location[0] = 700; 
       break; 
      default: 
       location[0] = 350; 
       break; 
     } 
     location[1] = 400; 
     location[2] = 50; 
     location[3] = 50; 

    } 

    public void paint(Graphics g) { 
     g.setColor(mainColor); 
     g.fillRect(location[0], location[1], location[2], location[3]); 

    } 
    public int getX() { 
     return location[0]; 
    } 

    public int getY() { 
     return location[1]; 
    } 

} 

`那类IM实例化,继承人在那里我让 进口java.awt.Color中; import javax.swing。*;

public class Frame extends JFrame { 
    public Frame(){ 
     setLayout(null); 


     Robit r1 = new Robit(Color.red, 0); 
     Robit r2 = new Robit(Color.blue, 1); 


    } 
} 

和主类

import javax.swing.JFrame; 

public class App { 

    public static void main(String[] args) { 
     Frame f = new Frame(); 
     f.setSize(800, 450); 
     f.setResizable(false); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setVisible(true); 

    } 
} 
+0

'setLayout(null);'Java GUI必须在不同的OS上工作',屏幕大小,屏幕分辨率等。因此,它们不利于像素完美布局。请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[white space]的布局填充和边框(http://stackoverflow.com/a/17874718/ 418556)。 '公共类框架扩展了JFrame ..'这是一个自定义类的可怜的名字,因为有一个'java.awt.Frame'。那么'RobitsFrame'怎么样呢? – 2015-02-10 00:44:54

回答

0

你是不是叫你的Robitpaint方法。请尝试以下操作:

public class Frame extends JFrame { 
    protected Robit r1; 
    protected Robit r2; 
    public Frame(){ 
     setLayout(null); 

     r1 = new Robit(Color.red, 0); 
     r2 = new Robit(Color.blue, 1); 
    } 

    public void paint(Graphics g) 
    { 
     super.paint(g); 
     r1.paint(g); 
     r2.paint(g); 
    } 
}