java考證大題答案

iteye_6017發表於2010-04-23
Ⅱ 卷

四、操作題

242.

在下圖中的九個點上,空出中間的點,其餘的點上任意填入數字1至8;1的位置保持不動,

然後移動其餘的數字,使1到8順時針從小到大排列。移動的規則是:只能將數字沿線移向

空白的點。請將製作好的原始檔儲存為“t2.java”。

要求:

(1)分析問題,並描述你的演算法設計思想。

(2)程式設計顯示數字移動過程。

方法:首先找到1的位置;假定在A處。

如果1的下一個(B)是2,就找3;否則,

從1的下一個開始,往下找到2,假定位置在C上。

C的2到空位,C的前一個到C,......,B到B的下一個,最後,2到B,2排好。以些類推再排3,4......

關鍵問題在於,從1往下依次找2,3......移動時,卻是反向。於是將每個數字儲存於雙向迴圈連結串列的

結點中。正向查詢,反向移動。

public class GuardQueue{

public static void main(String[] args){

SortedCircute sc=new SortedCircute(new int[]{8,5,2,4,7,3,1,6});

int[] result=sc.sort();

for(int i=0;i<result.length;i++){

System.out.print(result[i]);

}

System.out.println();

}

}

class SortedCircute{

private Element head;

private int count;

public SortedCircute(int[] values){

count=values.length;

Element previous,next=null;

head=previous=new Element(values[0]);

for(int i=1;i<count;i++){

next=new Element(values[i]);

previous.next=next;

next.previous=previous;

previous=next;

}

next.next=head;

head.previous=next;

Element e=head;

}

public int[] sort(){

int maxSteps=count*(count+1)/2,index=0;

int[] steps=new int[maxSteps];

Element start=head;

while(start.value!=1){

start=start.next;

}

Element center=new Element(0),temp;

for(int i=1;i<count;i++){

if(start.next.value!=i+1){

for(temp=start.next.next;temp.value!=i+1;temp=temp.next);

center.previous=temp;

start.next.previous=center;

temp=center;

do{

temp.value=temp.previous.value;

steps[index++]=temp.value;

temp=temp.previous;

}while(temp!=center);

start.next.previous=start;

}

start=start.next;

}

int[] result=new int[index];

System.arraycopy(steps,0,result,0,index);

return result;

}

public String toString(){

String result=String.valueOf(head.value);

Element e=head.next;

for(int i=1;i<count;i++){

result+="-"+String.valueOf(e.value);

}

return result;

}

class Element{

Element next,previous;

int value;

public Element(int value){

this.value=value;

}

}

}



243.

編寫一個Java應用程式,對於給定的一個字串的集合,格式如:{aaa bbb ccc}, {bbb

ddd},{eee fff},{ggg},{ddd hhh} 要求將其中交集不為空的集合合併,要求合併完成後

的集合之間無交集,例如上例應輸出:{aaa bbb ccc ddd hhh},{eee fff}, {ggg} 請將製作

好的原始檔儲存為“t1.java”。

(1)分析問題,描述你解決這個問題的思路、處理流程,以及演算法複雜度。

(2)程式設計實現題目要求的集合合併。

(3)描述可能的改進(改進的方向如效果,演算法複雜度,效能等等)。

public class Interest2{



static ArrayList<StringSet> listSup = new ArrayList<StringSet>();

public void init (String... str) {

listSup.add(new StringSet(str));

}

public static void main(String args[]) {

Interest2 t = new Interest2();

//初始化

t.init("aaa","bbb","ccc");

t.init("eee","fff");

t.init("ggg");

t.init("ddd","hhh");

t.init("bbb","ddd");



//把交集不為空的集合合併

boolean flag = false;//標記是否有合併

for(int i = 0; i < listSup.size() - 1; i++) {



for (int j = i + 1; j < listSup.size(); j++) {

if (listSup.get(i).comp(listSup.get(j))) {

listSup.get(i).combine(listSup.get(j));//合併到get(i)中

listSup.remove(j);

flag = true;

}

}

if (flag) {//有合併下一次要從listSup的第一個元素開始從新比較

i = -1;

flag = false;

}

}



//輸出結果

Iterator<StringSet> it = listSup.iterator();

it.hasNext();

while (true) {

System.out.print(it.next());

if (it.hasNext())

System.out.print(",");

else

break;

}

}

}

class StringSet {

ArrayList<String> listString = new ArrayList<String>();

static String theSameString = "";

//提供陣列引數的構造器

public StringSet(String[] strs) {

for (int i = 0; i < strs.length; i++) {

listString.add(strs[i]);

}

}



//比較兩個StringSet中是否有相同的元素,有還回true

public boolean comp (StringSet strSet) {

for (int j = 0; j < this.listString.size(); j++) {

for (int i = 0; i < strSet.listString.size(); i++) {

if (this.listString.get(j).equals(strSet.listString.get(i))) {

theSameString = this.listString.get(j);

return true;

}

}

}

return false;

}



//結合兩個StringSet,不能含相同的元素

public void combine (StringSet strSet) {

this.listString.addAll(strSet.listString);

while (this.listString.contains(StringSet.theSameString)) {//以防有多個相同的

this.listString.remove(StringSet.theSameString);

}

this.listString.add(StringSet.theSameString);

}





//列印StringSet物件

public String toString () {

Collections.sort(this.listString);//對list中的元素排序

Iterator<String> it = this.listString.iterator();

String str = "";

str += "{ ";

while (it.hasNext()) {

str += it.next() + " ";

}

str += "}";

return str;

}

}



244.

撰寫一個 myString class,其中包含一個String物件,可於建構函式中通過引數來設定初值。

加入toString()和concatenate()。後者會將String物件附加於你的內部字串尾端。請為

myString()實現clone()。撰寫兩個static函式,令它們都接收myString reference x引數並調

用x.concatenate(“test”)。但第二個函式會先呼叫clone()。請測試這兩個函式並展示其不同

結果。

public class MyString implements Cloneable

{

String sourceString;



//帶引數的建構函式

public MyString(String str)

{

//在建構函式中通過引用數來設定初值

this.sourceString = str;

}



/**

* 重寫toString方法

*/

public String toString()

{

StringBuilder sb = new StringBuilder();

sb.append(sourceString);

sb.append(":");

return sb.toString();

}

/**

* 實現講傳入引數連線到你的字串尾端

*

* @param str

* 傳入引數

* @return 連結好的字串

*/

public String concatenate(String str)

{

return sourceString.concat(str);

}



/**

* 克隆實現

*/

public Object clone() throws CloneNotSupportedException

{

return super.clone();

}

/**

* 克隆前

*/

public static void cloneBegin(String str)

{

MyString testString = new MyString(" Clone begin ");

String result = testString.concatenate(str);

System.out.println(testString.toString() + result);

}

/**

* 克隆後

*/

public static void cloneAfter(String str) throws CloneNotSupportedException

{

MyString testString = new MyString(" Clone begin ");

MyString testStringClone = (MyString)testString.clone();

String result = testStringClone.concatenate(str);

System.out.println(testStringClone.toString()+result);

}

/**

* @param args

*/

public static void main(String[] args)

{

cloneBegin("test");

try

{

cloneAfter("testClone");

} catch (CloneNotSupportedException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

245.

為Thread撰寫兩個子類,其中一個的run()在啟動後取得第二個Thread object reference,然

後呼叫wait()。另一個子類的run()在過了數秒之後呼叫notifyAll(),喚醒第一個執行緒,使第

一個執行緒可以印出訊息。

MasterThread.java

public class MasterThread extends Thread {

public static void main(String[] args) {

MasterThread mt = new MasterThread();

mt.start();

}

public void run() {

SlaverThread st = new SlaverThread(this);

st.start();

synchronized (this) {

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("MasterThread say hello!");

}

}



SlaverThread.java

public class SlaverThread extends Thread {

private Thread mt = null;



public SlaverThread(Thread mt) {

this.mt = mt;

}

public void run() {

try {

System.out.println("SlaverThread started..");

sleep(3000);

System.out.println("3 second past");

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("notify MasterThread");

synchronized (mt) {

mt.notifyAll();

}

}

}



246.

編寫一個簡單的Web程式,根據當前時間的不同,在JSP頁面上顯示“上午”、“下午”。

只要在jsp頁面中假如如下程式碼就行

<%

if(new Date().getHours()>=0 && new Date().getHours()<=12){//看看當前時間是在0點到中午12點之間

%>

上午好

<%

}

else{

%>

下午好

<%

}

%>



247.

編寫一個簡單的Web程式,根據表彰中的使用者名稱,讓合法的使用者登入主頁面,使用session

物件將使用者名稱顯示在主頁面中,不合法的使用者將回發無效頁面。

login.jsp

<%@ page language="java" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>Login page</title>

</head>

<body>

<div>

<form action="login.servlet" method="post">

<fieldset style="width:50px;">

username:<input type="text" name="name" /><br>

password:<input type="password" name="password" />

<input type="submit" value="submit" />

</fieldset>



</form>

</div>

</body>

</html>

main.jsp

<%@ page language="java" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head></head>



<body>

<div>Welcome:<%=session.getAttribute("name")%></div>

</body>

</html>

LoginServlet

package test;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

public LoginServlet() {

super();

}

public void destroy() {

super.destroy();

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request,response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name=request.getParameter("name");

String password=request.getParameter("password");

if(null!=name&&"admin".equals(name)&&null!=password&&"admin".equals(password)){

request.getSession().setAttribute("name", name);

request.getRequestDispatcher("main.jsp").forward(request, response);

}

else{

response.sendRedirect("login.jsp");

}

}

public void init() throws ServletException {}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>

<servlet-name>LoginServlet</servlet-name>

<servlet-class>test.LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>login.servlet</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>login.jsp</welcome-file>

</welcome-file-list>

</web-app>



248.

使用JSP+JavaBean的模式開發一個Web程式,在JSP頁面中例項化一個JavaBean,然後

再把資料顯示在頁面中。

package mysql;

import java.sql.*;

public class Test{

private String user = "root";

private String pass = "soft5";

private String url = "";

private Connection con = null;

private Statement stmt = null;

private ResultSet rs = null;

public Test(){}



public void setUser (String user){

this.user = user;

}

public void setPass (String pass){

this.pass = pass;

}

public void BulidCon(){

try{

Class.forName("com.mysql.jdbc.Driver").newInstance();

url ="jdbc:mysql://localhost:3306/bookshop?useUnicode=true&characterEncoding=UTF-8";

con= DriverManager.getConnection(url,user,pass);

stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

}catch (Exception e){

System.out.println(e.getMessage());

}

}

public ResultSet selectLog(String sql){

try{

BulidCon();

rs = stmt.executeQuery(sql);

}catch(Exception e){

System.out.println(e.getMessage());

}

return rs;

}

public void updateLog(String sql){

try{

BulidCon();

stmt.executeUpdate(sql);

}catch (Exception e){

System.out.println(e.getMessage());

}

}

public void close(){

try{

con.close();

stmt.close();

}catch (SQLException e){

System.out.println(e.getMessage());

}

}

}



資料插入

<%@ page contentType="text/html;charset=GB2312" %>

<%@ page import="java.sql.*;"%>

<jsp:useBean id="ss" class="mysql.Test" scope="page"/>

<html>

<body>

<%



String sql="insert into books (id, bookName) values ('id','book')";

ss.updateLog(sql);

%>

</body>

</html>

資料查詢

<%@ page contentType="text/html;charset=GB2312" %>

<%@ page import="java.sql.*;"%>

<jsp:useBean id="ss" class="mysql.text" scope="page"/>

<html>

<body>

<%

ResultSet rs = null;

rs = ss.selectLog("select * from books");

while(rs.next()){

String bookId = rs.getString("ID");

String bookName = rs.getString("bookName");



out.print(bookId);

out.print(bookName);

}



%>

</body>

</html>



249.

使用JSP+Servlet+JavaBean的模式開發一個Web程式,將表單提交的資料顯示在下一頁面

中。

package test;

public class UserInfo {

private String name;

private String password;

private String gender;



public UserInfo(){}



public UserInfo(String name,String password,String gender){

this.name=name;

this.password=password;

this.gender=gender;

}



public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

}

InfoServlet

package test;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class InfoServlet extends HttpServlet {

public InfoServlet() {

super();

}

public void destroy() {

super.destroy();

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request,response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name=request.getParameter("name");

String password=request.getParameter("password");

String gender=request.getParameter("gender");

UserInfo user=new UserInfo();

user.setName(name);

user.setPassword(password);

user.setGender(gender);

request.setAttribute("user",user);

request.getRequestDispatcher("main.jsp").forward(request, response);

}

public void init() throws ServletException {}

}

info.jsp

<%@ page language="java" import="test.UserInfo" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head></head>



<body>

<div><%UserInfo user=(UserInfo)request.getAttribute("user");%>

Username:<%=user.getName()%><br/>

Password:<%=user.getPassword()%><br/>

Gender:<%=user.getGender()%>

</div>

</body>

</html>



250.

編寫程式ProductFrame.java,使用Web元件來建立使用者介面,將使用者輸入的資料插入到表

Product中。

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextArea;

public class ProductFrame extends JFrame implements ActionListener{ JButton button;

JTextArea jtx,jtx2;

Container c;

JPanel p;

public ProductFrame(){

c=this.getContentPane();

p= new JPanel();

jtx = new JTextArea(12,12);

jtx2 = new JTextArea(12,12);

button = new JButton("確定");

button.addActionListener(this);

p.add(jtx); p.add(jtx2);

p.add(button);

this.add(p);

this.setSize(500, 400);

this.setVisible(true); }

public void actionPerformed(ActionEvent e)

{ if(e.getSource() == button){

jtx2.setText(jtx.getText()); jtx.setText("");

}

}

public static void main(String args[]){

ProductFrame m =new ProductFrame();

}





251.

使用自定義標籤實現加法和減法的運算。

package test;

public class Calculate {

public static String add(String a,String b){

String cc = "";

try{

int c = Integer.parseInt(a)+Integer.parseInt(b);

cc=""+c;

}catch(Exception e){

e.printStackTrace();

}

return cc;

}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<jsp-config>

<taglib>

<taglib-uri>/ites</taglib-uri>

<taglib-location>/WEB-INF/tag/one.tld</taglib-location>

</taglib>

</jsp-config>

</web-app>

testTag.tld

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"

"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>



<description>自定義標籤</description>

<tlib-version>1.0</tlib-version>

<short-name>iter</short-name>

<function>

<name>add</name>

<function-class>com.Calcutate</function-class>

<function-signature>java.lang.String add(java.lang.String,java.lang.String)</function-signature>

</function>



</taglib>

<%@ page language="java" contentType="text/html; charset=GBK"%>

<%@ taglib uri="/ites" prefix="i"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

</head>

<body>



${i:add('44','9')};



</body>

</html>







252.

使用自定義標籤實現兩個數的乘積的運算。

import java.awt.*;

import java.awt.event.*;

class ComputerFrame extends Frame implements ActionListener

{ TextField textOne,textTwo,textResult;

Button getProblem,giveAnwser;

Label operatorLabel,message;

Teacher teacher;

ComputerFrame(String s)

{ super(s);

teacher=new Teacher();

setLayout(new FlowLayout());

textOne=new TextField(10); //建立textOne,其可見字元長是10

textTwo=new TextField(10); //建立textTwo,其可見字元長是10

textResult=new TextField(10); //建立textResult,其可見字元長是10

operatorLabel=new Label("+");

message=new Label("你還沒有回答呢");

getProblem=new Button("獲取題目");

giveAnwser=new Button("確認答案");

add(getProblem);

add(textOne);

add(operatorLabel);

add(textTwo);

add(new Label("="));

add(textResult);

add(giveAnwser);

add(message);

textResult.requestFocus();

textOne.setEditable(false);

textTwo.setEditable(false);

getProblem.addActionListener(this);//將當前視窗註冊為getProblem的ActionEvent事件監視器

giveAnwser.addActionListener(this);//將當前視窗註冊為giveAnwser的ActionEvent事件監視器

textResult.addActionListener(this);//將當前視窗註冊為textResult的ActionEvent事件監視器

setBounds(100,100,450,100);

setVisible(true);

// validate();

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{ if(e.getSource() == getProblem) //判斷事件源是否是getProblem

{ int number1=teacher.giveNumberOne(100);

int number2=teacher.giveNumberTwo(100);

String operator=teacher.giveOperator();

textOne.setText(""+number1);

textTwo.setText(""+number2);

operatorLabel.setText(operator);

message.setText("請回答");

textResult.setText(null);

}

if(e.getSource() == giveAnwser) //判斷事件源是否是giveAnwser

{ String answer=textResult.getText();

try{

int result=Integer.parseInt(answer);

if(teacher.getRight(result)==true)

{ message.setText("你回答正確");

}

else

{ message.setText("你回答錯誤");

}

}

catch(NumberFormatException ex)

{ message.setText("請輸入數字字元");

}

}

textResult.requestFocus();

// validate();

}

}

public class MainClass

{ public static void main(String args[])

{ ComputerFrame frame;

frame=new ComputerFrame("算術測試");//建立視窗,其標題為:算術測試



253.

從鍵盤上輸入10個整數,並放入一個一維陣列中,然後將其前5個元素與後5個元素對換,

即:第1個元素與第10個元素互換,第2個元素與第9個元素互換,……,第5個元素與

第6個元素互換。分別輸出陣列原來各元素的值和對換後各元素的值。

package Test;

import java.util.Scanner;

public class test {

public static void main(String[] args) {

Scanner sca = new Scanner(System.in);

int[] ints = new int[10];

System.out.println("請輸入10個數字");

for (int i = 0; i < 10; i++) {

ints[i] = sca.nextInt();

}

int temp;

for (int i = 0; i < 5; i++) {

temp = ints[i];

ints[i] = ints[9 - i];

ints[9 - i] = temp;

}

for (int i = 0; i < 10; i++) {

System.out.println(ints[i]);

}

}

}



254.

編寫一個程式,用一個執行緒顯示時間,一個執行緒來計算(如判斷一個大數是否是質數),當

質數計算完畢後,停止時間的顯示。

package Test;

public class test {

public static void main(String[] args) {

ThreadA thr1 = new ThreadA(1234567841);

ThreadB thr2 = new ThreadB(thr1);

thr1.start();

thr2.start();

}

}

class ThreadA extends Thread {

private int number;

public ThreadA(int number) {

this.number = number;

}

public void run() {

if (number < 2)

System.out.println(number + "不是素數");

for (int i = 2; i * i <= number; i++) {

if (number % i == 0) {

System.out.println(number + "不是素數");

return;

}

}

System.out.println(number + "是素數");

}

}

class ThreadB extends Thread {

private Thread thread;

private long time;

public ThreadB(Thread thread) {

this.thread = thread;

time = System.currentTimeMillis();

}

public void run() {

while (!thread.isAlive()) {

try {

Thread.sleep(50);

} catch (InterruptedException e) {

}

}

System.out.println(System.currentTimeMillis() - time+"毫秒");

}

}



255.

用JavaApplication編寫一個模擬的文字編輯器。給文字編輯器增設字型字號的功能。

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Notepad extends JFrame{



private String fontNames[] = { "宋體", "華文行楷", "隸書" };

private String[] sizeString = new String[30];

int[] size = new int[30];

private static JTextArea displayText;

private int style;

private JScrollPane scroll;

private JComboBox styleBox;

private JComboBox fontBox;

private JComboBox sizeBox;

private JPanel toolPanel;

private int rowNumber = 0;



public Notepad(){

super( "記事本" ); //標題設定

for(int i = 0 ; i<size.length;i++){

sizeString[i] = "" + (i+5) * 2;

size[i] = (i+5)*2;

}



Container container = this.getContentPane();

container.setLayout(new BorderLayout() );

toolPanel = new JPanel();

JLabel label1 = new JLabel("字型名稱");

toolPanel.add(label1);

fontBox = new JComboBox(fontNames);

fontBox.addItemListener( //事件處理

new ItemListener(){

public void itemStateChanged(ItemEvent event){

if( event.getStateChange() == ItemEvent.SELECTED){

displayText.setFont(

new Font( fontNames[fontBox.getSelectedIndex()],

displayText.getFont().getStyle(),

displayText.getFont().getSize() ) );

} //字型設定

}

}

);

toolPanel.add(fontBox);

JLabel label2 = new JLabel("字型風格");

toolPanel.add(label2);

String style_name[] = {"常規","傾斜","粗體","傾斜加粗體"};//字型風格設定

styleBox = new JComboBox(style_name);

styleBox.addItemListener( //事件處理

new ItemListener(){

public void itemStateChanged(ItemEvent event){

if( event.getStateChange() == ItemEvent.SELECTED){

if(styleBox.getSelectedIndex()==0) style = Font.PLAIN;

if(styleBox.getSelectedIndex()==1) style = Font.ITALIC;

if(styleBox.getSelectedIndex()==2) style = Font.BOLD;

if(styleBox.getSelectedIndex()==3) style = Font.ITALIC+Font.BOLD;

displayText.setFont( new Font( displayText.getFont().getName(),

style, displayText.getFont().getSize() ) );

}

}

}

);



toolPanel.add( styleBox );

JLabel label3 = new JLabel("字號");

toolPanel.add(label3);

sizeBox = new JComboBox(sizeString);

sizeBox.addItemListener(

new ItemListener(){

public void itemStateChanged(ItemEvent event){

if( event.getStateChange() == ItemEvent.SELECTED){

displayText.setFont( new Font( displayText.getFont().getName(),

displayText.getFont().getStyle(), size[sizeBox.getSelectedIndex()] ) );

}

}

}

);

toolPanel.add(sizeBox);

container.add( toolPanel, BorderLayout.NORTH );

JMenu fileMenu = new JMenu( "檔案(F)" );

fileMenu.setMnemonic( 'F' );



displayText = new JTextArea();

displayText.setFont( new Font( "Serif", Font.PLAIN, 24) );

scroll = new JScrollPane( displayText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );

container.add( scroll, BorderLayout.CENTER );

displayText.addKeyListener(

new KeyListener(){

public void keyPressed( KeyEvent event ){

rowNumber = displayText.getLineCount();

setTitle("總共" + rowNumber + "行");

}

public void keyReleased( KeyEvent event ){}

public void keyTyped( KeyEvent event ){ }

}

);

setSize( 700, 500 );

setVisible( true );

}



public static void main( String args[] ){

Notepad application = new Notepad();

application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );//預設視窗關閉方式

}

}

相關文章