2017年計(jì)算機(jī)二級(jí)考試JAVA練習(xí)試題及答案3

字號(hào):


    三、簡單應(yīng)用題(共24分)
    本題的功能是通過按鈕來選擇窗口顯示的風(fēng)格。窗口
    中有三個(gè)按鈕:“Metal”、“Motif”和“Windows”,單擊任何一
    個(gè)按鈕,就能將窗口的風(fēng)格改變?yōu)榘粹o名稱所對(duì)應(yīng)的風(fēng)格。
    import java.a(chǎn)wt.*;
    import java.a(chǎn)wt.event.*;
    import javax.swing.*;
    class PlafPanel extends JPanel implements ActionLis-
    tener
    {public ()
    {metaIButton=new JButton("Metal");
    motifButtOn=new J Button("Motif");
    windowsButton=new JButton("Windows");
    add(metalButton);
    add(motifButton);
    add(windowsButton);
    metalButton.a(chǎn)ddActionListener(this);
    motifButton.a(chǎn)ddActionListener(this);
    windowsButton.a(chǎn)ddActionListener(this);
    }
    Dublic void actionPerformed(ActionEvent evt)
    {Object source=evt.getSource();
    String plaf="":
    if(source= =metalButton)
    plaf="javax.swing.plaf.metal.MetalLookAnd-
    Feel";
    else if(source= =motifButton)
    plaf="com.sun.java.swing.plaf.motif.Moti-
    fLookAndFeel";
    else if(source= =windowsButton)
    Dlaf="com.sun.java.swing.plaf.windows.Win-
    dowsLookAndFeel";
    try
    {UIManager.setLookAndFeel( );
    SwingUtilities.updateComponentTreeUI(this);
    }
    catch(Exception e){)
    }
    private JButton metalButton;
    private JButton motifButton;
    private JButton windowsButton;
    }
    class PlafFrame extends JFrame
    {public PlafFrame()
    { setTitle("simple");
    setSize(300,200);
    addWindowListener(new WindowAdapter()
    {public void windowClosing(WindowEvent e)
    {System.exit(O);
    }
    });
    Container contentPane=getContentPane();
    contentPane.a(chǎn)dd(new PlafPanel());
    }
    }
    public class java2
    {public static void main(String[]args)
    f JFrame frame=new PlafFrame();
    frame.show();
    }
    三、簡單應(yīng)用題
    第1處:PlafPanel
    第2處:plaf
    【解析】第一處由題意可知,類PlafPanel缺少構(gòu)造函數(shù),所以填PlafPanel。第二處是通過String類型的對(duì)象plaf,和UIManager.setLookAndFeel()方法實(shí)現(xiàn)顯示風(fēng)格的切換。