题目: 在一个文本框中输入网址,然后点击确定按钮读取服务器上的资源,由于网络速度或其它的因素,URL资源的读取可能会引起堵塞,因此,程序需要在一个线程中读取URL资源,以免堵塞主线程。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class Win extends JFrame
implements ActionListener,Runnable
{
JButton button;
URL url;
JTextField text;
JTextArea area;
byte b[]=new byte[118];
Thread thread;
public Win()
{
text=new JTextField(20);
area=new JTextArea(12,12);
button=new JButton("确定");
button.addActionListener(this);
thread=new Thread(this);
JPanel p=new JPanel();
p.add(new JLabel("输入网址:"));
p.add(text);
p.add(button);
Container con=getContentPane();
con.add(new JScrollPane(area),BorderLayout.CENTER);
con.add(p,BorderLayout.NORTH);
setBounds(60,60,360,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
thread=new Thread(this);
try{
thread.start();
}
catch(Exception ee)
{
text.setText("我正在读取"+url);
}
}
public void run()
{
try {
int n=-1;
area.setText(null);
url=new URL(text.getText().trim());
InputStream in=url.openStream();
while((n=in.read(b))!=-1)
{
String s=new String(b,0,n);
area.append(s);
}
}
catch(MalformedURLException e1)
{
text.setText(""+e1);
return;
}
catch(IOException e1)
{
text.setText(""+e1);
return;
}
}
}
public class Example
{
public static void main(String args[])
{
new Win();
}
}
分享到:
相关推荐
Java每日一题20160906,每日一道Java编程题,提高自己
NULL 博文链接:https://duyiwuer.iteye.com/blog/362849
NULL 博文链接:https://duyiwuer.iteye.com/blog/353541
NULL 博文链接:https://jythoner.iteye.com/blog/344407
java每日一练练习题
NULL 博文链接:https://duyiwuer.iteye.com/blog/351913
Java方向每日一题day17_11月24日编程题答案1
Java方向每日一题day18_11月25日编程题答案1
java面试题,参考面试使用,与什么不懂的不用联系我,我随便传的东西,不传不让下载,真烦
比特科技制作[编程题]44581-寻找第K大链接:https://www.nowcoder.com/questionTerminal/e016ad9b7f0b4
1. 执行如下程序,输出结果是( ) 3. 下列选项中属于面向对象设计方法主要特征的是( ) 6. 在基本 JAVA 类型中,如果不明确指定,整数型的默认是 _
整理互联网常见面试题,为春招、校招和社招做准备。如若不能下载,关注公众号“每日技术分享”,可免费下载资源。
干货资源推荐: JVM干货调试视频教程分享 50份优秀Java求职者简历 SpringCloud前后端分离实战项目...本资源整理自互联网,仅供学习交流使用,请勿商用,坚持每日分享一套Java学习资源干货,一起提高,一起进步!!!
leetcode-java:每日一题leetcode-java版
9. 以下关于java封装的描述中,正确的是: 1. 标题:DNA序列 | 时间限制:1秒 | 内存限制:32768K 2. 标题:百万富翁问题 | 时间限制:
1. 以下哪项是类实例化的语句 6. 变量a是一个64位有符号的整数,初始值用16进制表示为:0Xf000000000000000 7. HashSet子类依靠
一些考试的java习题,一些试卷,考生可能用处大点
leetcode 答案 leetcode-java 每日更新一题,Java编写的LeetCode算法题目答案。
Leetcode每日LeetCode每日一题Java实现
推出了每日一题活动。借此打卡! ID Difficulty Solution Series Finish Time Java C C++ Address 1 ☆ 2019-02-29 ✓ 225 ☆ 每日一题 2020-03-01 ✓ 206 ☆ 每日一题 2020-03-02 ✓ 面试题 ☆ 每日一题 2020-03-03...