JAVA学习


好吧,我要学java了,我妥协了,555555555555,加油!!!

描述对象

访问控制类型

java有四种访问控制权限:private,protected,public,default。
在这里插入图片描述

创建类变量(静态变量)

关键字 static

static int number=0

accessor方法

如果在类中将对象变量申明为私有的(private),那么如何访问这些变量呢。我们可以通过方法来进行访问,这些方法被称为accessor方法

public int getSecond(){
      return newSeconds;
}
public void setSecond(int newValue)
{
    if(newValue>60)
    {
         newSeconds=newValue;
    }
}

将一个类放在另一个类中

public class Wrecker
{
   String author="Daniel";
   
   public void infectFile()
   {
      VirusCode vic=new VirusCode(1024);
   }
   class VirusCode
   {
      int vSize;
	  
	  VirusCode(int size)
	  {
	     vSize=size;
	  }
   }
}

内部类的使用方法与正常情况没有任何差别,主要差别出现在编译之后,内部类没有使用class语句来指定名称,而是由编译器给他们指定名称,其中包含主类名。
例如这个实例,编译器将生成Wreaker.class和Wreaker$VirusCode.class

练习实例

public class Virus {
	static int virusCount=0;
	public Virus()
	{
		virusCount++;
	}
	static int getVirusCount()
	{
		return virusCount;
	}
}
import java.util.Scanner;

public class VirusLab {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("请您输入一个数");
		Scanner scanner=new Scanner(System.in);
		int numViruses=scanner.nextInt();
		if(numViruses>0)
		{
			Virus[] viriiVirus=new Virus[numViruses];
			for(int i=0;i<numViruses;i++)
			{
				viriiVirus[i]=new Virus();
			}
			System.out.println("There are "+Virus.getVirusCount()+" viruses");
		}
		scanner.close();
	}

}

重复利用现有对象

将相同类型的对象存储到Vector中

Vector是一种存储相同类对象的数据结构,其长度可以动态的增减
Vector位于java.util中,这是Java类库中最有用的一个包
Vector存储的对象要么属于同一类,要么有相同的超类

  • 创建Vector对象
Vector<String> victor=new Vector<String>();
  • 将对象加入到Vector中
victor.add("Daniel");
  • 从Vector中检索元素
String name=victor.get(1);
  • 查看Vector中是否包含某对象
if(victor.contains("Daniel"))
{
   System.out.println("Daniel found");
}
  • Vector新增的一种for循环,下面实例演示了遍历Vector的victor对象,并将其中的每个对象的名字显示到屏幕上
for(String name:victor)
{
   System.out.println(name);
}

使用this和super关键字

Point是java中表示二维点的标准类,有move(将其移动到某一点)和translate(将对象沿x和y移动特定的距离)方法,我们现在将这个类扩展到三维空间中。

import java.awt.*;
public class Point3D extends Point
{
	public int z;
	
	public Point3D(int x,int y,int z)
	{
		super(x,y);   //调用父类的构造方法,存储x和y坐标
		
		this.z=z;
	}
	
	public void move(int x,int y,int z) 
	{
		this.z=z;
		super.move(x, y);  //调用父类的move方法
 	}
	
	public void translate(int x,int y,int z) 
	{
		this.z+=z;
		super.translate(x, y); //调用父类的x,y方法
	}
}

创建简单的用户界面

Swing和抽象窗口工具包

在java中使用两组类来开发程序的用户界面:Swing和抽象窗口工具包(Abstract Windowing Toolkit),这些类让你能够创建图形用户界面以及接收用户输入
Swing可以提供以下GUI元素:

  • 按钮,复选框,标签,和其他简单组件
  • 文本框,滑块,和其他复杂组件
  • 下拉菜单和弹出菜单
  • 窗口,框架,对话框,和applet窗口
    组织图形用户界面时,需要使用两类对象:组件和容器,组件是用户中的独立的元素,如按钮和滑块;容器是用于容纳其他组件的组件。

在应用程序中,该组件通常是窗口(JWindow)或框架(JFrame)。

导入Swing包

import javax.swing.*

创建一个框架

框架

创建框架时,必须在框架的构造函数中执行几种操作:

  • 调用超类JFrame的构造函数
  • 设置框架的标题
  • 设置框架的大小
  • 设置框架的外观
  • 定义用户关闭框架时应执行的操作
import javax.swing.*;
public class Saluton extends JFrame {
	public Saluton()
	{
		//调用JFrame的构造函数,并传入标题
		//标题设置还可以用 setTitle("Saulton mondo!")来设置
		super("Saulton mondo!"); 
		setLookAndFeel();
		//指定框架的大小,设置框架大小另一种方法是pack()
		//pack()根据框架每个组件的首选尺寸来设置框架。
		setSize(350, 1000);
		//JFrame 有4个枚举类型
		//EXIT_ON_CLOSE 按钮被单击时退出程序
		//DISPOSE_ON_CLOSE 关闭框架并销毁框架对象,但应用程序继续运行
		//DO_NOTHING_ON_CLOSE 让框架打开并继续运行
		//HIDE_ON_CLOSE 关闭框架并继续运行
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	private void setLookAndFeel() 
	{
		try 
		{
			//JAVA7引入了增强外观,名为Nimbus
			//通过调用Swing包中的UIManager类的setLookAndFeel()
			//方法可以设置外观,该方法接收一个参数:外观类的完整名称
			UIManager.setLookAndFeel(
					"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	public static void main(String[] arguments)
	{
		Saluton saluton=new Saluton();
	}
}

效果
在这里插入图片描述

各种组件集合
import javax.swing.*;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;

import java.awt.*;
public class Playback extends JFrame
{
	public Playback()
	{
		super("PlayBack");
		setLookAndFeel();
		setSize(800, 800);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//在容器中添加组件,不需要明确组件在容器的位置,
		//一切交给布局管理器来决定
		//最简单的布局管理器是FlowLayout类
		FlowLayout flo=new FlowLayout();
		setLayout(flo);
		
		
		//按钮
		JButton play=new JButton("Play");
		JButton stop=new JButton("Stop");
		JButton pause=new JButton("Pause");
		
		//标签和文本框
		//RIGHT将文本与标签右对齐
		JLabel pageLabel=new JLabel("Web Page address",JLabel.RIGHT);
		JLabel pageLabel2=new JLabel("US page address",JLabel.RIGHT);
		//指定文本框的宽度为20个字符
		JTextField pageAddressField=new JTextField(20);
		//设置文本框的文本
		pageAddressField.setText("Daniel is handsome boy");
		//指定文本框的宽度为20个字符,且内容默认为"US"
		JTextField pageAddressField2=new JTextField("US",20);
		//获取文本框的文本
		String str=pageAddressField.getText();
		pageAddressField2.setText(str);
		
		//复选框
		JCheckBox jumBox=new JCheckBox("JumBox Size");
		//JCheckBox 可以单独显示,也可以编成组。在一组复选框中不能够
		//同时选中多个,要是JCheckBox对象称为某个组的一部分,必须
		//创建一个ButtonGroup对象
		JCheckBox frogBox=new JCheckBox("Frog",true);
		JCheckBox fishBox=new JCheckBox("Fish",true);
		JCheckBox emuBox=new JCheckBox("emu",true);
		ButtonGroup mealsButtonGroup=new ButtonGroup();
		mealsButtonGroup.add(frogBox);
		mealsButtonGroup.add(fishBox);
		mealsButtonGroup.add(emuBox);
		
		//组合框
		JComboBox profession=new JComboBox();
		profession.addItem("Daniel");
		profession.addItem("Lucas");
		profession.addItem("Jack");
		//要让JComboBox组件能够接收文本输入,必须使用true
		//作为参数调用其setEditable()方法
		profession.setEditable(true);
		
		//文本区域
		//允许输入多行文本
		JTextArea comments=new JTextArea(8,40);//高度为8行,宽度大约40个字符
		//可以在构造函数中指定要在文本区域显示的字符串,可以使用
		//"\n"换行
		JTextArea comArea=new JTextArea("Daniel\nJack",8,40);
		
		//JPanel
		JPanel topRow=new JPanel();
		
		//自定义组件
		ClockPanel timeClockPanel=new ClockPanel();
		
		//调用add方法将组件添加到容器中
		add(play);
		add(stop);
		add(pause);
		add(pageLabel);
		add(pageLabel2);
		add(pageAddressField);
		add(pageAddressField2);
		add(jumBox);
		add(frogBox);
		add(fishBox);
		add(emuBox);
		add(profession);
		add(comments);
		add(comArea);
		add(topRow);
		add(timeClockPanel);
		setVisible(true);		
	}
	private void setLookAndFeel() 
	{
		try 
		{
			UIManager.setLookAndFeel(
					"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (Exception e) {
			// TODO: handle exception
			
		}
	}
	public static void main(String[] arg)
	{
		Playback pbPlayback=new Playback();
	}
}


import javax.swing.*;
import java.awt.*;
import java.util.*;
public class ClockPanel extends JPanel
{
	public ClockPanel()
	{
		super();
		String currentTime=getTime();
		JLabel time=new JLabel("Time: ");
		JLabel current=new JLabel(currentTime);
		add(time);
		add(current);
	}
	final String getTime()
	{
		String time;
		
		Calendar now=Calendar.getInstance();
		int hour=now.get(Calendar.HOUR_OF_DAY);
		int minute=now.get(Calendar.MINUTE);
		int month=now.get(Calendar.MONTH)+1;
		int day=now.get(Calendar.DAY_OF_MONTH);
		int year=now.get(Calendar.YEAR);
		String monthName="";
		switch (month) 
		{
		case(1):
			monthName="January";
		break;
		case(2):
			monthName="February";
		break;
		case(3):
			monthName="March";
		break;
		case(4):
			monthName="April";
		break;
		case(5):
			monthName="May";
		break;
		case(6):
			monthName="June";
		break;
		case(7):
			monthName="July";
		break;
		case(8):
			monthName="August";
		break;
		case(9):
			monthName="September";
		break;
		case(10):
			monthName="October";
		break;
		case(11):
			monthName="November";
		break;
		case(12):
			monthName="December";
		break;
		}
		time=monthName+" "+day+" ,"+year+" "+hour+":"+minute;
		return time;
	}
}

效果如下:
在这里插入图片描述

用户界面的布局

前面的FlowLayout排列组件,是从左到右排列,当前行没有空间后进行下一行。这一节我们介绍更加灵活美观的界面布局。

GridLayout管理器

当组件加入到容器时,是从左到右依次添加的,当这一行满了之后,从下一行左边开始。

	GridLayout gridLayout=new GridLayout(2,3);
	setLayout(grid);

在这里插入图片描述

BorderLayout管理器

BorderLayout管理器会将周围放置4个边界组件,在中间放置一个中间组件

BorderLayout crisisLayout=new BorderLayout();
setLayout(crisisLayout);
add(panicButton,BorderLayout.NORTH);
add(dontPanicButton,BorderLayout.SOUTH);
add(blameButton,BorderLayout.EAST);
add(mediaButtton,BorderLayout.WEST);
add(saveButton,BorderLayout.CENTER);

在这里插入图片描述

BoxLayout管理器

使用该布局的时候,先创建一个放置组件的面板,然后再创建一个布局管理器

JPanel pane=new JPanel();
BoxLayout box=new BoxLayout(pane,BoxLayout.Y_AXIS);
pane.setLayout(box);
pane.add(panicButton);
pane.add(dontPanicButton);
pane.add(blameButton);
pane.add(mediaButtton);
pane.add(saveButton);
add(pane);

BoxLayout.Y_AXIS 表示竖直排列
BoxLayout.X_AXIS 表示水平排列

使用Insets将组件隔开

Insets around=new Insets(10,6,10,3);

around 对象代表容器的边界,上边缘内10像素,左边缘内6像素,下边缘内10像素,右边缘内3像素。

应用程序的界面布局

要想在一个框架内使用不同的布局管理器,解决办法是,将一组JPanel对象作为容器,用于放置图形用户界面的不同部分,对于其中每部分,可以使用JPanel对象的setLayout方法设置不同的布局规则。

import java.awt.*;
import javax.swing.*;
public class LottoMadness extends JFrame
{
	//set up row1
	JPanel row1=new JPanel();
	ButtonGroup option=new ButtonGroup();
	JCheckBox quickpick=new JCheckBox("Quick Pick",false);
	JCheckBox personal1=new JCheckBox("Personal",true);
	
	//set up row2
	JPanel row2=new JPanel();
	JLabel numbersLabel=new JLabel("Your picks: ",JLabel.RIGHT);
	JTextField[] numbers=new JTextField[6];
	JLabel winnersLabel=new JLabel("Winners",JLabel.RIGHT);
	JTextField[] winners=new JTextField[6];
	
	//set up row3
	JPanel row3=new JPanel();
	JButton stop=new JButton("Stop");
	JButton play=new JButton("play");
	JButton reset=new JButton("Reset");
	
	//set up row4
	JPanel row4=new JPanel();
	JLabel got3Label=new JLabel("3 of 6: ",JLabel.RIGHT);
	JTextField got3=new JTextField("0");
	JLabel got4Label=new JLabel("4 of 6: ",JLabel.RIGHT);
	JTextField got4=new JTextField("0");
	JLabel got5Label=new JLabel("5 of 6: ",JLabel.RIGHT);
	JTextField got5=new JTextField("0");
	JLabel got6Label=new JLabel("5 of 6: ",JLabel.RIGHT);
	JTextField got6=new JTextField("0",10);
	JLabel drawingJLabel=new JLabel("Drawing: ",JLabel.RIGHT);
	JTextField drawing=new JTextField("0");
	JLabel yearsJLabel=new JLabel("Years: ",JLabel.RIGHT);
	JTextField yearsField=new JTextField();
	
	public LottoMadness()
	{
		super("Lotto Madness");
		setLookAndFeel();
		setSize(550, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		GridLayout layout=new GridLayout(5,1,10,10);
		setLayout(layout);
		
		FlowLayout layout1=new FlowLayout(FlowLayout.CENTER,10,10);
		option.add(quickpick);
		option.add(personal1);
		row1.setLayout(layout1);
		row1.add(quickpick);
		row1.add(personal1);
		add(row1);
		
		GridLayout layout2=new GridLayout(2,7,10,10);
		row2.setLayout(layout2);
		row2.add(numbersLabel);
		for(int i=0;i<6;i++)
		{
			numbers[i]=new JTextField();
			row2.add(numbers[i]);
		}
		row2.add(winnersLabel);
		for(int i=0;i<6;i++)
		{
			winners[i]=new JTextField();
			winners[i].setEditable(false);
			row2.add(winners[i]);
		}
		add(row2);
		
		FlowLayout layout3=new FlowLayout(FlowLayout.CENTER,10,10);
		row3.setLayout(layout3);
		stop.setEnabled(false);
		row3.add(stop);
		row3.add(play);
		row3.add(reset);
		add(row3);
		
		GridLayout layout4=new GridLayout(2,3,20,10);
		row4.setLayout(layout4);
		row4.add(got3Label);
		got3.setEditable(false);
		row4.add(got3);
		row4.add(got4Label);
		got4.setEditable(false);
		row4.add(got4);
		row4.add(got5Label);
		got5.setEditable(false);
		row4.add(got5);
		row4.add(got6Label);
		got6.setEditable(false);
		row4.add(got6);
		row4.add(drawingJLabel);
		drawing.setEditable(false);
		row4.add(drawing);
		row4.add(yearsJLabel);
		yearsField.setEditable(false);
		row4.add(yearsField);
		add(row4);
		
		setVisible(true);
	}
	private void setLookAndFeel() 
	{
		try 
		{
			UIManager.setLookAndFeel(
					"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (Exception e) {
			// TODO: handle exception
			
		}
	}
	public static void main(String[] arg)
	{
		LottoMadness lottoMadness=new LottoMadness();
	}
	
}

效果如下:

在这里插入图片描述

响应用户的输入

创建一个LottoEvent类用于响应用户输入

import javax.swing.*;
import java.awt.event.*;
 
public class LottoEvent implements ItemListener, ActionListener, Runnable {
    LottoMadness gui;  //why no import LottoMadness;
    Thread playing;
 
    public LottoEvent(LottoMadness in){
        gui = in;
    }
 
    public void actionPerformed(ActionEvent event){
        String command = event.getActionCommand();
        if(command == "play"){
            startPlaying();
        }
        if(command == "stop"){
            stopPlaying();
        }
        if(command == "reset"){
            clearAllField();
        }
    }
 
    void startPlaying(){
        playing = new Thread(this);
        playing.start();
        gui.play.setEnabled(false);
        gui.stop.setEnabled(true);
        gui.reset.setEnabled(false);
        gui.quickpick.setEnabled(false);
        gui.personal.setEnabled(false);
 
    }
 
    void stopPlaying() {
        gui.stop.setEnabled(false);
        gui.play.setEnabled(true);
        gui.reset.setEnabled(true);
        gui.quickpick.setEnabled(true);
        gui.personal.setEnabled(true);
        playing = null;
    }
 
    void clearAllField() {
        for (int i = 0; i<6; i++){
            gui.numbers[i].setText(null);
            gui.winners[i].setText(null);
 
        }
        gui.got3.setText("0");
        gui.got4.setText("0");
        gui.got5.setText("0");
        gui.got6.setText("0");
        gui.drawings.setText("0");
        gui.years.setText("0");
    }
 
    public void itemStateChanged(ItemEvent event) {
        Object item = event.getItem();
        if(item ==gui.quickpick){
            for(int i=0; i<6; i++){
                int pick;
                do{
                    pick = (int)Math.floor(Math.random()*50 + 1);
                }while(numberGone(pick,gui.numbers,i)); //To guarantee the numbers are different;
                gui.numbers[i].setText(""+ pick);
            }
        }else{
            for(int i = 0; i<6; i++){
                gui.numbers[i].setText(null);  //the differences between "" and null here;
            }
        }
    }
 
    void addOneToField(JTextField field){
        int num = Integer.parseInt("0"+field.getText());
        num++;
        field.setText(""+num);
 
    }
 
    boolean numberGone(int num, JTextField[] pastNums, int count){
        for(int i=0; i<count; i++){
            if(Integer.parseInt(pastNums[i].getText() )== num){
                return true;
            }
 
        }
        return false;
    }
 
    boolean matchedOne(JTextField win, JTextField[] allPicks){
        for(int i=0; i<6; i++){
            String winText = win.getText();
            if (winText.equals(allPicks[i].getText())){
                return true;
            }
        }
        return false;
    }
 
    public void run() {
        Thread thisThread = Thread.currentThread();  //why not new thread?
        while(playing == thisThread){
            addOneToField(gui.drawings);
            int draw = Integer.parseInt(gui.drawings.getText());
            float numYears = (float)draw/52;  //once a week;
            gui.years.setText(""+numYears);
 
            int matches = 0;
            for(int i= 0; i<6; i++){
                int ball;
                do{
                    ball = (int)Math.floor(Math.random()*50 +1 );
                }while(numberGone(ball, gui.winners, i));
                gui.winners[i].setText(""+ball);  //why "". to change an Integer to string;
                if(matchedOne(gui.winners[i], gui.numbers)){
                    matches++;
                }
 
            }
 
            switch(matches) {
                case 3:
                    addOneToField(gui.got3);
                    break;
                case 4:
                    addOneToField(gui.got4);
                    break;
                case 5:
                    addOneToField(gui.got5);
                case 6:
                    addOneToField(gui.got6);
                    gui.stop.setEnabled(false);
                    gui.play.setEnabled(true);
                    playing = null;
 
            }
            try {
                Thread.sleep(100);
            }catch(InterruptedException e){
 
            }
        }
 
    }
}

LottoMadness修改成以下代码

import java.awt.*;
import javax.swing.*;
 
public class LottoMadness extends JFrame {
    LottoEvent lotto  = new LottoEvent(this);
 
    JPanel row1 = new JPanel();
    ButtonGroup option = new ButtonGroup();
    JCheckBox quickpick = new JCheckBox("quickpick",false);
    JCheckBox personal = new JCheckBox("personal",true);
 
    JPanel row2 = new JPanel();
    JLabel numbersLabel = new JLabel("Your picks : ", JLabel.RIGHT);
    JTextField[] numbers = new JTextField[6];
    JLabel winnersLabel = new JLabel("winners: " , JLabel.RIGHT);
    JTextField[] winners = new JTextField[6];
 
    JPanel row3 = new JPanel();
    JButton stop = new JButton("stop");
    JButton play = new JButton("play");
    JButton reset = new JButton("reset");
 
    JPanel row4 = new JPanel();
    JLabel got3Label = new JLabel("3 of 6 :",JLabel.RIGHT);
    JTextField got3 = new JTextField("0");
    JLabel got4Label = new JLabel("4 of 6 :",JLabel.RIGHT);
    JTextField got4 = new JTextField("0");
    JLabel got5Label = new JLabel("5 of 6 :",JLabel.RIGHT);
    JTextField got5 = new JTextField("0");
    JLabel got6Label = new JLabel("6 of 6 :",JLabel.RIGHT);
    JTextField got6 = new JTextField("0");
    JLabel drawingsLabel = new JLabel("drawings :",JLabel.RIGHT);
    JTextField drawings = new JTextField("0");
    JLabel yearsLabel = new JLabel("years :",JLabel.RIGHT);
    JTextField years = new JTextField("0");
 
    public LottoMadness(){
        super("Lotto Madness");
        setSize(550, 260);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridLayout layout = new GridLayout(5,1,10,10);
        setLayout(layout);
 
        quickpick.addItemListener(lotto);
        personal.addItemListener(lotto);
        stop.addActionListener(lotto);
        play.addActionListener(lotto);
        reset.addActionListener(lotto);
 
        FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
        option.add(quickpick);
        option.add(personal);
        row1.setLayout(layout1);
        row1.add(quickpick);
        row1.add(personal);
        add(row1);
 
        GridLayout layout2 = new GridLayout(2, 7 ,10, 10);
        row2.setLayout(layout2);
        row2.add(numbersLabel);
        for (int i =0 ;i<6; i++){
            numbers[i] = new JTextField();
            row2.add(numbers[i]);
        }
        row2.add(winnersLabel);
        for (int i=0; i<6; i++){
            winners[i]=new JTextField();
            winners[i].setEnabled(false);
            row2.add(winners[i]);
        }
        add(row2);
 
        FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER, 10, 10);
        row3.setLayout(layout3);
        stop.setEnabled(false);
        row3.add(stop);
        row3.add(play);
        row3.add(reset);
        add(row3);
 
        GridLayout layout4 = new GridLayout(2, 3, 20, 10);
        row4.setLayout(layout4);
        row4.add(got3Label);
        got3.setEditable(false);
        row4.add(got3);
        row4.add(got4Label);
        got4.setEditable(false);
        row4.add(got4);
        row4.add(got5Label);
        got5.setEditable(false);
        row4.add(got5);
        row4.add(got6Label);
        got6.setEditable(false);
        row4.add(got6);
        row4.add(drawingsLabel);
        drawings.setEditable(false);
        row4.add(drawings);
        row4.add(yearsLabel);
        years.setEditable(false);
        row4.add(years);
        add(row4);
 
        setVisible(true);
 
    }
 
    public static void main (String[] arguments){
        LottoMadness frame = new LottoMadness();
    }
 
}

创建复杂的用户界面

滚动窗格(JScrollPane)

JTextArea messArea=new JTextArea(4,22);
		messArea.setLineWrap(true);
		messArea.setWrapStyleWord(true);
		JScrollPane scrollPane=new JScrollPane(messArea,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		row3.add(scrollPane);

滑块(JSlider)

创建一个根据RGB数值改变颜色的程序

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
public class ColorsSliders extends JFrame implements ChangeListener {
	
	ColorPanel canvas;
	JSlider red;
	JSlider green;
	JSlider blue;
	
	public ColorsSliders()
	{
		super("Color Slider");
		setLookAndFeel();
		setSize(270,300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		
		canvas=new ColorPanel();
		red=new JSlider(0,255,255);  //创建具有指定最小值,最大值和初始值的滑块
		green=new JSlider(0,255,0);
		blue=new JSlider(0,255,0);
		
		red.setMajorTickSpacing(50);
		red.setMinorTickSpacing(10);
		red.setPaintTicks(true);
		red.setPaintLabels(true);
		red.addChangeListener(this);
		
		green.setMajorTickSpacing(50);
		green.setMinorTickSpacing(10);
		green.setPaintTicks(true);
		green.setPaintLabels(true);
		green.addChangeListener(this);
		
		blue.setMajorTickSpacing(50);
		blue.setMinorTickSpacing(10);
		blue.setPaintTicks(true);
		blue.setPaintLabels(true);
		blue.addChangeListener(this);
		
		JLabel redLabel=new JLabel("Red: ");
		JLabel greenLabel=new JLabel("Green: ");
		JLabel blueLabel=new JLabel("blue: ");
		GridLayout gridLayout=new GridLayout(4,1);
		FlowLayout right=new FlowLayout(FlowLayout.RIGHT);
		setLayout(gridLayout);
		
		JPanel redPanel=new JPanel();
		redPanel.setLayout(right);
		redPanel.add(redLabel);
		redPanel.add(red);
		add(redPanel);
		
		JPanel greenPanel=new JPanel();
		greenPanel.setLayout(right);
		greenPanel.add(greenLabel);
		greenPanel.add(green);
		add(greenPanel);
		
		JPanel bluePanel=new JPanel();
		bluePanel.setLayout(right);
		bluePanel.add(blueLabel);
		bluePanel.add(blue);
		add(bluePanel);
		
		add(canvas);
		setVisible(true);
	}
	
	//实现ChangeListener接口的类,
	public void stateChanged(ChangeEvent event) {
		JSlider source=(JSlider)event.getSource();
		if(source.getValueIsAdjusting()!=true)  //判断滑块是否在移动,在移动的化返回true
		{
			Color current=new Color(red.getValue(),
					green.getValue(),
					blue.getValue());
			canvas.changeColor(current);
			canvas.repaint();
		}
	}
	
	public Insets getInsets() {
		Insets border=new Insets(45, 10, 10, 10);
		return border;
	}
	
	private void setLookAndFeel() {
		try {
			UIManager.setLookAndFeel(
					"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (Exception e) {
			// TODO: handle exception
			
		}
	}
	
	public static void main(String[] args) {
		ColorsSliders cs=new ColorsSliders();
	}
	

}
public class ColorPanel extends JPanel{
	
	Color backgroundColor;
	ColorPanel()
	{
		backgroundColor=Color.red;
	}
	
	public void paintComponent(Graphics comp) {
		Graphics2D comp2D=(Graphics2D) comp;
		comp2D.setColor(backgroundColor);
		comp2D.fillRect(0, 0, getSize().width, getSize().height);
		
	}
	
	void changeColor(Color newbackground)
	{
		backgroundColor=newbackground;
	}

}

使用图像图标和工具栏(ImageIcon)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Tool extends JFrame{
	public Tool()
	{
		super("Tool");
		setLookAndFeel();
		setSize(370,200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//build toolbar buttons
		ImageIcon image1=new ImageIcon("D:/eclipse/java_practice/Java24/src/ios7-gear-outline.png");
		image1.setImage(image1.getImage().getScaledInstance(50,50,Image.SCALE_DEFAULT));
		JButton button1=new JButton(image1);
		ImageIcon image2=new ImageIcon("D:/eclipse/java_practice/Java24/src/ios7-glasses-outline.png");
		image2.setImage(image2.getImage().getScaledInstance(50,50,Image.SCALE_DEFAULT));
		JButton button2=new JButton(image2);
		ImageIcon image3=new ImageIcon("D:/eclipse/java_practice/Java24/src/ios7-home-outline.png");
		image3.setImage(image3.getImage().getScaledInstance(50,50,Image.SCALE_DEFAULT));
		JButton button3=new JButton(image3);
		
		//build toolbar
		JToolBar bar=new JToolBar();
		bar.add(button1);
		bar.add(button2);
		bar.add(button3);
		
		//build text area
		JTextArea ediTextArea=new JTextArea(8,40);
		JScrollPane scrollPane=new JScrollPane(ediTextArea);
		
		//create frame
		BorderLayout border=new BorderLayout();
		setLayout(border);
		add("North",bar);
		add("Center",scrollPane);
		setVisible(true);
		
	}
	
	private void setLookAndFeel() {
		try {
			UIManager.setLookAndFeel(
					"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (Exception e) {
			// TODO: handle exception
			
		}
	}
	
	public static void main(String[] args) {
		Tool frameTool=new Tool();
	}
}

创建线程程序

创建线程

有两种方法可将任务放在线程中:

  • 将任务放在实现了Runnable接口的类中
  • 将任务放在Thread类中
使用Runnable

实现Runnable接口

要支持Runnable接口,可在创建类时使用关键字implements

public class LoadStocks implements Runnable {
	//body of the class

}

实现了Runnable接口的类必须包含run()方法 结构如下:

public void run() {
		// TODO Auto-generated method stub
		
	}

run()方法应完成线程要完成的任务,例如在股票分析中,run方法应包含从磁盘加载数据以及根据这些数据 生成统计信息的语句

如何启动线程

当线程应用程序运行时,不会自动执行run方法中的语句,在java中必须做以下两项工作来启动线程:

  • 通过调用构造函数Thread创建线程化类的对象
  • 通过调用start()方法启动线程
    构造函数Thread 接受一个参数———包含线程的run()方法的对象,通常使用this作为参数,this表明当前类包含run方法
Thread runner;
public void start(){
     if(runner==null)
	 {
	    runner=new Thread(this);
		runner.start();
	 }
}

如何运行线程

public void run()
{
   Thread thisThread=Thread.currentThread();
   while(runner==thisThread)
   {
	   //线程要运行的程序
   }
}

如何终止线程
Java不提倡使用线程类的stop()方法 resume()方法 suspend()方法

那么如何停止线程呢,请看以下代码

public void stop()
{
   if(runner!=null)
   {
      runner=null;
   }
}

读写文件

要访问存储在硬盘中的文件和Web服务器中的文档,可以使用java.io包中的类。其中的io表示input/output,这些类用于访问数据源,如硬盘,CD-ROM或计算机内存。

  • 流是一种对象,将信息从一个地方发送到另一个地方。
  • 流可以连接各种数据源,包括计算机程序,硬盘,Internet服务器,计算机内存,和DVD_ROM.
  • 流有两种类型,输入流和输出流

使用的过程:
(1)创建一个与数据相关联的流对象
(2)调用流的方法,将信息加入流中或者从流中取出信息
(3)调用流对象的close()方法关闭流

文件

文件用File类表示,位于java.io包中。

File bookName=new File("data\\address.dat");

创建指定文件路径的文件address.dat

File bookName=new File("address.dat");

创建位于当前文件夹中的address.dat

\字符适用于windows系统 /字符使用于linux系统 要适应任何操作系统可使用File.pathSeparator

File的几个有用的方法

  • exist()
  • getName()
  • length(); //将文件长度作为long值返回
  • createNewFile(); //如果文件不存在,创建它
  • delete(); // 如果文件存在,将其删除
  • renameTo(File); //重命名文件

也可以使用File对象表示系统中的文件夹而不是文件,这需要在构造函数中指定文件夹名:
如绝对路径(C:\MyDocuments\)
相对路径(java\database)
有了表示文件夹的File对象后,可以调用其listFiles()方法来看文件夹的内容。

从流中读取数据

使用FileInputStream类,它代表可通过它从文件中读取字节的输入流。

下面创建一个从MP3音频文件读取ID3数据的应用程序。MP3是一种非常流行的音乐文件格式,因此经常在ID3文件的末尾添加128个字节,用于存储与歌曲相关的信息,如歌名,创作者,以及其所属的唱片。

import java.io.*;
import java.text.FieldPosition;

public class ID3Reader {
	public static void main(String[] arguments) {
		try {
			String filepath="src/Cartoon,Futuristik - C U Again.mp3";
			File song=new File(filepath);
			FileInputStream file=new FileInputStream(song);
			int size=(int)song.length();
			file.skip(size-128);  //调用skip方法来跳过一些字节
			byte[] last128=new byte[128];
			file.read(last128);
			String id3=new String(last128);
			String tag=id3.substring(0,3);
			if(tag.equals("TAG"))
			{
				System.out.println("Title: "+id3.substring(3,32));
				System.out.println("Artist: "+id3.substring(33,62));
				System.out.println("Album: "+id3.substring(63,91));
				System.out.println("Years: "+id3.substring(93,97));
			}
			else {
				System.out.println(filepath+"does not contains ID3 info.");
			}
			file.close();
		}
		catch (Exception e) {
			System.out.println("Error --"+e.toString());
		}
	}

}

缓冲输入流

对于读取输入流的程序,提高其性能的一个方法就是将输入放到缓冲区中,缓冲(buffering)是将数据放到内存中供程序需要时使用的一个过程。

要是有缓冲区,需要创建一个输入流,如FileInputStream对象,然后使用该对象创建缓冲的流,为此,将输入流作为唯一的参数调用BufferedInputStream(InputStream)构造函数,这样,从输入流中读取数据时,数据将被存储到缓冲区中。

接下来的项目(Console类)包含一个类方法,可在任何Java程序中用于接收控制台输入。

import java.io.*;
public class Console {
	public static String readLine() {
		StringBuffer response=new StringBuffer();
		try
		{
			BufferedInputStream bin=new BufferedInputStream(System.in);
			int in=0;
			char inchar;
			do {
				in=bin.read();
				inchar=(char)in;
				if(in!=-1)
				{
					response.append(inchar);
				}
			} while ((in!=-1)&(inchar!='\n'));
			bin.close();
			return response.toString();
		}
		catch (IOException e) {
			System.out.println("Exception: "+e.toString());
			return null;
		}
	}
	
	public static void main(String[] args) {
		String input=Console.readLine();
		System.out.println("I received: "+input);
	}
}

将数据写入流中

在java中,与流相关的类都是成对出现的,对于字节流,有FileInputStream类和FileOutputStream类;对于字符流,有FileReader类和FileWriter类。

可通过两种方式创建FileOutputStream。

  • 第一种,在现有文件中追加字节
FilleOutputStream(FileObject,true);
  • 第二种,写入一个新文件种
FileOutputStream(FileObject);

以下例子通过编写一个简单的应用程序,它通过将字节写入到文件输出流种的方式,将几行文本存储到一个文件种。

import java.io.*;
public class ConfigWriter {
	String newline=System.getProperty("line.separator");  //换行符
	
	ConfigWriter()
	{
		try {
			File file=new File("jianjipan.properties");
			FileOutputStream fileStream=new FileOutputStream(file);
			writer(fileStream, "username=jianjipan");
			writer(fileStream, "score=99999");
			writer(fileStream, "level=10");
		} catch (IOException e) {
			System.out.println("could not write file");
		}
	}
	
	void writer(FileOutputStream stream,String output) throws IOException
	{
		output=output+newline;
		byte[] data=output.getBytes();  //将字符串转换成byte数组
		stream.write(data);  //将数据写入到字节数组中
	}
	
	public static void main(String[] args) {
		ConfigWriter cw=new ConfigWriter();
	}
}

读写配置属性

上述的ConfigWriter应用程序,它将多个文件属性设置写入到一个文件中,而Configurator应用程序将这些属性设置读入到一个java属性文件中,并添加一个名为runtime的新属性,然后保存该文件。
要用到java.util

import java.io.*;
import java.util.*;
public class Configurator {
	Configurator()
	{
		try
		{
			//载入一个名为jianjipan.properties的属性文件
			File configFile=new File("jianjipan.properties");
			FileInputStream inStream=new FileInputStream(configFile);
			Properties config=new Properties();
			config.load(inStream);
			//创建一个新属性
			Date current=new Date();
			config.setProperty("runtime", current.toString());  //设置属性
			//保存属性文件
			FileOutputStream outStream=new FileOutputStream(configFile);
			config.store(outStream, "properties setting");
			inStream.close();
			
			//检索属性
			//检索username的属性值
			String user=config.getProperty("username");
			System.out.println(user);
			//列出所有的属性值
			config.list(System.out);
		}
		catch (IOException e) {
			System.out.println("IO error"+e.toString());
		}
	}
	
	public static void main(String[] args) {
		Configurator con=new Configurator();
	}
}

读写XML数据

本章将使用XML对象模型(XML Object Model,XOM)来读写XML数据,XOM是一个Java类库,在Java程序中使用XOM,可以方便地处理XML数据。

创建XML文件

Java类库中有多个可读写XML的类,其中包括java.util包中的Properties

使用方法如下述代码

import java.io.*;
import java.nio.channels.NonWritableChannelException;
import java.util.*;
public class PropertyFileCreator {
	public PropertyFileCreator()
	{
		Properties properties=new Properties();
		properties.setProperty("username", "jianjipan");
		properties.setProperty("browser", "Google");
		properties.setProperty("showEmail", "qq.com");
		try
		{
			File proFile=new File("jianjipan.xml");
			FileOutputStream propStream=new FileOutputStream(proFile);
			Date now=new Date();
			properties.storeToXML(propStream, "Create on"+now);
		}
		catch (IOException e) {
			// TODO: handle exception
			System.out.println("Error: "+e.getMessage());
		}
	}
	
	public static void main(String[] args) {
		PropertyFileCreator pfc=new PropertyFileCreator();
	}
}

读取XML文件

Builder类能够加载并分析任何方言的XML数据,只要它的格式是良好的
下面代码创建一个Builder对象并使用它加载天气文件

File file=new File("forecast.xml");
Builder builder=new Builder();
Document doc=builder.build(file);

XOM也可以加载Web上的XML数据。不过它调用的build()方法是将数据所在网络地址做为参数。如下面代码所示:

Builder builder=new Builder();
Document doc=builder.build("http://tinyurl.com/rd4r72");

要检索文档的根元素,可以使用Document对象的getRootElement()方法

Element root=doc.getRootElement();

Element表示单个元素,可使用Element类的多个方法来查看元素的内容:

  • getFirstChildElement() 提取与指定名称相同的第一个子元素
  • get(in)读取与指定索引(从0开始编号)匹配的元素
  • getChildElements() 提取所有的子元素
  • getValue读取元素的文本
  • getAttribute()检索元素的一个属性
import nu.xom.*;
import java.io.*;
public class WeatherStation {
	int[] highTemp=new int[6];
	int[] lowTemp=new int[6];
	String[] conditions=new String[6];
	
	public WeatherStation() throws ParsingException,IOException
	{
		//get the XML document
		Builder builder=new Builder();
		Document doc=builder.build("http://tinyurl.com/rd4r72");
		
		//get the root element,<forecast>
		Element root=doc.getRootElement();
		
		//get the <simpleforecast> element
		Element simple=root.getFirstChildElement("forecast");
		//get the <forecastday> elements
		Elements days=simple.getChildElements("forecastday");
		for(int current=0;current<days.size();current++)
		{
			//get current <forecastday>
			Element day=days.get(current);
			//get current <high>
			Element high=day.getFirstChildElement("high");
			Element highF=high.getFirstChildElement("fahrenheit");
			//get current <low>
			Element low=day.getFirstChildElement("low");
			Element lowF=low.getFirstChildElement("fahrenheit");
			
			//get current <icon>
			Element icon=day.getFirstChildElement("icon");
			
			//store value in object variables
			lowTemp[current]=-1;
			highTemp[current]=-1;
			try {
				lowTemp[current]=Integer.parseInt(lowF.getValue());
				highTemp[current]=Integer.parseInt(highF.getValue());
			} catch (NumberFormatException e) {
				// TODO: handle exception
			}
			conditions[current]=icon.getValue();
		}
	}
	
	public void display()
	{
		for(int i=0;i<conditions.length;i++)
		{
			System.out.println("Period "+i);
			System.out.println("\tConditions: "+conditions[i]);
			System.out.println("\tHigh: "+highTemp[i]);
			System.out.println("\tLow: "+lowTemp[i]);
		}
	}
	
	public static void main(String[] args) {
		try {
			WeatherStation station=new WeatherStation();
			station.display();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Error: "+e.getMessage());
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值