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