您的位置:首页 > 产品设计 > UI/UE

GUI线程

2015-12-16 11:07 363 查看
界面编程我又新学一种方式:一个类可以对多个接口实现,并且继承另外一个类,这样都写在一个类里可以减少类之间调用的错误,而且直接调用更方便

书上一个字母游戏的例子让我印象深刻

包括其中用标签作输出,我特地查了一些他的构造函数和一些用法:

1、JLabel常用的一些构造函数

JLabel()

创建无图像并且其标题为空字符串的 JLabel。

JLabel(Icon image)

创建具有指定图像的 JLabel 实例。

JLabel(Icon image, int horizontalAlignment)

创建具有指定图像和水平对齐方式的 JLabel 实例。

JLabel(String text)

创建具有指定文本的 JLabel 实例。

JLabel(String text, Icon icon, int horizontalAlignment)

创建具有指定文本、图像和水平对齐方式的 JLabel 实例。

JLabel(String text, int horizontalAlignment)

创建具有指定文本和水平对齐方式的 JLabel 实例。

2、方法(也是可以显示图标的哦)

String getText()

返回该标签所显示的文本字符串。

void setText(String text)

定义此组件将要显示的单行文本。

Icon getIcon()

返回该标签显示的图形图像(字形、图标)。

void setIcon(Icon icon)

定义此组件将要显示的图标。

public class Example12_10 {
public static void main(String args[]) {
WindowTyped win=new WindowTyped();
win.setTitle("打字母游戏");
win.setSleepTime(3000);
}
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WindowTyped extends JFrame implements ActionListener,Runnable {
JTextField inputLetter;
Thread giveLetter;       //负责给出字母
JLabel showLetter,showScore;
int sleepTime,score;
Color c;
WindowTyped() {
setLayout(new FlowLayout());
giveLetter=new Thread(this);
inputLetter=new JTextField(6);
showLetter =new JLabel(" ",JLabel.CENTER);
showScore  = new JLabel("分数:");
showLetter.setFont(new Font("Arial",Font.BOLD,22));
//修改字体格式
add(new JLabel("显示字母:"));
add(showLetter);
add(new JLabel("输入所显示的字母(回车)"));
add(inputLetter);
add(showScore);
inputLetter.addActionListener(this);
setBounds(100,100,400,280);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
giveLetter.start();    //在AWT-Windows线程中启动giveLetter线程
}
public void run() {
char c ='a';
while(true) {
showLetter.setText(""+c+" ");
validate();
c = (char)(c+1);
if(c>'z') c = 'a';
try{ Thread.sleep(sleepTime);
}
catch(InterruptedException e){}
}
}
public void setSleepTime(int n){
sleepTime = n;
}
public void actionPerformed(ActionEvent e) {
String s = showLetter.getText().trim();
String letter = inputLetter.getText().trim();
if(s.equals(letter)) {
score++;
showScore.setText("得分"+score);
inputLetter.setText(null);
validate();
giveLetter.interrupt();  //吵醒休眠的线程,以便加快出字母的速度
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: