基本操作题
1. 本题的功能是求1~100的自然数的累加,并打印输出
计算结果。
public class javal{
public static void main(String[]args){
int sum=0;
int i=1;
for(;;){
if( ){
sum=sum+i:
}else
’
;
}
System.OUt.println("sums="+sum);
}
}
参考解析:
第1处:i<=100 第2处:break
第3处:i++或i=i+1或i+=1
【解析】for(;;){}可以构成无限循环,所以第l处和第2处分别为跳出循环的条件和跳出循环;第3处为循环条件的自加操作。
点击进入>>全国计算机等级考试真题题库全套最新考试资料
2. 本题分别比较两个字符串"A"和"a"是否相等,并比较两个字符"A"和"a"是否相等,并输出比较结果。
public class javal{
public static void main(String[]args){
;
cl='A ';c2='a';
String strl=new String("A"),str2=new String
("a"):
if( )
System.Out.println("char"+c1+"equals"+"char"
+c2);
else
System.OUt.println("char"+cl+"doesn't equal
"+"char"+c2);
if( )
System.out.println("string"+strl+"equals"+
"string"+str2):
else
System.OUt.println("string"+strl+"doesn't e-
qual"+"string"+str2); .
}
}
参考解析:
第1处:char cl,c2 第2处:cl= =c2
第3处:strl.equals(str2)
【解析】第1处声明两个字符型变量cl和c2;第2处表示当cl等于c2时if条件为真;第3处判断strl和str2是否相等,返回值是布尔类型true或false。
3. 本题读取用户输入的字符流,直到用户输入字符串quit后结束。
importjava.io.*;
public class javal{
public static void main(String[]args){
;
BufferedReader in;
ir=new InputStreamReader(System.in);
in=new BufferedReader(ir);
System.OUt.println("please input:");
while( ){
try{
String s=in.readLine();
System.out.println("echo:"+s);
if(S.equals("quit"))
;
)catch(Exception e){
}
}
}
}
参考解析:
第1处:InputStreamReader ir 第2处:true
第3处:break
【解析】第1处构造一个InputStreamReader对象,把从控制台输入的字节作为参数,构建一个读取数据用的InDutStreamReader流,读取字节将其解码为字符;第2处while条件为真,执行循环;第3处当输入的s中的内容为quit时,跳出循环。
点击进入>>全国计算机等级考试真题题库全套最新考试资料
4. 本题中数组arr中存储了学生的成绩,分别为87,45,56,78,67,56,91,62,82,63,程序的功能是计算低于平均分的人数,并打印输出结果。请在程序空缺部分填写适当内容。使程序能正确运行。
public class javal{
public static void main(String[]args){
int arr[]={56,91,78,67,56,87,45,62,82,63};
int num=arr.length
int i=0;
int sumScore= 0;
int sumNum=0;
double average;
while(i<num){
sumScore=sumScore+arr[i];
;
}
average= ;
i=0;
do{
if(arr[i]<average)
sumNum++:
i++;
}while( );
System.OUt.println("average:"+average+",be-
lows average:"+sumNum);
}
}
参考解析:
第1处:i++或i=i+1或i+=1 第2处:(double)sumSeore/num
第3处:i<num
【解析】本程序首先通过第一个while循环求得平均数,再通过do while循环逐一比较,判断是否及格。第1处为while循环的自加;第2处计算平均数;第3处do while循环终止条件。
5. 本题统计score[]={37,89,63,60,59,78,91)中成绩不及格的人数。
public class javal{
public static void main(String[]args){
int score[]={37,89,63,60,59,78,91),
int sum=0:
int i=0;
while(i<score.length){
if(score[i]>=60){
;
;
}
;
i++;
}
System.OUt.println("below 60 sum:"+sum);
}
}
参考解析:
第1处:i++ 第2处:continue
第3处:sum++
【解析】第1处是为往后遍历做自加;第2处是结束本次循环;第3处是如果符合不及格这个条件,则sum做累加统计。
简单应用题
6. 本题是一个表格式的成绩单,其中包括“姓名”、“英语成绩”、“数学成绩”和“总成绩”,姓名和成绩都可以进行修改,单击按钮“计算每人总成绩”,则可以统计出每个人的总成绩并显示在总成绩栏中。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class java2 extends JFrame implements ActionL-
istener
{JTable table;Object a[][];
Object name[]={"姓名","英语成绩","数学成 绩","总成绩"};
JButton button;
java2()
{setTitle("java2");
a=new Object[8][4]:
for(int i=0;i<8;i++)
{for(int j=0;j<4;j++)
{if(j!=0)
a[i][j]="";
else
a[i][j]="';
}
}
button=new JButton("计算每人总成绩");
table=
button.addActionListener(this);
getContentPane().add(new JScrollPane(table),
BorderLayout.CENTER);
getContentPane().add(button,BorderLayout.
SOUTH):
setSize(400,200);
setVisible(true):
validate();
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(O);
}
});
}
public void actionPerformed(ActionEvent e)
{for(int i=0;i<8;i++)
{double sum=0;
boolean boo=true;
for(int J=1;j<=2;j++)
{try{
sum=sum+Double.parseDouble( );
}
catch(Exception ee)
{
boo=false;
table.repaint();
}
if(boo= =true)
{
a[i][3]=""+sum:
table.repaint();
}
}
}
}
public static void main(String args[-])
{java2 Win=new java2();
}
}
参考解析:
第1处:new.JTable(a,name) 第2处:a[i][J].toString()
【解析】第1处初始化表格变量;第2处取得表格中单元格内容并转换成Double型计算出总成绩。
7. 本题用复选框来控制字体的显示,窗口中有一个标签和两个复选按钮,这两个复选按钮分别对应的字体的两个特点:加粗和倾斜,任意选中一个按钮或两个都选中,标签上的字符串就显示对应的字体。
tmport.java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CheckBoxFrame extends JFrame implements Ac-
tionListener{
public CheckBoxFrame(){
setTitle("CheckBoxTest");
setSize(300,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)(
System.exit(O);
}
});
JPanel P=new JPanel();
bold=addCheckBox(p,"Bold");
italic=addCheckBox(P,"Italic");
getContentPane().add(p,"South");
panel=new CheekBoxTestPanel();
getContentPane().add(panel,"Center");
}
public JCheckBox addCheekBox(JPanel p,String
name){
JCheckBox c=new JCheekBox(name):
c.addActionListener( );
P.add(c);
return C;
}
public void {
int m=(bold.isSelected()?Font.BOLD:O)+
(italic.isSelected()?Font.ITALIC:O);
panel.setFont(m);
}
private CheckBoxTestPanel panel;
private JCheckBox bold;
private JCheckBox italic;
}
class CheckBoxTestPanel extends JPanel{
public CheckBoxTestPanel(){
setFont(Font.PLAIN);
}
public void setFont(int m){
setFont(new Font("SansSerif",m,12));
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
9.drawstring("The quick brown fox jumps over
the lazy dog.",0,50);
}
}
public class java2{
public static void main(String[]args){
JFrame frame=new CheckBoxFrame();
frame.show();
}
}
参考解析:
第1处:this 第2处:actionPerformed(ActionEvent evt)
【解析】第l处注册监听器进行授权,该方法的参数是事件处理的对象;第2处是actionPerformed方法通过读取ActionEvent对象的相关信息来得到事件发生时的情况。
8. 本题是一个Applet,它显示了一个树型结构。单击树结点的时候,就能将其子结点展开,同时下面的文本框可以显示出所单击的结点的路径,比如单击了根结点下B结点下B2结点,则文本框显示为"[TOP,B,B2]"。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class java2 extends JApplet
{
JTree tree;
JTextField jtf;
public void init()
{
Container cp=getContentPane();
cp.setLayout(new BorderLayout());
top=new DefaultMutableTreeNode("
TOP"):
DefaultMutableTreeNode a=new Default-
MutableTreeNode("A");
DefaultMutableTreeNode al = new Default-
MutableTreeNode("Al");
a.add(a1);
DefatIltMutableTreeNode a2=new Default-
MutableTreeNode("A2");
a.add(a2);
DefaultMutableTreeNode a3=new Default-
MutableTreeNode("A3");
a.add(a3);
DefaultMutableTreeNode b=new Default-
MutableTreeNode("B");
DefaultMutableTreeNode bl=new Default-
MutableTreeNode("Bl");
b.add(b1);
DefaultMutableTreeNode b2=new Default-
MutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3=new Default-
MutableTreeNode("B3"):
b.add(b3);
top.add(a);
top.add(b);
tree=new JTree(top);
int v=ScrollPaneConstants.VERTICAL_
SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_
SCRoLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(tree,V,h);
cp.add(jsp,BorderLayout.CENTER);
jtf=new JTextField(20);
cp.add(jtf,BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
}
void doMouseClicked(MouseEvent me)
{
tp=tree.getPathForLocation(me.getX
(),me.getY());
if(tp!=null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
}
参考解析:
第1处:DefauhMutableTreeNode 第2处:TreePath
【解析】第1处创建一个内容为TOP的top树结点;第2处因为getPathForLocation(int x,int y)返回由参数x、Y来确定指定位置的结点路径。
9. 本题的功能是通过鼠标确定两个点,然后画两点间的直线。窗口中有一个按钮“Draw line”,单击该按钮后,它就处于按下状态,然后用鼠标在窗口中单击一下,在单击的地方就会出现一个坐标圆点,用鼠标在另外一个地方单击一下又会出现另外一个圆点,并且此时在两个坐标圆点间画出一条直线,且“Draw line”处于可用状态,再单击这个按钮就可以画另外一条直线。
Import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
class EventQueuePanel extends JPanel implements Ac-
tionListener
{EventQueuePanel()
{JButton button=new JButton("Draw line");
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
(Graphics g=getGraphics();
P=getClick();
g.drawOval(P.x-2,P.Y-2,4,4);
Point q=getClick();
g.drawOval(q.x-2,q.y-2,4,4);
g.drawLine(P.X,P.Y,q.x,q.y);
g.dispose();
}
public Point getClick()
{EventQueue eq=Toolkit.getDefaultToolkit().
getSystemEventQueue();
while(true)
{try
{AWTEvent evt=eq.getNextEvent();
if(evt.getID()= =MouseEvent.MOUSE.
PRESSED)
{MouseEvent mevt=(MouseEvent)evt;
Point P= ();
Point top=getRootPane().getLocation();
P.X-=top.x;
P.Y-=top.Y;
return P;
}
}
catch(InterruptedException e)
{}
}
}
private int Y=60;
}
class EventQueueFrame extends JFrame
{public EventQueueFrame()
{setTitle("java2");
setSize(300,200);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
Container contentPane=getContentPane();
contentPane.add(new EventQueuePanel());
}
}
public class java2
{public static void main(String[]args)
{Frame frame=new EventQueueFrame();
frame.show();
}
}
参考解析:
第1处:Point 第2处:nevt.getPoint
【解析】第1处表示获得Point型的坐标给了P;第2处获得鼠标单击的坐标。
10. 本题是一个Applet,页面中有10个按钮,名称从“0~ 9”,用鼠标任意单击其中一个按钮后,通过键盘上的上下左右键可以控制按钮在窗口中移动。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class java2 extends Applet
{Button b[]=new Button[10];
int x,Y;
public void init()
{for(int i=0;i<=9;i++)
{b[i]=new Button(""+i);
b[i].addKeyListener(this);
addCb[i]);
}
}
public void
{Button button=(Button)e.getSource();
x=button.getBounds().x;
y—button.getBounds().y;
if(e,getKeyCode()= =KeyEvent.VK_UP)
{y=y-2;
if(y<=O)y=0;
button.setLocation(x,y);
}
else if(e.getKeyCode()= =KeyEvent.VK_
DOWN)
{y=y+2;
if(y>=300)y=300;
button,.setLocation(X,y);
}
else if(e.getKeyCode()= =KeyEvent.VK_
LEFT)
{x=x-2;
if(x<=0)x=0;
button.setLocation(x,y);
}
else if(e.getKeyCode()= =KeyEvent.VK_
RIGHT)
(x=X+2;
if(x>=300)x=300;
button.setLoeation(X,y);
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
}
参考解析:
第1处:implements KeyListener 第2处:keyPressed(KeyEvent e)
【解析】第1处实现接口监听键盘事件;第2处处理键盘事件。
综合应用题
11. 本题的功能是监听对于菜单项和工具条的操作。窗口中有一个菜单“Color”和一个工具体,菜单“Color”中有菜单项“Yellow”、“Blue”、“Red”和“Exit”,每个菜单项都有对应的图形,单击前三个颜色菜单项,主窗口就变成对应的颜色,单击“Exit”则退出程序。工具条上有4个按钮,分别为三个颜色按钮和一个退出程序的按钮,单击任意一个颜色按钮,主窗口将变成按钮对应的颜色,单击退出程序按钮,则退出程序。
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swin9.*;
public class java3
{
public static void main(String[]args)
{
ToolBarFrame frame=new ToolBarFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_
ON_CLOSE);
frame.show();
}
}
class ToolBarFrame extends JFrame
{
public ToolBarFrame()
{
setTitle("java3");
setSize(DEFAULT_WIDTH,DEFAUlT_
HElGHT);
Container contentPane=getContentPane();
panel=new JPanel();
contentPane.add(panel,BorderLayout.CEN-
TER);
Action blueAction=new ColorAction("Blue".
new ImageIcon("java3-blue-ball.gif"),Color.
BLUE);
Action yellowAction=new ColorAction("
Yellow",
new Imagelcon("java3-yellow-ball.gif"),Col-
or.YELLOW);
Action redAction=new ColorAction("Red".
new Imagelcon("java3-red-ball.gif"),Color.
RED);
Action exitAction=new
AbstractAction("Exit".new Imagelcon("java3-
exit.gif"))
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
};
exitAction.putValue(Action.SH()RT_DESCRIP-
TIoN,"Exit");
JToolBar bar=new JToolBar();
bar.add(blueAction);
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator();
bar.add(exitAction);
contentPane.addToolBar(bar,BorderLayout.
NoRTH);
JMenu menu=new JMenu("Color"):
menu.add(yellowAction);
menu.add(blueAction);
menu.add(redAction);
menu.add(exitAction);
JMenuBar menuBar=new JMenuBar():
menuBar.add(menu);
SetJ Menu(menuBar);
}
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT
=200;
private JPanel panel;
class ColorAction extends AbstractAction
{
public ColorAction(String name,Icon icon,Color
c)
{
putValue(Action.NAME,name);
putValue(Action.SMALL_ICON,icon);
putValue(Action.SHORT_DESCRIPTION,
name+"background");
putValue("Color",c);
}
public void actionPerformed(ActionEvent evt)
{
Color C=(Color)getValue("Color");
panel.setBackcolor(c);
}
}
}
参考解析:
第1处:contentPane.add(bar,BorderLayout.NORTH) 第2处:setJMenuBar(menuBar)
第3处:panel.setBackgroud(c)
【解析】第1处将工具条添加到容器内使用的方法应为add;第2处的上一步为将menu添加到menuBar中,从这一步的参数为menuBar可看出应为setJMenuBar;第3处设置面板的背景颜色应使用的方法为setBackgroud()。
12. 本题中,通过菜单“Connect”显示一个对话框,单击“ok”按钮后,所填写的内容就会传回到主窗口并显示出来。
import java.awt.* ;
import java.awt.event.*;
import javax.swin9.*;
public class java3 extends JFrame implements ActionL-
istener{
public java3(){
setTitle("java3");
setSize(300,300);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
JMenuBar mbar = new JMenuBar();
setJMenuBar(bar);
JMenu fileMenu=new JMenu("File");
mbar.add(fileMenu);
connectltem=new JMenuhem("Connect");
connecthem.addActionListener(this);
fileMenu.add(connecthem);
exithem=new JMenuhem("Exit");
exithem.addActionListener(this);
fileMenu.add(exithem);
}
public void actionPerformed(ActionEvent evt){
Object source=evt.getSource();
if(source= =connecthem){
Connectlnfo transfer=new ConnectInfo ("your-
name","pw");
if(dialog= =null)
dialog=new ConnectDialog(this);
if(dialog.showDialog(transfer)){
String uname=transfer.username;
String pwd=transfer.password;
Container contentPane=getContentPane();
contentPane.add(new JLabel("username="+
uname+",password="+pwd),"South");
validate();
}
}
else if(source= =exitltem)
System.exit(0);
}
public static void main(String[]args){
JFrame f=new java3();
f.show();
}
private ConnectDialog dialog=null;
private JMenuhem connecthem;
private JMenuhem exithem;
}
class Connectlnfo{
public String username;
public String password;
public Connectlnfo(String U,String p){
username=u;password=P;
}
}
class ConnectDialog extends JDialog implements Ac-
tionListener{
public ConnectDialog(){
super(parent,"Connect",true);
Container contentPane=getContentPane();
JPanel pl=new JPanel();
pl.setLayout(new GridLayout(2,2));
pl.add(newJLabel("User name:"));
pl.add(username=new JTextField(""));
pl.add(new JLabel("Password:"));
pl.add(password=new JPasswordField(""));
contentPane.add("Center",pl);
Panel p2=new Panel();
okButton=addButton(p2,"ok");
cancelButton=addButton(p2。"Cancel");
contentPane.add("South",p2);
setSize(240,120);
}
JButton addButton(Container C,String name){
JButton button=new JButton(name);
button.addActionListener(this);
C.add(button);
return button;
}
public void actionPerformed(ActionEvent evt){
object source=evt.getSource();
if(source= =okButton){
ok=true:
setVisible(false);
}
else if(source= =cancelButton)
setVisible(false);
}
public void showDialog(Connectlnfo transfer){
username.setText(transfer.username);
password.setText(transfer.password);
ok=false;
show();
if(ok){
transfer.username=username.getText();
transfer.password=new String(password.get-
Password());
}
return ok;
}
private JTextField username ;
private JPasswordField password;
private boolean ok;
private JButton okButton;
private JButton cancelButton;
}
参考解析:
第1处:setJMenuBar(mbar) 第2处:public ConnectDialog(JFrame parent)
第3处:public Boolean showDialog(Connectlnfotransfer)
【解析】第1处参数错误,bar未定义;第2处从下一行的super(parent,"Connect",true);可以看出,这里需要的参数为父窗体;第3处从下面的return ok;等可以看出,这是一个有Boolean型返回值的函数,故类型应为Boolean。
13. 本题是一个Applet,功能是用鼠标画不同颜色的图形。页面中有5个按钮“画红色图形”、“画绿色图形”、“画蓝色图形”、“橡皮”和“清除”,单击前三个按钮中的一个,按住鼠标左键或右键在面板中拖动,就能两出对应颜色的线条,单击“橡皮”按钮,按住鼠标左键或右键在面板中拖动就能将面板中的图形擦除掉,单击“清除”按钮,就能将面板中所有的图形清除掉。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class java3 extends Applet implements ActionListener
{int x=-1,y=-1,rubberNote=0,clearNote=0;
Color C=new Color(255,0,O);
int con=3;
Button b_red,b_blue,b_green,b_clear,b_quit;
public void init()
{
addMouseMotionListener(this);
b_red=new Button("画红色图形");
b_blue=new Button("画蓝色图形");
b_green=new Button("画绿色图形");
b_quit=new Button("橡皮");
b_clear=new Button("清除");
add(b_red);
add(b_green);
add(b_blue);
add(b_quit);
add(b_clear);
b_red.addActionListener(this);
b_green.addActionListener(this);
b_blue.addActionListener(this);
b_quit.addActionListener(this);
b_dear.addActionListener(this);
}
public void paint()
(if(x!=-l&&y!=-l&rubberNote= =
0R&clearNote= =0)
{g.setColor(c);
g.filloval(X,Y,con,con);
}
else if(rubberNote= =1&&clearNote= =O)
{g.clearRect(x,Y,10,10);
}
else if(clearNote= =1&&rubberNote= =O)
{g.clearRect(0,0,getSize().width,getSize().
height);
}
}
public void mouseDragged(MouseEvent e)
{x=(int)e.getX();y=(int)e.getY();repaint();
}
public void mouseMoved(MouseEvent e){)
public void update(Graphics g)
{paint(g);
}
public void actionPerformed(Event e)
{if(e.getSource()= =b-red)
{rubberNote=0;clearNote=0;c=new Color
(255,0,0);
}
else if(e.getSource()= =b_green)
{rubberNore=0;clearNote=0;C=new Color(0,
255,0);
}
else if(e.getSource()= =b_blue)
{rubberNote=0;clearNote=0;C=new Color(0,
0,255);
}
if(e.getSource()= =b—quit)
{rubberNote=1;clearNote=0;
}
if(e.getSource()= =b—clear)
{clearNote=1;rubberNote=0;repaint();
}
}
}
参考解析:
第1处:extends Applet implements ActionListener,MouseMotionListener 第2处:public void paint(Graphics g)
第3处:public void actionPerformed(ActionEvent e)
【解析】第1处继承Applet实现构件动作监听接口和鼠标移动监听接口;第2处定义paint绘制图形方法以Graphics类对象作为参数;第3处actionPerformed方法是发生对象的操作事件时调用,以一个监听动作类的对象e为参数。
14. 本题的功能是在文本域面板中添加一个带有行数的面板。窗口中有一个文本域,在文本域的左侧有一个带有数字的面板,该面板上的数字指示着文本域中的行数。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class java3 extends JFrame
{
public static JTextPane textPane;
public static JScrollPane scrollPane;
JPanel panel;
public java3()
{
super("java3()");
panel=new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBor-
der(20,20,20,20));
textPane=new JTextPane();
textPane.setFont(new Font("monospaeed",
Font.PLAIN,12));
scrollPane=new JScrollPane(textPane);
panel.add(scrollPane);
scrollPane.setPreferredsize(new Dimension(300,
250));
setContentPane(panel);
setCloseOperation(JFrame.EXIT_ON_CLOSE);
LineNumber lineNumber=new LineNumber();
scrollPane.setRowHeaderView(lineNumber);
}
public static void main(String[]args)
{
java3 ttp=new java3();
ttp.pack();
ttp.setVisible(true);
}
}
class LineNumber extends JTextPane
{
private final static Color DEFAULT_BACK-
GROUND=Color.gray;
private final static Color DEFAULT_FORE-
GROUND=Color.black;
private final static Font DEFAUl。T—FONT=new
Font("monospaced",Font.PLAIN,12);
private final static int HEIGHT=Integer.MAX_
VALUE-1000000;
private final static int MARGIN=5;
private FontMetrics fontMetrics;
private int lineHeight;
private int currentRowWidth;
private JComponent component;
private int componentFontHeight;
private int componentFontAscent;
public LineNumber(JComponent component)
{
if(component= =null)
{
setBackground(DEFAULT_BACKGROUND);
setForegroun"DEFAULT_FOREGROUND);
setFont(DEFAULT FONT);
this.component=this;
}
else
{
setBaekground(DEFAULT_BACKGROUND);
setForeground(component.getForeground());
setFont(component.getFont());
this.component=component;
}
componentFontHeight=component.getFontMet-
rics(component.getFont()).getHeight();
componentFontAscent=component.getFontMet-
ries(component.getFont()).getAscent();
setPreferredWidth(9999);
}
public void setPreferredWidth(int row)
{
int width=fontMetrics.stringWidth(String.val-
ueOf(row));
if(currentRowWidth<width)
{
currentRowWidth=width;
setPreferredSize(new Dfimension(2 * MARGIN
+width,HEIGHT));
}
}
public void setFont(Font font)
{
super.setFont(font);
fontMetrics=getFontMetrics(getFont());
}
public int getLineHeight()
{
if(hneHeight= =0)
return componentFontHeight;
else
return lineHeight;
}
public void setLineHeight(int lineHeight)
{
if(hneHeight>0)
this.lineHeight=lineHeight;
}
public int getStartOffset()
{
return component.getlnsets().top+component-
FontAscent;
}
public void paintComponent(Graphics g)
{
int lineHeight=getLineHeight();
int startOffset=getStartOffset();
Rectangle drawHere=g.getClipBounds();
g.setColor(getBackground());
g.fillRect(drawHere.x,drawHere.Y,drawHere.
width,drawHere.height);
g.setColor(getForeground());
int startLineNumber=(drawHere.y/line-
Height)+1;
int endLineNUmber = startLineNumber+
(drawHere.height/lineHeight);
int start=(drawHere.Y/hneHeight)*line-
Height+startOffset;
for(int i=startLineNumber;i<=endLineN-
umber;i++)
{
String lineNumber=String.valueOf(i);
int width=fontMetrics.stringWidth(lineNumber
);
g.drawstring(lineNumber,MARGIN+current-
RowWidth-width,start);
start+=lineHeight:
}
setPreferredWidth(endLineNumber);
}
}
参考解析:
第1处:scrollpane.setPreferredSize(new Dimension(300,250)) 第2处:setDefauhCloseOperation(JFrame.EXIT_ON_CLOSE)
第3处:LineNumber LineNumber=new LineNumber(textPane)
【解析】第1处Java是大小写敏感的;第2处设置窗口关闭方式应使用setDefauhCloseOperation()方法;第3处从下面的public LineNumber(JComponent component)可以看出LineNumber()需要JComDonent型参数。
15. 本题的功能是展示4种不同的对话框。窗口中有4个按钮:“消息”、“输入”、“确定”和“选择”,单击任意一个按钮,就能弹出一个对应的对话框。其中,消息对话框只有一个提示信息和一个“确定’’按钮,输入对话框有一个供输入的文本框及“确定”和“撤销”两个按钮;确定对话框中有一个提示信息和三个按钮“是”、“否”和“撤销”;而选择对话框中有一个提示信息和两个按钮“确定,,和“取消”。
import javax.swin9.*:
import java.awt.event.*;
import java.awt.*;
Public class java3 extends JFrame implements ButtonSelecte ActionListener
{
JButton btnMessage=new JButton("消息");
JButton btnlnput=new JButton("输入");
JButton btnConfirm=new JButton("确认");
JButton btnOption=new JButton("选择");
public java3()
{
super("java3");
btnMessage.addActionListener(this);
btnlnput.addActionListener(this);
btnConfirm.addActionListener(this);
btnOption.addActionListener(this);
getContentPane().setLayout( new FIowLavout
()):
getContentPane().add(btnMessage);
getContentPane().add(btnlnput):
getContentPane().add(btnConfirm):
getContentPane().add(btnOption);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
java3 fr=new java3();
fr.pack();
fr.setVisible(true);
}
Public void actionperformed(ActionEvent e)
{
Object[]opt={"确认","取消");
JButton instance:(JButton)e.getObject();
if(instance= =btnMessage)
JOptionPane.showMessageDialog(this,"消息对话框");
else if(instance= =btnInput、
JOptionPane.showInputDialog(this,"输入对话框");
else if(instance= =btnConfirm、
JOptionPane.showConfirmDialog(this,"确认对话框");
else
JOptionPane.showOptionDialog(this,"选择对话框","选择",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE,null,opt,opt[1]);
}
}
参考解析:
第1处:extends JFrame implements ActionListener 第2处:public void actionPerformed(ActionEvent e)
第3处:JButton instantce=(JButton)e.getSource()
【解析】第1处是实现与ActionEvent事件对应的接口,使之能够处理ActionEvent事件,相应的接口应为ActionListener;第2处是actionPerformed方法通过读取ActionEvent对象的相关信息来得到事件发生时的情况,Java是大小写敏感的;第3处是在Java的事件类中java.util.Event()bject类是所有事件对象的基础父类,通过getSource()方法可以得到事件源对象。
下载仅供下载体验和测试学习,不得商用和正当使用。
下载体验