Improve Your Java Skills – Series III

Java Tips

Java Tips – Series III

概观: In this ‘Java Tips’ series, we have mainly worked on the hands-on coding part. The objective of this series is to help you understand the coding part and implementation details. 我们尝试涵盖各种主题以及编码示例,,en,你也会喜欢我们的,,en,Java系列我,,en,Java系列II,,en,如何使用applet显示时钟,,en,该示例使用String类和Calendar类来显示applet时钟,,en,日历类给出'小时'的值,,en,'分钟'和'秒',,en,import java.applet。*,,en,公共类ClockApplet扩展Applet实现Runnable,,en,线程t,,en,T1,,vi,公开无效的开始,,en,t =新线程,,en,t.start,,en,公共无效运行,,en,t1 = Thread.currentThread,,en,t1 == t,,en,重绘,,en,t1.sleep,,en. You will also like our Java series IJava series II








1) How to display a clock using an applet?

一: The example has used String class and Calendar class to display the applet clock. Calendar class gives the value of ‘Hours’, ‘Minutes’ and ‘second’.

进口的软件包java.awt。*;

import java.applet.*;

import java.applet.*;

进口的软件包java.awt。*;

import java.util.*;

public class ClockApplet extends Applet implements Runnable{

Thread t,t1;

public void start(){

t = new Thread(this);

t.start();

}

public void run(){

t1 = Thread.currentThread();

而(t1 == t){

repaint();

尝试{

t1.sleep(1000);

}

抓(InterruptedException的Ë){}

}

}

public void paint(Graphics g){

Calendar cal = new GregorianCalendar,,en,String hour = String.valueOf,,en,cal.get,,en,Calendar.HOUR,,en,String minute = String.valueOf,,en,Calendar.MINUTE,,en,String second = String.valueOf,,en,Calendar.SECOND,,en,小时,,en,您必须再次在浏览器或applet查看器中运行applet以检查输出,,en,如何在Applet中创建事件侦听器,,en,下面的示例演示如何创建具有要添加的按钮的基本Applet,,en,减去两个数字,,en,这里使用的方法是addActionListener,,en,听一个事件,,en,点击一个按钮,,en,构造函数来创建一个按钮,,en,公共类EventListeners扩展了Applet,,en,实现ActionListener,,en,TextArea txtArea,,en,字符串添加,,en,减去,,en,j =,,en,sum = 0,Sub = 0,,en,txtArea = new TextArea,,en,txtArea.setEditable,,en,中央,,en,按钮b =新按钮,,en,加,,en,按钮c =新按钮,,en,b.addActionListener,,en,c.addActionListener,,en();

String hour = String.valueOf(cal.get(Calendar.HOUR));

String minute = String.valueOf(cal.get(Calendar.MINUTE));

String second = String.valueOf(cal.get(Calendar.SECOND));

g.drawString(hour + “:” + minute + “:” + second, 20, 30);

}

}

Again you have to run the applet in a browser or applet viewer to check the output.

2) How to create an event listener in Applet?

一: Following example demonstrates how to create a basic Applet having buttons to add & subtract two numbers. Methods used here are addActionListener () to listen to an event(click on a button) & 按键() constructor to create a button.

import java.applet.*;
import java.awt.event.*;
进口的软件包java.awt。*;

public class EventListeners extends Applet

implements ActionListener{

TextArea txtArea;

String Add, Subtract;

INT I = 10, j = 20, sum =0,Sub=0;

public void init(){

txtArea = new TextArea(10,20);

txtArea.setEditable(false);

加(txtArea,”center”);

Button b = new Button(“Add”);

Button c = new Button(“Subtract”);

b.addActionListener(this);

c.addActionListener(this);

加(b);

加(Ç);

}

public void actionPerformed,,en,ActionEvent e,,en,sum = i,,en,txtArea.setText,,en,txtArea.append,,en,按钮源=,,en,e.getSource,,en,source.getLabel,,en,和,,en,和,,en,Sub = i,,en,Sub = j,,en,子,,en,如何使用Applet在新窗口中打开链接,,en,此示例演示如何使用showDocument在新窗口中从applet打开特定网页,,en,第二个参数的方法为,,en,import java.net。*,,en,public class testURL_NewWindow扩展了Applet,,en,String link_Text =,,en,谷歌,,en,LINK_TEXT,,en,ActionEvent ae,,en,ae.getSource,,en,字符串链接=,,en,万维网。,,en,同,,pt,AppletContext a = getAppletContext,,en,网址url =新网址,,en,链接,,en,a.showDocument,,en,MalformedURLException e,,en,如何使用Applet读取文件,,en,以下代码段演示了如何使用openStream使用Applet读取文件,,en,URL的方法,,en,有不同的方法来读取像缓冲流一样的流,,en,定制缓冲流等,,en(ActionEvent e){

sum = i + Ĵ;

txtArea.setText(“”);

txtArea.append(“I = “+ 我 + “\t” + “j = ” + Ĵ + “\Ň”);

Button source = (按键)e.getSource();

如果(source.getLabel() == “Add”){

txtArea.append(“Sum : ” + sum + “\Ň”);

}

如果(我 >Ĵ){

Sub = i – Ĵ;

}

其他{

Sub = j – 我;

}

如果(source.getLabel() == “Subtract”){

txtArea.append(“Sub : ” + Sub + “\Ň”);

}

}

}

3) How to open a link in a new window using Applet?

一: This example demonstrates how to open a particular webpage from an applet in a new window using showDocument() method with second argument as “_空白” .

import java.applet.*;

进口的软件包java.awt。*;

import java.net.*;

import java.awt.event.*;

public class testURL_NewWindow extends Applet

implements ActionListener{

public void init(){

String link_Text = “google”;

Button b = new Button(link_Text);

b.addActionListener(this);

加(b);

}

public void actionPerformed,,en,ActionEvent e,,en,sum = i,,en,txtArea.setText,,en,txtArea.append,,en,按钮源=,,en,e.getSource,,en,source.getLabel,,en,和,,en,和,,en,Sub = i,,en,Sub = j,,en,子,,en,如何使用Applet在新窗口中打开链接,,en,此示例演示如何使用showDocument在新窗口中从applet打开特定网页,,en,第二个参数的方法为,,en,import java.net。*,,en,public class testURL_NewWindow扩展了Applet,,en,String link_Text =,,en,谷歌,,en,LINK_TEXT,,en,ActionEvent ae,,en,ae.getSource,,en,字符串链接=,,en,万维网。,,en,同,,pt,AppletContext a = getAppletContext,,en,网址url =新网址,,en,链接,,en,a.showDocument,,en,MalformedURLException e,,en,如何使用Applet读取文件,,en,以下代码段演示了如何使用openStream使用Applet读取文件,,en,URL的方法,,en,有不同的方法来读取像缓冲流一样的流,,en,定制缓冲流等,,en(ActionEvent ae){

Button source = (按键)ae.getSource();

String link = “HTTP://www.”+source.getLabel()+”.com”;

尝试 {

AppletContext a = getAppletContext();

URL url = new URL(link);

a.showDocument(url,”_空白”);

}

抓 (MalformedURLException e){

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

}

}

}








4) How to read a file using Applet?

一: The following code snippet demonstrates how to read a file using an Applet using openStream() method of URL. There are different ways to read a stream like buffered stream, customized buffered stream etc. 这里我们使用缓冲流来读取数据,,en,public class readFileApplet扩展了Applet,,en,String fileToRead =,,en,test1.txt的,,en,StringBuffer strBuff,,en,String prHtml = this.getParameter,,en,fileToRead,,el,prHtml,,en,fileToRead = new String,,en,READFILE,,en,public void readFile,,en,字符串行,,en,URL url = null,,en,url =新网址,,en,getCodeBase,,en,InputStream in = url.openStream,,en,BufferedReader bf = new BufferedReader,,en,strBuff = new StringBuffer,,en,line = bf.readLine,,en,strBuff.append,,en,文件名,,en,strBuff.toString,,en,如何使用Applet创建不同的形状,,en,此示例演示如何创建将具有一行的applet,,en,一个椭圆形,,en,使用drawLine的Rectangle,,en,DRAW,,sk,和drawRect,,en,Graphics类的方法,,en,在java中,Graphics类被广泛用于绘制图表,而那些用于饼图,,en,条形图等,,en,公共类Shapes扩展了Applet,,en,int x = 300,y = 100,r = 50,,en,g.drawLine,,en.

import java.applet.*;

进口的软件包java.awt。*;

进口java.io. *;

import java.net.*;

public class readFileApplet extends Applet{

String fileToRead = “test1.txt”;

StringBuffer strBuff;

TextArea txtArea;

Graphics g;

public void init(){

txtArea = new TextArea(100, 100);

txtArea.setEditable(false);

加(txtArea, “center”);

String prHtml = this.getParameter(“fileToRead”);

如果 (prHtml != NULL) fileToRead = new String(prHtml);

readFile();

}

public void readFile(){

String line;

URL url = null;

尝试{

url = new URL(getCodeBase(), fileToRead);

}

抓(MalformedURLException e){}

尝试{

InputStream in = url.openStream();

BufferedReader bf = new BufferedReader

(new InputStreamReader(in));

strBuff = new StringBuffer();

而((line = bf.readLine()) != NULL){

strBuff.append(line + “\Ň”);

}

txtArea.append(“File Name : ” + fileToRead + “\Ň”);

txtArea.append(strBuff.toString());

}

抓(IOException异常Ë){

e.printStackTrace();

}

}

}

5) How to create different shapes using Applet?

一: This example demonstrates how to create an applet which will have a line, an Oval & a Rectangle using drawLine(), drawOval() and drawRect() methods of Graphics class. In java Graphics class is widely used to draw diagrams and those are used in pie chart, bar diagram etc.

import java.applet.*;

进口的软件包java.awt。*;

public class Shapes extends Applet{

int x=300,y=100,r=50;

public void paint(Graphics g){

g.drawLine(30,300,200,10);

g.drawOval,,en,X-R,,en,和-R,,es,g.drawRect,,en,上面的代码示例将在启用Java的Web浏览中生成以下结果,,en,一条线,,en,椭圆,,en,将在浏览器中绘制一个矩形,,en,如何在JAVA中使用swing applet,,en,Swing是java生成UI接口的重要组件,,en,这些swing组件也在applet中用于创建用户界面。以下示例演示了如何通过实现ActionListener在JAVA中使用Swing Applet,,en,通过创建JLabel,,en,公共类SApplet扩展Applet实现ActionListener,,en,TextField输入,,en,标签label1,label2,,en,按钮b1,,en,JLabel lbl,,en,int num,,en,label1 =新标签,,en,请输入号码,,en,LABEL1,,en,label1.setBackground,,en,label1.setForeground,,en,Color.magenta,,en,input = new TextField,,en,label2 =新标签,,en,LABEL2,,en,label2.setBackground,,en,label2.setForeground,,en,output = new TextField,,en,b1 =新按钮,,en,b1.addActionListener,,en(x-r,y-r,100,100);

g.drawRect(400,50,200,100);

}

}

The above code sample will produce the following result in a java enabled web browse

A line, Oval & a Rectangle will be drawn in the browser.

6) How to use swing applet in JAVA?

一: Swing is an important component in java to produce UI interfaces. These swing components are also used in applet to make the user interface.Following example demonstrates how to go use Swing Applet in JAVA by implementing ActionListener & by creating JLabels.

导入javax.swing中。;

import java.applet.*;

进口的软件包java.awt。*;

import java.awt.event.*;

public class SApplet extends Applet implements ActionListener {

TextField input,output;

Label label1,label2;

Button b1;

JLabel lbl;

int num, sum = 0;

public void init(){

label1 = new Label(“please enter number : “);

加(label1);

label1.setBackground(Color.yellow);

label1.setForeground(Color.magenta);

input = new TextField(5);

加(input);

label2 = new Label(“Sum : “);

加(label2);

label2.setBackground(Color.yellow);

label2.setForeground(Color.magenta);

output = new TextField(20);

加(output);

b1 = new Button(“Add”);

加(B1);

b1.addActionListener(this);

lbl =新的JLabel,,en,Swing Applet示例,,en,LBL,,en,num = Integer.parseInt,,en,input.getText,,en,sum = sum num,,en,input.setText,,en,output.setText,,en,Integer.toString,,en,lbl.setForeground,,en,Color.blue,,en,lbl.setText,,en,输出第二个文本框,,en,output.getText,,en,NumberFormatException e,,en,输入无效,,en,如何使用Applet写入文件,,en,在以下示例中,已使用java文本区域输入用户输入,,en,输入输入后,它已写入本地文件系统的文件中,,en,文件,,en,构造函数已用于创建文件,,en,import java.applet.Applet,,en,public class WriteFile扩展了Applet,,en,按钮写=新按钮,,en,将writeToFile,,en,标签label1 =新标签,,en,输入文件名,,en,TextField text = new TextField,,en,标签label2 =新标签,,en,写下你的文字,,en,TextArea area = new TextArea,,en,Color.lightGray,,en,区,,en,BorderLayout.CENTER,,en,write.addActionListener,,en,新的ActionListener,,en(“Swing Applet Example. “);

加(lbl);

的setBackground(Color.yellow);

}

public void actionPerformed,,en,ActionEvent e,,en,sum = i,,en,txtArea.setText,,en,txtArea.append,,en,按钮源=,,en,e.getSource,,en,source.getLabel,,en,和,,en,和,,en,Sub = i,,en,Sub = j,,en,子,,en,如何使用Applet在新窗口中打开链接,,en,此示例演示如何使用showDocument在新窗口中从applet打开特定网页,,en,第二个参数的方法为,,en,import java.net。*,,en,public class testURL_NewWindow扩展了Applet,,en,String link_Text =,,en,谷歌,,en,LINK_TEXT,,en,ActionEvent ae,,en,ae.getSource,,en,字符串链接=,,en,万维网。,,en,同,,pt,AppletContext a = getAppletContext,,en,网址url =新网址,,en,链接,,en,a.showDocument,,en,MalformedURLException e,,en,如何使用Applet读取文件,,en,以下代码段演示了如何使用openStream使用Applet读取文件,,en,URL的方法,,en,有不同的方法来读取像缓冲流一样的流,,en,定制缓冲流等,,en(ActionEvent ae){

尝试{

num = Integer.parseInt(input.getText());

sum = sum num;

input.setText(“”);

output.setText(Integer.toString(sum));

lbl.setForeground(Color.blue);

lbl.setText(“Output of the second Text Box : ”

+ output.getText());

}

抓(NumberFormatException e){

lbl.setForeground(Color.red);

lbl.setText(“Invalid Entry!”);

}

}

}

7) How to write to a file using Applet?

一: In the following example java text area has been used to enter the user input. After entering the input it has been written in a file in local file system. The File () constructor has been used to create the file.

进口java.io. *;

进口的软件包java.awt。*;

import java.awt.event.*;

导入javax.swing中。;

import java.applet.Applet;

import java.net.*;

 

public class WriteFile extends Applet{

Button write = new Button(“WriteToFile”);

Label label1 = new Label(“Enter the file name:”);

TextField text = new TextField(20);

Label label2 = new Label(“Write your text:”);

TextArea area = new TextArea(10,20);

public void init(){

加(label1);

label1.setBackground(Color.lightGray);

加(text);

加(label2);

label2.setBackground(Color.lightGray);

加(area);

加(write,BorderLayout.CENTER);

write.addActionListener(new ActionListener (){

public void actionPerformed,,en,ActionEvent e,,en,sum = i,,en,txtArea.setText,,en,txtArea.append,,en,按钮源=,,en,e.getSource,,en,source.getLabel,,en,和,,en,和,,en,Sub = i,,en,Sub = j,,en,子,,en,如何使用Applet在新窗口中打开链接,,en,此示例演示如何使用showDocument在新窗口中从applet打开特定网页,,en,第二个参数的方法为,,en,import java.net。*,,en,public class testURL_NewWindow扩展了Applet,,en,String link_Text =,,en,谷歌,,en,LINK_TEXT,,en,ActionEvent ae,,en,ae.getSource,,en,字符串链接=,,en,万维网。,,en,同,,pt,AppletContext a = getAppletContext,,en,网址url =新网址,,en,链接,,en,a.showDocument,,en,MalformedURLException e,,en,如何使用Applet读取文件,,en,以下代码段演示了如何使用openStream使用Applet读取文件,,en,URL的方法,,en,有不同的方法来读取像缓冲流一样的流,,en,定制缓冲流等,,en(ActionEvent e){

新的WriteText,,en,公共类WriteText,,en,WRITETEXT,,en,String str = text.getText,,en,str.equals,,en,JOptionPane.showMessageDialog,,en,请输入文件名,,en,text.requestFocus,,en,文件f =新文件,,en,f.exists,,en,BufferedWriter out = new,,en,但是BufferedWriter,,en,area.getText,,en,请输入你的文字,,en,area.requestFocus,,en,f.canWrite,,cy,文字写在,,en,text.setText,,en,area.setText,,en,文字没有写入,,en,文件未找到,,en,例外x,,en,x.printStackTrace,,en,如何打印n个数字的总和,,en,下面的示例演示了如何使用堆栈的概念添加前n个自然数,,en,这里静态Stack类用于保存数字,,en,自定义stackAddition,,en,method用于将数字添加到堆栈中,,en,公共类AdditionStack,,en,static int num,,en,static int ans,,en,static Stack theStack,,en,num =,,pt,堆栈除了,,sv,总和=,,en,岁月,,fr,public static void stackAddition,,en,ans =,,fr();

}

}

);

}

public class WriteText {

WriteText(){

尝试 {

String str = text.getText();

如果(str.equals(“”)){

JOptionPane.showMessageDialog(零,

“Please enter the file name!”);

text.requestFocus();

}

其他{

File f = new File(海峡);

如果(f.exists()){

BufferedWriter out = new

BufferedWriter(新的FileWriter中(f,真));

如果(area.getText().等于(“”)){

JOptionPane.showMessageDialog

(零,”Please enter your text!”);

area.requestFocus();

}

其他{

out.write(area.getText());

如果(f.canWrite()){

JOptionPane.showMessageDialog(零,

“Text is written in “+海峡);

text.setText(“”);

area.setText(“”);

text.requestFocus();

}

其他{

JOptionPane.showMessageDialog(零,

“Text isn’t written in “+海峡);

}

out.close();

}

}

其他{

JOptionPane.showMessageDialog

(零,”File not found!”);

text.setText(“”);

text.requestFocus();

}

}

}

抓(Exception x){

x.printStackTrace();

}

}

}

}








8) How to print summation of n numbers?

一: Following example demonstrates how to add first n natural numbers by using the concept of stack. Here the static Stack class is used to hold the numbers. The custom stackAddition () method is used to add the numbers into the stack.

进口java.io.IOException异常;

public class AdditionStack {

static int num;

static int ans;

static Stack theStack;

公共静态无效的主要(串[] 参数) 抛出IOException异常 {

num = 50;

stackAddition();

System.out.println(“Sum=” + ans);

}

public static void stackAddition() {

theStack = new Stack(10000);

ans = 0;

而 (NUM > 0)

{

theStack.push(NUM);

–NUM;

}

而 (!theStack.isEmpty())

{

int newN = theStack.pop,,el,ans = newN,,el,私人int,,en,int s,,en,maxSize = s,,en,int p,,en,= p,,en,public int pop,,en,返回数据,,en,public int peek,,en,总和= 1225,,en,如何获取链表的第一个和最后一个元素,,en,以下示例显示了如何在linkedlistname.getFirst的帮助下获取链表的第一个和最后一个元素,,en,和linkedlistname.getLast,,en,LinkedList类,,en,所有堆栈/队列/双端队列操作都可以根据标准列表操作轻松重铸,,en,这里包括它们主要是为了方便起见,,en,虽然它们可能比同等的List操作运行得稍快,,en();

ans = newN;

}

}

}

class Stack {

private int maxSize;

private int[] data;

private int top;

public Stack(int s) {

maxSize = s;

data = new int[maxSize];

top = -1;

}

public void push(int p) {

data[++top] = p;

}

public int pop() {

return data[top–];

}

public int peek() {

return data[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

The above code sample will produce the following result.

Sum=1225

9) How to get the first and the last element of a linked list?

一: Following example shows how to get the first and last element of a linked list with the help of linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class. All of the stack/queue/deque operations could be easily recast in terms of the standard list operations. They’re included here primarily for convenience, though they may run slightly faster than the equivalent List operations.

import java.util.LinkedList;

公共类主 {

公共静态无效的主要(串[] 参数) {

LinkedList lList = new LinkedList,,en,lList.add,,en,LinkedList的第一个元素是,,en,lList.getFirst,,en,LinkedList的最后一个元素是,,en,lList.getLast,,en,如何在链表的第一个和最后一个位置添加元素,,en,以下示例显示如何使用addFirst在链接列表的第一个和最后一个位置添加元素,,en,和addLast,,en,Linked List类的方法,,en,清单,,ca,lList.addFirst,,en,lList.addLast,,en();

lList.add(“100”);

lList.add(“200”);

lList.add(“300”);

lList.add(“400”);

lList.add(“500”);

System.out.println(“First element of LinkedList is :

” + lList.getFirst());

System.out.println(“Last element of LinkedList is :

” + lList.getLast());

}

}

The above code sample will produce the following result.

First element of LinkedList is: 100

Last element of LinkedList is: 500

10) How to add an element at first and last position of a linked list?

一: Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.

import java.util.LinkedList;

公共类主 {

公共静态无效的主要(串[] 参数) {

LinkedList lList = new LinkedList,,en,lList.add,,en,LinkedList的第一个元素是,,en,lList.getFirst,,en,LinkedList的最后一个元素是,,en,lList.getLast,,en,如何在链表的第一个和最后一个位置添加元素,,en,以下示例显示如何使用addFirst在链接列表的第一个和最后一个位置添加元素,,en,和addLast,,en,Linked List类的方法,,en,清单,,ca,lList.addFirst,,en,lList.addLast,,en();

lList.add(“1”);

lList.add(“2”);

lList.add(“3”);

lList.add(“4”);

lList.add(“5”);

System.out.println(lList);

lList.addFirst(“0”);

System.out.println(lList);

lList.addLast(“6”);

System.out.println(lList);

}

}

The above code sample will produce the following result.

1, 2, 3, 4, 5

0, 1, 2, 3, 4, 5

0, 1, 2, 3, 4, 5, 6







 

Tagged on: ,
============================================= ============================================== 在亚马逊上购买最佳技术书籍,en,电工CT Chestnutelectric,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share