将窗口分为上下两个区,分别运行两个线程,显示由右向左和由左向右字符串
程序员文章站
2022-03-26 17:09:04
《Java程序设计》里的一道题,将窗口分为上下两个区,分别运行两个线程,一个在上面的区域中显示由右向左游动的字符串,另一个在下面的区域中显示从左向右游动的字符串。import java.awt.*;import java.awt.event.*;import javax.swing.JFrame;import javax.swing.JPanel;import java.awt.GridLayout;public class Several extends JFrame{public Sev...
《Java程序设计》里的一道题,将窗口分为上下两个区,分别运行两个线程,一个在上面的区域中显示由右向左游动的字符串,另一个在下面的区域中显示从左向右游动的字符串。
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class Several extends JFrame{
public Several()
{
setSize(500,500);
setLocation(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,1));
}
public static void main(String[] args) {
Several frame=new Several();
Panel1 first=new Panel1();
Panel2 second=new Panel2();
frame.add(first);
frame.add(second);
frame.setVisible(true);
}
}
class Panel1 extends JPanel implements Runnable{
int x1=0;
public Panel1()
{
Thread t1=new Thread(this);
t1.start();
}
public void run() {
while(true) {
try {
Thread.sleep(30);
}catch(InterruptedException e) {}
x1+=10;
if(x1>300)
x1=0;
repaint();
}
}
public void paint(Graphics g1)
{
super.paint(g1);
g1.drawString("hello,Java!", x1, 20);
}
}
class Panel2 extends JPanel implements Runnable{
int x2=300;
public Panel2()
{
Thread t2=new Thread(this);
t2.start();
}
public void run() {
while(true) {
try {
Thread.sleep(30);
}catch(InterruptedException e) {}
x2-=10;
if(x2<-100)
x2=300;
repaint();
}
}
public void paint(Graphics g2)
{
super.paint(g2);
g2.drawString("hello,Java!", x2, 40);
}
}
难点是这里要使用JJPanel布局,同时要把它作为单独线程运行,所以只能采用Runnable接口比较简单。其它的绘图细节可以参考《Java游戏编程原理和实践教程》一书,书中对Java绘图的讲解比较详细,当然时间较多或者英语水平较好的同学可以下载免费的官方文档来看。
本文地址:https://blog.csdn.net/returnadsss/article/details/109565033