学习java中,,作业要求按不同的按钮显示不同的图案,但我加入按钮后,不知道在怎么实现图案,actionPerformed方法中直接用Frame中定义buttonpanel对象吗package showFace;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.applet.*;
class drawsmile extends JPanel{ //画笑脸
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
int centerx=0;
int centery=0;
int minx=-200;
int miny=-200;
int maxx=200;
int maxy=200;
g2.translate(800,5);
g2.draw(new Line2D.Double(minx,centery,maxx,centery));
}
}
class drawcry extends JPanel{ //流泪脸
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
int centerx=0;
int centery=0;
int minx=-200;
int miny=-200;
int maxx=200;
int maxy=200;
g2.translate(800,5);
g2.draw(new Line2D.Double(centerx, miny, centerx, maxy));
}
}
class DrawFrame extends JFrame{
JPanel buttonPanel;
public DrawFrame(){
setTitle("显示表情"); //窗口标题
setSize(500,500); //窗口大小
//创建按钮
JButton smileButton=new JButton("微笑"); //创建按钮“微笑”
JButton cryButton=new JButton("流泪");
//创建绘制面板buttonPanel
JPanel buttonPanel=new JPanel();
//图形绘制中加入按钮
buttonPanel.add(smileButton);
buttonPanel.add(cryButton);
//按钮加入面板
add(buttonPanel);
//创建按钮事件
FaceAction smileAction=new FaceAction("smile");
//将事件与按钮连接起来
smileButton.addActionListener(smileAction);
}
//内部类
class FaceAction extends JPanel implements ActionListener{ //编写函数对应不同的类
private String a;
Panel panel=new Panel();
public FaceAction (String a){ //构造函数
if(a=="smile") {
drawsmile panel=new drawsmile();
}
if(a=="cry") {}
drawcry panel =new drawcry();
}
public void actionPerformed(ActionEvent event) {
buttonPanel.add(panel);
}
}
}
public class showface {//主函数showface为测试函数
public static void main(String[] args) {
// TODO Auto-generated method stub
DrawFrame a=new DrawFrame(); //框架定义
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setVisible(true);
}
}
添加回答
举报
0/150
提交
取消