import java.util.*;
import javax.swing.*;public class mainEntry{
public static void main(String[] args){
JFrame jf = new JFrame("Clock");
JLabel clock = new JLabel("Clock");
clock.setHorizontalAlignment(JLabel.CENTER);
jf.add(clock,"Center");
jf.setSize(140,80);
jf.setLocation(500,300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
Thread t=new MyThread(clock);
t.start();
}
}class MyThread extends Thread{
private JLabel clock;
public MyThread(JLabel clock){
this.clock=clock;
}
public void run(){
while(true){
clock.setText(getTime());
try{
Thread.sleep(1000); //this.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public String getTime(){
Calendar c = new GregorianCalendar();
String time = c.get(Calendar.YEAR) + "-" +
(c.get(Calendar.MONTH) + 1) + "-" +
c.get(Calendar.DATE) + " " ;
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
String ph = h<10 ? "0":"";
String pm = m<10 ? "0":"";
String ps = s<10 ? "0":"";
time += ph + h + ":" + pm + m + ":" + ps + s;
return time;
}
}两个类的作用是利用线程显示时间,问题是java 是按值传递的,但是为什么MyThread类中的clock的改变还是会影响的主函数中的clock属性?
import javax.swing.*;public class mainEntry{
public static void main(String[] args){
JFrame jf = new JFrame("Clock");
JLabel clock = new JLabel("Clock");
clock.setHorizontalAlignment(JLabel.CENTER);
jf.add(clock,"Center");
jf.setSize(140,80);
jf.setLocation(500,300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
Thread t=new MyThread(clock);
t.start();
}
}class MyThread extends Thread{
private JLabel clock;
public MyThread(JLabel clock){
this.clock=clock;
}
public void run(){
while(true){
clock.setText(getTime());
try{
Thread.sleep(1000); //this.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public String getTime(){
Calendar c = new GregorianCalendar();
String time = c.get(Calendar.YEAR) + "-" +
(c.get(Calendar.MONTH) + 1) + "-" +
c.get(Calendar.DATE) + " " ;
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
String ph = h<10 ? "0":"";
String pm = m<10 ? "0":"";
String ps = s<10 ? "0":"";
time += ph + h + ":" + pm + m + ":" + ps + s;
return time;
}
}两个类的作用是利用线程显示时间,问题是java 是按值传递的,但是为什么MyThread类中的clock的改变还是会影响的主函数中的clock属性?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货