學(xué)習(xí)java中,,作業(yè)要求按不同的按鈕顯示不同的圖案,但我加入按鈕后,不知道在怎么實(shí)現(xiàn)圖案,actionPerformed方法中直接用Frame中定義buttonpanel對(duì)象嗎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("顯示表情");????//窗口標(biāo)題
setSize(500,500);???????//窗口大小
//創(chuàng)建按鈕
JButton?smileButton=new?JButton("微笑");????//創(chuàng)建按鈕“微笑”
JButton?cryButton=new?JButton("流淚");
//創(chuàng)建繪制面板buttonPanel
JPanel?buttonPanel=new?JPanel();
//圖形繪制中加入按鈕
buttonPanel.add(smileButton);?
buttonPanel.add(cryButton);
//按鈕加入面板
add(buttonPanel);
//創(chuàng)建按鈕事件
FaceAction?smileAction=new?FaceAction("smile");
//將事件與按鈕連接起來(lái)
smileButton.addActionListener(smileAction);
}
//內(nèi)部類?
class?FaceAction?extends?JPanel?implements?ActionListener{???//編寫函數(shù)對(duì)應(yīng)不同的類
private?String?a;???
Panel?panel=new?Panel();
public?FaceAction?(String?a){?//構(gòu)造函數(shù)
???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?{//主函數(shù)showface為測(cè)試函數(shù)
public?static?void?main(String[]?args)?{
//?TODO?Auto-generated?method?stub
?????????DrawFrame?a=new?DrawFrame();??????//框架定義
?????????a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
?????????a.setVisible(true);
}
}
添加回答
舉報(bào)
0/150
提交
取消