在java面板上绘制2d对象

时间:2012-07-23 19:28:42

标签: jpanel

我是java的新手,只是为了一个有趣的,我试图绘制到一个面板上。我有1个面板,我已经为背景着色,以便我可以看到它们的位置。我试图绘制圆形,椭圆形等,但结果是面板上没有任何东西出现在java面板上。

我会很乐意帮助你!

所以我的代码就在这里:

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);
}

}
}
}

1 个答案:

答案 0 :(得分:2)

在公共应用程序构造函数中最后调用pack();