2012-07-23 125 views
0

我是java中的新手,就像一个有趣的东西,我试图绘制到面板上。我有1个面板,我已经为背景着色,以便我可以看到它们在哪里。我试图绘制圆形,椭圆等,但结果是面板没有出现在Java面板上。在java面板上绘制2D对象

我会很乐意为您提供帮助!

所以我的代码放在这里:

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

public class app extends JFrame implements ActionListener{ 
boolean rectangle1=false; 
boolean circle1=false; 
boolean polygon1=false; 
boolean ellipse1=false; 

String x,y; 

JTextField input1; 
JTextField input2; 
JButton rectangle; 
JButton circle; 
JButton polygon; 
JButton ellipse; 
JLabel label1,label2,label3; 
Mypanel mypanel; 

public app(){ 
setSize(1000,1000); 
setLayout(new FlowLayout()); 
setVisible(true); 

JPanel mypanel =new JPanel(); 
mypanel.setPreferredSize(new Dimension(600,600)); 
mypanel.setBackground(Color.blue); 

rectangle=new JButton("rectangle"); 
circle=new JButton("circle"); 
polygon=new JButton("polygon"); 
ellipse=new JButton("ellipse"); 

rectangle.addActionListener(this); 
circle.addActionListener(this); 
polygon.addActionListener(this); 
ellipse.addActionListener(this); 

JLabel label1=new JLabel("my paint application"); 
JLabel label2=new JLabel("select line color"); 
JLabel label3=new JLabel("select fill color"); 

input1=new JTextField(4); 
input2=new JTextField(4); 

add(label1); 
add(rectangle); 
add(circle); 
add(ellipse); 
add(polygon); 
add(label2); 
add(input1); 
add(label3); 
add(input2); 
add(mypanel, BorderLayout.CENTER); 
} 
public void actionPerformed(ActionEvent e){ 
x=input1.getText(); 
y=input2.getText(); 

if(e.getSource()==rectangle) 
{ 
rectangle1= true; 
repaint(); 
} 
if(e.getSource()==circle) 
{ 
circle1= true; 
repaint(); 
} 
if(e.getSource()==polygon) 
{ 
polygon1= true; 
repaint(); 
} 
if(e.getSource()==ellipse) 
{ 
ellipse1= true; 
repaint(); 
} 

} 

public static void main(String args[]){ 
new app(); 
} 
class Mypanel extends JPanel{ 
public void paint(Graphics g){ 
if(rectangle1==true){ 
    rectangle1=false; 
    g.setColor(Color.red); 
    g.drawRect(10, 10,20,20); 
    g.setColor(Color.black); 
    g.fillRect(11, 11,20,20); 
} 

if(circle1==true){ 
circle1=false; 
g.setColor(Color.red); 
g.drawOval(250, 20, 40,40); 
g.setColor(Color.black); 
g.fillOval(249, 19,40,40); 
} 

if(polygon1==true){ 
polygon1=false; 
int xpoints[]={10,20,170,10}; 
int ypoints[]={20,40,140,20}; 
g.setColor(Color.red); 
g.fillPolygon(xpoints,ypoints,4); 
} 
if(ellipse1==true){ 
ellipse1=false; 
g.setColor(Color.red); 
g.drawOval(250, 20, 40,40); 
g.setColor(Color.black); 
g.fillOval(249, 19,40,40); 
} 

} 
} 
} 

回答

2

在公开的应用程序调用构造pack();在最后。