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