`
dkplus
  • 浏览: 17594 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
阴影文字 java se, java实例100, 阴影文字
/*
dkplus专业搜集和编写实用电脑软件教程,搜集各种软件资源和计算机周边(java网络编程、seo网站优化、web开发,lnmp,java网络编程,毕业论文设计),独立制作视频和ppt和音频微信公众号,点击进入 dkplus官方博客http://dkplus.iteye.com 微信搜索dkplus关注公众号可获取海量计算机周边资源。
*/
import java.awt.*;
import java.applet.*;
import java.util.Random;

//跳动文字

public class ShadowTextApplet extends Applet implements Runnable{	
   String message;  //待显示的文本信息
   Thread thread;  //实现文字运动的线程
   int fontHeight,speed,baseline; //字体高度,运动速度和基线
   Color textColor,bgColor,shadomColor; //文字颜色、背景颜色与阴影颜色
   Image newImage;  //实现跳动的Image对象
   Graphics newGraphics;  //实现跳动的Graphics对象
   boolean normal; //文字是否跳动的标志
   Font font; //显示字体
   FontMetrics fontMetric; //显示字体的FontMetrics对象

   public void init(){ //初始化
		Graphics graphics = getGraphics(); //得到graphics对象
	   Dimension dim=getSize(); //得到尺寸
	   fontHeight=dim.height-10; //根据Applet尺寸设置文字高度
	   newImage=createImage(dim.width,dim.height); //创建newImage对象
	   newGraphics = newImage.getGraphics(); //得到Graphics对象
	   message=getParameter("text"); //得到显示文字
	   if (message==null){        
	     	message="阴影文字";	//设置默认文字
	   }
	   
	   int textWidth=dim.width-(message.length() + 1)*5-10; //设置文字宽度
	   do{
	   	graphics.setFont(new Font("TimesRoman", 1, fontHeight)); //设置显示字体
	      fontMetric = graphics.getFontMetrics(); //得到FontMetric对象
	      if(fontMetric.stringWidth(message)>textWidth) //根据文字宽度调整其高度
	         fontHeight--;
	   }
	   while(fontMetric.stringWidth(message) > textWidth);{
	   	baseline = getSize().height - fontMetric.getMaxDescent(); //调整显示基线位置
	   }
	   font = new Font("TimesRoman", 1, fontHeight); //得到字体实例
	   
	   String param; //参数字符串
	   if((param = getParameter("TEXTCOLOR")) == null) //得到文本颜色
	   	textColor = Color.black; //设置默认文本颜色
	   else
	      textColor = new Color(Integer.parseInt(param));  //设置文本颜色
	   if((param = getParameter("BGCOLOR")) == null)  //得到背景颜色
	       bgColor = Color.white;  //设置默认背景颜色
	   else
	       bgColor = new Color(Integer.parseInt(param)); 
	   if((param = getParameter("SHADOMCOLOR")) == null)  //得到阴影颜色
	       shadomColor = Color.lightGray;  //设置默认阴影颜色
	   else
	       shadomColor = new Color(Integer.parseInt(param)); 
	   if((param = getParameter("NORMAL")) != null) //是否是静态文本
	       normal = (Integer.valueOf(param).intValue()!=0); //参数值不为零,则为静态文本
	   setBackground(bgColor); //设置背景颜色
	   if((param = getParameter("SPEED")) != null) //得到运动速度
	       speed = Integer.valueOf(param).intValue();
	   if(speed == 0)
	       speed = 200;  //设置默认运动速度	  
     	thread = new Thread(this); //实例化运动文字线程
    }

    public void start(){ //开始运行线程
        if(thread == null) {
        		thread = new Thread(this); //实例化线程
        }
        thread.start(); //线程运行
    }

    public void run(){  //线程运行主体
        while(thread!=null) { 
            try{
                Thread.sleep(speed); //线程休眠,即跳动间隔时间
            }
            catch(InterruptedException ex) {}
            repaint();  //重绘屏幕
        }
        System.exit(0);  //退出程序
    }


    public void paint(Graphics g) {  //绘制Applet
        if(normal) {  //如果是静态文本
            g.setColor(bgColor);  //设置当前颜色
            g.fillRect(0, 0, getSize().width, getSize().height);  //绘制填充矩形
            g.setColor(textColor); //设置当前颜色
            g.setFont(font); //设置当前字体
            g.drawString(message, (getSize().width - fontMetric.stringWidth(message)) / 2, baseline); //绘出字符串
        }
    }

    public void update(Graphics g){  //更新Applet
        newGraphics.setColor(bgColor); //设置当前颜色
        newGraphics.fillRect(0, 0, getSize().width, getSize().height); //绘制填充矩形
        newGraphics.setColor(textColor); //设置当前颜色
        newGraphics.setFont(font); //设置字体
        if(!normal){ //如果是跳动文字
        		java.util.Random r=new java.util.Random();	
            int xpoint = r.nextInt(fontMetric.stringWidth(message));  //生成随机X坐标
            
            font = new Font("TimesRoman",Font.BOLD,30); //设置字体
			newGraphics.setFont(font);  //设置当前字体
			    
		    newGraphics.setColor(shadomColor); //设置当前颜色
		    newGraphics.drawString(message,xpoint+3,baseline +3); //绘制阴影
		    
		    newGraphics.setColor(textColor); //设置文本颜色
		    newGraphics.drawString(message,xpoint,baseline); //绘字符串
			    
        } 
        else {  //如果是静态文本
            font = new Font("TimesRoman",Font.BOLD,30); //设置字体
			newGraphics.setFont(font);  //设置当前字体
			    
		    newGraphics.setColor(shadomColor); //设置当前颜色
		    newGraphics.drawString(message,xpoint+3,baseline +3); //绘制阴影
		    
		    newGraphics.setColor(textColor); //设置文本颜色
		    newGraphics.drawString(message,xpoint,baseline); //绘字符串
     	  }
        g.drawImage(newImage, 0, 0, this); //绘制Image
    }
}
滑杆演示 滑杆演示, java实例100, java se 滑杆演示
import java.awt.*;
import javax.swing.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class GraphPanel extends JPanel {
   int width=10;  //椭圆高度值
   int hight=10;  //椭圆宽度值
 
   public void paintComponent(Graphics g) {
      super.paintComponent(g);  //调用父类方法
      g.fillOval(5,5,width,hight);  //绘制椭圆
   }
 
   public void setW(int length){ //设置宽度
      width=(length>=0?length:10 ); 
      repaint(); //重绘组件
   }
    
   public void setH(int length){ //设置高度
      hight=(length>=0?length:10 );  
      repaint();  //重绘组件
   }   
}
滑杆演示 滑杆演示, java实例100, java se 滑杆演示
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
//滑杆演示
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class JSliderDemo extends JFrame {
   JSlider xSlider;  //用于改变椭圆宽度值
   JSlider ySlider;  //且于改变椭圆高度值
   GraphPanel panel; //绘圆的面板
 
   public JSliderDemo() 
   {
      super("滑杆演示");  //调用父类构造函数
      panel=new GraphPanel();  //实例化面板
      panel.setBackground(Color.orange); //设置面板背景色为橙色
 
      xSlider=new JSlider( SwingConstants.HORIZONTAL,0,200,10); //实例化滑杆
      xSlider.setMajorTickSpacing(10); //设置刻度值
      xSlider.setPaintTicks(true); //描绘刻度
      ySlider=new JSlider( SwingConstants.VERTICAL,0,200,10); 
      ySlider.setMajorTickSpacing(10);
      ySlider.setPaintTicks(true);
      ySlider.setInverted(true);  //设置拖动方向
      ValueChangeListener myListener=new ValueChangeListener(); //实例化滑杆事件处理
      xSlider.addChangeListener(myListener); //增加滑杆的事件处理
      ySlider.addChangeListener(myListener);
 
      Container container=getContentPane(); //得到容器
      container.add(xSlider,BorderLayout.SOUTH); //增加组件到容器上
      container.add(ySlider,BorderLayout.EAST);
      container.add(panel,BorderLayout.CENTER);
 
      setSize(220,200);  //设置窗口尺寸
      setVisible(true);  //设置窗口为可视
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );  //关闭窗口时退出程序
   }
    
   class ValueChangeListener implements ChangeListener{  //事件处理
      public void stateChanged(ChangeEvent e){
        if (e.getSource()==xSlider){ //判断事件源
            panel.setW(xSlider.getValue()); //设置椭圆宽度
        }
        else{
            panel.setH(ySlider.getValue()); //设置椭圆高度
        }
      }
   }
 
   public static void main(String args[]) {
      new JSliderDemo();
   }
 
}
动画图标 动画图标, java se, java实例100 动画图标
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
//动画图标
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class AnimatorIcon extends JPanel implements ActionListener {
 
    ImageIcon[] images; //用于动画的图标数组
    Timer animationTimer; 
    int currentImage = 0; //当前图像编号
    int delay = 500;  //图像切换延迟
    int width; //图像宽度
    int height; //图像高度
 
    public AnimatorIcon() //构造函数
    {
        setBackground(Color.white);
        images = new ImageIcon[2]; //初始化数组
        for (int i=0;i<images.length;i++)
            images[i]=new ImageIcon(getClass().getResource("image"+i+".gif")); //实例化图标
        width = images[0].getIconWidth(); //初始化宽度值
        height = images[0].getIconHeight(); //初始化高度值
    }
 
    public void paintComponent(Graphics g) { //重载组件绘制方法
        super.paintComponent(g); //调用父类函数
        images[currentImage].paintIcon(this,g,70,0); //绘制图标
        currentImage=(currentImage+1)%2; //更改当前图像编号
    }
 
    public void actionPerformed(ActionEvent actionEvent) {
        repaint();
    }
 
    public void startAnimation() { //开始动画
        if (animationTimer==null) {
            currentImage=0; 
            animationTimer=new Timer(delay, this);  //实例化Timer对象
            animationTimer.start(); //开始运行
        } else if (!animationTimer.isRunning()) //如果没有运行
            animationTimer.restart(); //重新运行
    }
 
    public void stopAnimation() { 
        animationTimer.stop();  //停止动画
    }
 
    public static void main(String args[]) {
        AnimatorIcon animation = new AnimatorIcon(); //实例化动画图标
        JFrame frame = new JFrame("动画图标"); //实例化窗口对象
        frame.getContentPane().add(animation);  //增加组件到窗口上
        frame.setSize(200, 100); //设置窗口尺寸
        frame.setVisible(true); //设置窗口可视
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
        animation.startAnimation(); //开始动画
    }
 
}
简单的表单程序 简单的表单程序, java se, java实例100 简单的表单程序
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class FormDemo extends HttpServlet{
    public void doGet(HttpServletRequest request,HttpServletResponse response){     
        try{
            response.setContentType("text/html;charset=gb2312"); //设置头部
            PrintWriter out=response.getWriter();  //得到PrintWriter实例
            String name,age,sex,phone,address,email;  //变量声明
            name=request.getParameter("Name");  //得到参数
            sex=request.getParameter("Sex");
            phone=request.getParameter("Phone");
            address=request.getParameter("Address");
            email=request.getParameter("Email");
            out.println("<HTML><HEAD><TITLE>a</TITLE></HEAD>");  //输出信息到客户端
            out.println("<BODY>");
            out.println("<P><H3>名字:"+convertToChinese(name)+"</H3></P>");
            out.println("<P><H3>性别:"+convertToChinese(sex)+"</H3></P>");
            out.println("<P><H3>电话:"+phone+"</H3></P>");
            out.println("<P><H3>地址:"+convertToChinese(address)+"</H3></P>");
            out.println("<P><H3>电子邮件:"+email+"</H3></P>");
            out.println("</BODY></HTML>");          
         
        }
        catch (Exception ex){
            ex.printStackTrace();  //输出错误信息
        }
    }
     
    private String convertToChinese(String source){
        String s="";
        try{
             s=new String(source.getBytes("ISO8859_1"));  //字符编码转换
        }
        catch(java.io.UnsupportedEncodingException ex){
            ex.printStackTrace();  //输出错误信息
        }
        return s; //返回转换后的字符串
    }   
}
数字时钟 数字时钟, java se, java实例100 数字时钟
import java.awt.*;
import java.util.*;
import javax.swing.*;
 
//数字时钟
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class ClockDemo extends JFrame implements Runnable{
    Thread clock;   
     
    public ClockDemo(){
        super("数字时钟");  //调用父类构造函数  
        setFont(new Font("Times New Roman",Font.BOLD,60));  //设置时钟的显示字体
        start(); //开始进程
        setSize(280,100);  //设置窗口尺寸
        setVisible(true);  //窗口可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
    }
     
    public void start(){ //开始进程
        if (clock==null){ //如果进程为空值
            clock=new Thread(this); //实例化进程
            clock.start(); //开始进程
        }
    }
     
    public void run(){  //运行进程
        while (clock!=null){ 
            repaint(); //调用paint方法重绘界面
            try{
                Thread.sleep(1000);  //线程暂停一秒(1000毫秒)
            }
            catch (InterruptedException ex){
                ex.printStackTrace();  //输出出错信息
            }
        }   
    }
     
    public void stop(){  //停止进程
        clock=null;
    }
     
    public void paint(Graphics g){  //重载组件的paint方法
        Graphics2D g2=(Graphics2D)g;  //得到Graphics2D对象
        Calendar now=new GregorianCalendar(); //实例化日历对象
        String timeInfo=""; //输出信息
        int hour=now.get(Calendar.HOUR_OF_DAY); //得到小时数
        int minute=now.get(Calendar.MINUTE);   //得到分数
        int second=now.get(Calendar.SECOND);  //得到秒数
         
        if (hour<=9) 
            timeInfo+="0"+hour+":"; //格式化输出
        else
            timeInfo+=hour+":";
        if (minute<=9)
            timeInfo+="0"+minute+":";
        else
            timeInfo+=minute+":";
        if (second<=9)
            timeInfo+="0"+second;
        else
            timeInfo+=second;
 
        g.setColor(Color.white);  //设置当前颜色为白色
        Dimension dim=getSize();  //得到窗口尺寸
        g.fillRect(0,0,dim.width,dim.height);  //填充背景色为白色
        g.setColor(Color.orange);  //设置当前颜色为橙色
        g.drawString(timeInfo,20,80);  //显示时间字符串
    }
 
    public static void main(String[] args){
        new ClockDemo();
    }
}
图片的拖动效果 图片的拖动效果, java实例100, java se 图片的拖动效果
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
//图片的拖动效果
 
public class DragPictureDemo extends JFrame {
 
   JLabel jlPic; //图片,用于拖动
 
   public DragPictureDemo() {
    super("图片的拖动效果");  //调用父类构造函数
    Icon image=new ImageIcon(this.getClass().getResource("1.jpg"));  //实例化图标
        jlPic = new JLabel(image);  //实例化带图片的标签
      getContentPane().add(jlPic);  //增加标签到容器上
       
      DragPicListener listener=new DragPicListener();  //鼠标事件处理
      jlPic.addMouseListener(listener);  //增加标签的事件处理
      jlPic.addMouseMotionListener(listener);       
       
      setSize(300,200);  //设置窗口尺寸
      setVisible(true);  //设置窗口为可视
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
   }
    
   class DragPicListener implements MouseInputListener{  //鼠标事件处理
      Point p=new Point(0,0); //坐标点
    public void mouseMoved(MouseEvent e){}
    public void mouseDragged(MouseEvent e){
        Point newP=SwingUtilities.convertPoint(jlPic,e.getPoint(),jlPic.getParent()); //转换坐标系统
        jlPic.setLocation(jlPic.getX()+(newP.x-p.x),jlPic.getY()+(newP.y-p.y)); //设置标签的新位置
        p=newP; //更改坐标点
    }
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mousePressed(MouseEvent e){
        p=SwingUtilities.convertPoint(jlPic,e.getPoint(),jlPic.getParent()); //得到当前坐标点
    }   
   }
 
    public static void main(String[] args) {
        new DragPictureDemo();
   } 
}
文本的拖动处理 文本的拖动处理, java实例100, java se 文本的拖动处理
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import javax.swing.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class DragList extends JList implements DragGestureListener, DragSourceListener{
     
    DragSource dragSource=DragSource.getDefaultDragSource(); //拖动源
    public DragList(Object[] data){  //构造函数
        super(data); 
        int action = DnDConstants.ACTION_COPY_OR_MOVE; //拖动类型
        dragSource.createDefaultDragGestureRecognizer(this,action,this); //创建拖动识别
    }
     
    public void dragGestureRecognized(DragGestureEvent dge) {
        try{
            Transferable trans = new StringSelection(this.getSelectedValue().toString()); //得到拖动的Transferable对象
            dge.startDrag(DragSource.DefaultCopyNoDrop,trans,this);  //开始拖动操作
        }catch(Exception err){
            err.printStackTrace();  //输出错误信息
        }
    }
     
    public void dragEnter(DragSourceDragEvent dragSourcede) {  //拖动进入处理
        DragSourceContext dragSourceContext = dragSourcede.getDragSourceContext(); //得到拖动上下文对象
        int action = dragSourcede.getDropAction(); //得到拖动命令
        if ((action&DnDConstants.ACTION_COPY)!=0)  //判断命令类型
            dragSourceContext.setCursor(DragSource.DefaultCopyDrop);  //设置光标类型
        else
            dragSourceContext.setCursor(DragSource.DefaultCopyNoDrop);
    }
    public void dragOver(DragSourceDragEvent dragSourcede) {
    }
    public void dropActionChanged(DragSourceDragEvent dragSourcede) {
    }
    public void dragExit(DragSourceEvent dragSourcee) {
    }
    public void dragDropEnd(DragSourceDropEvent dragSourcede) {
    }
}
文本的拖动处理 文本的拖动处理, java se, java实例100 文本的拖动处理
import javax.swing.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class DragLabel extends JLabel implements DropTargetListener{
     
    public DragLabel(String str){
        super(str);  //调用父类构造函数
    }
     
    public void dragEnter(DropTargetDragEvent evt) {
    }
    public void dragOver(DropTargetDragEvent evt) {
    }
    public void dropActionChanged(DropTargetDragEvent evt) {
    }
    public void dragExit(DropTargetEvent evt) {
    }
    public void drop(DropTargetDropEvent evt) {  //拖动操作处理
        try{
            Transferable trans = evt.getTransferable(); //得以Transferable对象
            if (evt.isDataFlavorSupported(DataFlavor.stringFlavor)){ //是否支持拖动
                evt.acceptDrop(evt.getDropAction()); //接受拖动
                String s = (String) trans.getTransferData(DataFlavor.stringFlavor); //得到拖动数据
                setText(s); //设置标签的文本
                evt.dropComplete(true); //结束拖动
            }else{
                evt.rejectDrop(); //拒绝托运
 
            }
        }catch(Exception err){
            err.printStackTrace(); //输出出错信息
        }
    }
 
}
文本的拖动处理 文本的拖动处理, java实例100, java se 文本的拖动处理
import java.awt.*;
import javax.swing.*;
import javax.swing.JSplitPane;
import java.awt.dnd.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
//文本的拖动处理
 
public class DragTextDemo extends JFrame{
     
    public DragTextDemo(){
        super("文本的拖动处理"); //调用父类构造函数
         
        String[] data = {"one", "two", "three", "four"}; //字符数组,用于构造列表框     
        DragList list=new DragList(data); //列表框实例
        JTextArea jta=new JTextArea(8,20); //文本框实例
        DragLabel label=new DragLabel("拖动目标"); //标签实例
         
        jta.setLineWrap(true); //设置自动换行
        jta.setDragEnabled(true); //文本框可拖动
        new DropTarget(label,DnDConstants.ACTION_COPY,label); //实例化拖动目标为标签
         
        Container container=getContentPane(); //得到容器
        JSplitPane split=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); //实例化分隔面板
        split.setDividerLocation(140); //设置分隔位置
        split.add(list); //增加组件到分隔面板
        split.add(jta);
        container.add(split,BorderLayout.CENTER);  //增加组件到容器上       
        container.add(label,BorderLayout.SOUTH);
         
        setSize(300,150);  //设置窗口尺寸
        setVisible(true);  //设置窗口为可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
    }
     
    public static void main(String[] args){
        new DragTextDemo();
    }
}
使用剪贴板的复制/粘贴程序 使用剪贴板的复制/粘贴程序, java se, java实例100 使用剪贴板的复制/粘贴程序
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
//剪贴板演示
 
public class ClipboardDemo extends JFrame implements ClipboardOwner{
    Clipboard clipboard;  //剪贴板
    JTextArea jtaCopyTo=new JTextArea(5,10);    //用于拷贝的文本框
    JTextArea jtaPaste=new JTextArea(5,10); //用于粘贴的文本框
     
    public ClipboardDemo(){
        super("使用剪贴板的复制/粘贴程序"); //调用父类构造函数
                 
        clipboard=Toolkit.getDefaultToolkit().getSystemClipboard(); //获得系统剪贴板
         
        JButton btCopy=new JButton("拷贝");   //拷贝按钮
        JButton btPaste=new JButton("粘贴");  //粘贴按钮
        jtaCopyTo.setLineWrap(true);    //设置换行
        jtaPaste.setLineWrap(true);
        jtaCopyTo.setBorder(BorderFactory.createTitledBorder("复制到系统剪切板"));  //设置边界
        jtaPaste.setBorder(BorderFactory.createTitledBorder("从系统剪切板粘贴"));
         
        Container container=getContentPane();   //得到容器
        JToolBar toolBar=new JToolBar();    //实例化工具栏
        toolBar.add(btCopy);    //增加工具栏按钮
        toolBar.add(btPaste);       
        btCopy.addActionListener(new CopyListener());   //按钮事件处理
        btPaste.addActionListener(new PasteListener());     
        Box box=new Box(BoxLayout.X_AXIS);  //实例化Box
        box.add(jtaCopyTo); //增加文本框到Box上
        box.add(jtaPaste);      
        container.add(toolBar,BorderLayout.NORTH);  //增加工具栏到容器
        container.add(box,BorderLayout.CENTER); //增加Box到容器
     
        setSize(320,180);   //设置窗口尺寸
        setVisible(true);   //设置窗口为可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
    }
     
    class CopyListener implements ActionListener {  //拷贝数据处理
        public void actionPerformed(ActionEvent event) {
            StringSelection contents=new StringSelection(jtaCopyTo.getText());  //用拷贝文本框文本实例化StringSelection对象
            clipboard.setContents(contents, ClipboardDemo.this);    //设置系统剪贴板内容
        }
    }
     
    class PasteListener implements ActionListener { //粘贴数据处理
        public void actionPerformed(ActionEvent event) {
            Transferable contents=clipboard.getContents(this);  //得到剪贴板内容
                if(contents!=null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { //判断内容是否为空,是否为字符串
                    try{
                        String string= (String) contents.getTransferData(DataFlavor.stringFlavor);  //转换内容到字符串
                        jtaPaste.append(string);    //插入字符串到粘贴文本框
                    }catch (Exception ex){
                        ex.printStackTrace();   //错误处理
                    }
            }
        }
    }
     
    public void lostOwnership(Clipboard clip,Transferable transferable) {   //实现ClipboardOwner接口中的方法
    }
 
    public static void main(String[] args){
        new ClipboardDemo();    
    }
}
简单的文本编辑器 简单的文本编辑器, java实例100, java se 简单的文本编辑器
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
//简单的文本编辑器
 
public class EditorDemo extends JFrame {
    JTextPane textPane = new JTextPane(); //文本窗格,编辑窗口
    JLabel statusBar = new JLabel(); //状态栏
    JFileChooser filechooser = new JFileChooser(); //文件选择器
 
    public EditorDemo() { //构造函数
        super("简单的文本编辑器");  //调用父类构造函数
 
        Action[] actions =  //Action数组,各种操作命令
            {
                new NewAction(),
                new OpenAction(),
                new SaveAction(),
                new CutAction(),
                new CopyAction(),
                new PasteAction(),
                new AboutAction(),
                new ExitAction()};
 
        setJMenuBar(createJMenuBar(actions));  //设置菜单栏
        Container container = getContentPane(); //得到容器
        container.add(createJToolBar(actions), BorderLayout.NORTH); //增加工具栏
        container.add(textPane, BorderLayout.CENTER); //增加文本窗格
        container.add(statusBar, BorderLayout.SOUTH); //增加状态栏
 
        setSize(330, 200); //设置窗口尺寸
        setVisible(true);  //设置窗口可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
    }
 
    private JMenuBar createJMenuBar(Action[] actions) {  //创建菜单栏
        JMenuBar menubar = new JMenuBar(); //实例化菜单栏
        JMenu menuFile = new JMenu("文件"); //实例化菜单
        JMenu menuEdit = new JMenu("编辑");
        JMenu menuAbout = new JMenu("帮助");
        menuFile.add(new JMenuItem(actions[0])); //增加新菜单项
        menuFile.add(new JMenuItem(actions[1]));
        menuFile.add(new JMenuItem(actions[2]));
        menuFile.add(new JMenuItem(actions[7]));
        menuEdit.add(new JMenuItem(actions[3]));
        menuEdit.add(new JMenuItem(actions[4]));
        menuEdit.add(new JMenuItem(actions[5]));
        menuAbout.add(new JMenuItem(actions[6]));
        menubar.add(menuFile); //增加菜单
        menubar.add(menuEdit);
        menubar.add(menuAbout);
        return menubar; //返回菜单栏
    }
 
    private JToolBar createJToolBar(Action[] actions) { //创建工具条
        JToolBar toolBar = new JToolBar(); //实例化工具条
        for (int i = 0; i < actions.length; i++) { 
            JButton bt = new JButton(actions[i]); //实例化新的按钮
            bt.setRequestFocusEnabled(false); //设置不需要焦点
            toolBar.add(bt); //增加按钮到工具栏
        }
        return toolBar;  //返回工具栏
    }
 
    class NewAction extends AbstractAction { //新建文件命令
        public NewAction() {
            super("新建");
        }
        public void actionPerformed(ActionEvent e) {
            textPane.setDocument(new DefaultStyledDocument()); //清空文档
        }
    }
 
    class OpenAction extends AbstractAction { //打开文件命令
        public OpenAction() {
            super("打开");
        }
        public void actionPerformed(ActionEvent e) {
            int i = filechooser.showOpenDialog(EditorDemo.this); //显示打开文件对话框
            if (i == JFileChooser.APPROVE_OPTION) { //点击对话框中打开选项
                File f = filechooser.getSelectedFile(); //得到选择的文件
                try {
                    InputStream is = new FileInputStream(f); //得到文件输入流
                    textPane.read(is, "d"); //读入文件到文本窗格
                } catch (Exception ex) {
                    ex.printStackTrace();  //输出出错信息
                }
            }
        }
    }
 
    class SaveAction extends AbstractAction {  //保存命令
        public SaveAction() {
            super("保存");
        }
        public void actionPerformed(ActionEvent e) {
            int i = filechooser.showSaveDialog(EditorDemo.this); //显示保存文件对话框
            if (i == JFileChooser.APPROVE_OPTION) {  //点击对话框中保存按钮
                File f = filechooser.getSelectedFile(); //得到选择的文件
                try {
                    FileOutputStream out = new FileOutputStream(f);  //得到文件输出流
                    out.write(textPane.getText().getBytes()); //写出文件                
                } catch (Exception ex) {
                    ex.printStackTrace(); //输出出错信息
                }
            }
        }
    }
 
    class ExitAction extends AbstractAction { //退出命令
        public ExitAction() {
            super("退出");
        }
        public void actionPerformed(ActionEvent e) {
            System.exit(0);  //退出程序
        }
    }
 
    class CutAction extends AbstractAction {  //剪切命令
        public CutAction() {
            super("剪切");
        }
        public void actionPerformed(ActionEvent e) {
            textPane.cut();  //调用文本窗格的剪切命令
        } 
    }
 
    class CopyAction extends AbstractAction {  //拷贝命令
        public CopyAction() {
            super("拷贝");
        }
        public void actionPerformed(ActionEvent e) {
            textPane.copy();  //调用文本窗格的拷贝命令
        }
    }
 
    class PasteAction extends AbstractAction {  //粘贴命令
        public PasteAction() {
            super("粘贴");
        }
        public void actionPerformed(ActionEvent e) {
            textPane.paste();  //调用文本窗格的粘贴命令
        }
    }
 
    class AboutAction extends AbstractAction { //关于选项命令
        public AboutAction() {
            super("关于");
        }
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(EditorDemo.this, "简单的文本编辑器演示"); //显示软件信息
        }
    }
 
    public static void main(String[] args) {
        new EditorDemo();
    }
 
}
java连接MySQl数据库实例 java连接mysql数据库实例, java se, java实例100 java连接MySQl数据库实例
//java连接MySQl数据库实例代码
package com.abc.dao;
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class BaseDao {
 public Connection getConn()
 {
  Connection conn=null;
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  String url="jdbc:mysql://127.0.0.1:3306/user";
  try {
   conn=DriverManager.getConnection(url, "root", "");
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
  return conn;
 }
 public void closeAll(ResultSet rs,Statement stat,Connection conn)
 {
  if(rs!=null)
   try {
    rs.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  if(stat!=null)
   try {
    stat.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  if(conn!=null)
   try {
    conn.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
 }
}
登陆界面 登陆界面, java se, java实例100 登陆界面
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
 
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
public class Login {
 
    private JFrame frame = new JFrame("登录");
    private Container c = frame.getContentPane();
    private JTextField username = new JTextField();
    private JPasswordField password = new JPasswordField();
    private JButton ok = new JButton("确定");
    private JButton cancel = new JButton("取消");
    public Login(){
        frame.setSize(300,200);
        c.setLayout(new BorderLayout());
        initFrame();
        frame.setVisible(true);
    }
 
    private void initFrame() {
         
        //顶部
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(new FlowLayout());
        titlePanel.add(new JLabel("系统管理员登录"));
        c.add(titlePanel,"North");
         
        //中部表单
        JPanel fieldPanel = new JPanel();
        fieldPanel.setLayout(null);
        JLabel l1 = new JLabel("用户名:");
        l1.setBounds(50, 20, 50, 20);
        JLabel l2 = new JLabel("密    码:");
        l2.setBounds(50, 60, 50, 20);
        fieldPanel.add(l1);
        fieldPanel.add(l2);
        username.setBounds(110,20,120,20);
        password.setBounds(110,60,120,20);
        fieldPanel.add(username);
        fieldPanel.add(password);
        c.add(fieldPanel,"Center");
         
        //底部按钮
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(ok);
        buttonPanel.add(cancel);
        c.add(buttonPanel,"South");
    }
     
    public static void main(String[] args){
        new Login();
    }
     
}
多线程服务器 多线程服务器, java se, java实例100 多线程服务器
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
import java.io.*;  
import java.net.*;  
 
class moreServer  
{  
 public static void main (String [] args) throws IOException  
 {  
   System.out.println ("Server starting...\n");   
   //使用8000端口提供服务  
   ServerSocket server = new ServerSocket (8000);  
   while (true)  
   {  
    //阻塞,直到有客户连接  
     Socket sk = server.accept ();  
     System.out.println ("Accepting Connection...\n");  
     //启动服务线程  
     new ServerThread (sk).start ();  
   }  
 }  
}  
//使用线程,为多个客户端服务  
class ServerThread extends Thread  
{  
 private Socket sk;  
    
 ServerThread (Socket sk)  
 {  
  this.sk = sk;  
 }  
//线程运行实体  
 public void run ()  
 {  
  BufferedReader in = null;  
  PrintWriter out = null;  
  try{  
    InputStreamReader isr;  
    isr = new InputStreamReader (sk.getInputStream ());  
    in = new BufferedReader (isr);  
    out = new PrintWriter (  
           new BufferedWriter(  
            new OutputStreamWriter(  
              sk.getOutputStream ())), true);  
   
    while(true){  
      //接收来自客户端的请求,根据不同的命令返回不同的信息。  
      String cmd = in.readLine ();  
      System.out.println(cmd);  
      if (cmd == null)  
          break;  
      cmd = cmd.toUpperCase ();  
      if (cmd.startsWith ("BYE")){  
         out.println ("BYE");  
         break;  
      }else{  
        out.println ("你好,我是服务器!");  
      }  
    }  
    }catch (IOException e)  
    {  
       System.out.println (e.toString ());  
    }  
    finally 
    {  
      System.out.println ("Closing Connection...\n");  
      //最后释放资源  
      try{  
       if (in != null)  
         in.close ();  
       if (out != null)  
         out.close ();  
        if (sk != null)  
          sk.close ();  
      }  
      catch (IOException e)  
      {  
        System.out.println("close err"+e);  
      }  
    }  
 }  
}
计算器 计算器, java se, java实例100 计算器
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Calculate extends JFrame {
    private String front = "", behind = ""; //分别用于记录加减乘除运算符之前,之后输入的内容
    private String op; //用于记录运算符
    private String re;//用于存储运算结果的字符串格式
    private boolean flag = false; //用于记录是否按下了运算符
    private boolean flag1 = false;//用于判断是否输入了点运算符
    private double result;//用于存储运算结果
    private boolean flag2 = false;//用于判断是否输入了数字
    private boolean flag3 = false;//用于判断是否按下了等号运算符
    
    JPanel contentPane;
    
    JTextField txtResult = new JTextField("0");
    JButton btnNull = new JButton("sqrt");
    JButton btnFour = new JButton("4");
    JButton btnFive = new JButton("5");
    JButton btnSix = new JButton("6");
    JButton btnDecrease = new JButton("-");
    JButton btnBegin = new JButton("C");
    JButton btnOne = new JButton("1");
    JButton btnTwo = new JButton("2");
    JButton btnThree = new JButton("3");
    JButton btnMultiply = new JButton("*");
    JButton btnCancel = new JButton("←");
    JButton btnZero = new JButton("0");
    JButton btnMinus = new JButton("+/-");
    JButton btnPoint = new JButton(".");
    JButton btnDivide = new JButton("/");
    JButton btnEqual = new JButton("=");
    JButton btnIncrease = new JButton("+");
    JButton btnSeven = new JButton("7");
    JButton btnEight = new JButton("8");
    JButton btnNine = new JButton("9");
 
public Calculate() {
       try {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jbInit();
        } catch (Exception exception) {
            exception.printStackTrace();
                }
    }
 
    private void jbInit() throws Exception {
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(null);
        this.setResizable(false);
        setSize(new Dimension(400, 300));
        setTitle("计算器");
        txtResult.setEnabled(false);
        txtResult.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        txtResult.setEditable(false);
        
        txtResult.setHorizontalAlignment(SwingConstants.RIGHT);
        txtResult.setBounds(new Rectangle(33, 19, 310, 34));
        btnNull.setBounds(new Rectangle(298, 70, 46, 37));
        btnNull.setFont(new java.awt.Font("Dialog", Font.PLAIN, 12));
       
     //btnNull.addActionListener(new FrameCalculate_btnNull_actionAdapter(this));
        btnFour.setBounds(new Rectangle(33, 120, 46, 37));
        btnFour.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        
        btnFive.setBounds(new Rectangle(101, 120, 46, 37));
        btnFive.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        
        btnSix.setBounds(new Rectangle(167, 119, 46, 37));
        btnSix.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        btnDecrease.setBounds(new Rectangle(234, 120, 46, 37));
        btnDecrease.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
      
        btnBegin.setBounds(new Rectangle(298, 121, 46, 37));
        btnBegin.setFont(new java.awt.Font("Dialog", Font.PLAIN, 15));
       
        btnBegin.addActionListener(new Calculate_btnBegin_actionAdapter(this));
        btnOne.setBounds(new Rectangle(33, 172, 46, 37));
        btnOne.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        
        btnTwo.setBounds(new Rectangle(101, 172, 46, 37));
        btnTwo.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        btnThree.setBounds(new Rectangle(167, 172, 46, 37));
        btnThree.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        btnMultiply.setBounds(new Rectangle(234, 172, 46, 37));
        btnMultiply.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        
        btnCancel.setBounds(new Rectangle(298, 172, 46, 37));
        btnCancel.setFont(new java.awt.Font("Dialog", Font.PLAIN, 12));
       
       btnCancel.addActionListener(new Calculate_btnCancel_actionAdapter(this));
        btnZero.setBounds(new Rectangle(33, 222, 46, 37));
        btnZero.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        //加载数字0-9的监听事件
        btnZero.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnOne.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnTwo.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnThree.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnFour.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnFive.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnSix.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnSeven.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnEight.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnNine.addActionListener(new Calculate_btnZero_actionAdapter(this));
        btnMinus.setBounds(new Rectangle(101, 222, 46, 37));
        btnMinus.setFont(new java.awt.Font("Dialog", Font.PLAIN, 10));
        
        btnMinus.addActionListener(new Calculate_btnMinus_actionAdapter(this));
        btnPoint.setBounds(new Rectangle(167, 222, 46, 37));
        btnPoint.setFont(new java.awt.Font("Dialog", Font.PLAIN, 30));
        btnPoint.setHorizontalTextPosition(SwingConstants.CENTER);
       
        btnPoint.addActionListener(new Calculate_btnPoint_actionAdapter(this));
        btnDivide.setBounds(new Rectangle(234, 222, 46, 37));
        btnDivide.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        
        btnEqual.setBounds(new Rectangle(298, 222, 46, 37));
        btnEqual.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
        
        btnEqual.addActionListener(new Calculate_btnEqual_actionAdapter(this));
        btnIncrease.setBounds(new Rectangle(234, 70, 46, 37));
        btnIncrease.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        //加载加减乘除运算符的监听事件
        btnIncrease.addActionListener(new
                                     Calculate_btnIncrease_actionAdapter(this));
        btnDecrease.addActionListener(new
                                      Calculate_btnIncrease_actionAdapter(this));
        btnMultiply.addActionListener(new
                                     Calculate_btnIncrease_actionAdapter(this));
        btnDivide.addActionListener(new
                                    Calculate_btnIncrease_actionAdapter(this));
        btnSeven.setBounds(new Rectangle(33, 70, 46, 37));
        btnSeven.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        btnEight.setBounds(new Rectangle(101, 70, 46, 37));
        btnEight.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
       
        btnNine.setBounds(new Rectangle(167, 70, 46, 37));
        btnNine.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
      
        contentPane.add(btnFive);
        contentPane.add(btnSix);
        contentPane.add(btnDecrease);
        contentPane.add(btnBegin);
        contentPane.add(btnOne);
        contentPane.add(btnTwo);
        contentPane.add(btnThree);
        contentPane.add(btnMultiply);
        contentPane.add(btnCancel);
        contentPane.add(btnMinus);
        contentPane.add(btnPoint);
        contentPane.add(btnDivide);
        contentPane.add(btnEqual);
        contentPane.add(btnEight);
        contentPane.add(btnNine);
        contentPane.add(btnFour);
        contentPane.add(btnSeven);
        contentPane.add(btnIncrease);
        contentPane.add(btnNull);
        contentPane.add(txtResult);
        contentPane.add(btnZero);
    }
 
public void btnZero_actionPerformed(ActionEvent e) {
        if (flag) { //如果刚刚按下了运算符
            txtResult.setText("");
            if (flag1) {//判断之前是否输入了点运算符
                txtResult.setText("0." + e.getActionCommand());
                flag1 = false;
            } else {
                txtResult.setText(e.getActionCommand());
            }
            flag2 = true;
        } else {
            int num = txtResult.getText().indexOf(".");
            if (num < 0 && !txtResult.getText().equals("0")) {
                txtResult.setText(txtResult.getText() + e.getActionCommand());
            } else if (num < 0 && txtResult.getText().equals("0")) {
                txtResult.setText(e.getActionCommand());
            } else if (num >= 0 && txtResult.getText().equals("0")) {
                txtResult.setText("0." + e.getActionCommand());
            } else if (num >= 0 && !txtResult.getText().equals("0")) {
                txtResult.setText(txtResult.getText() + e.getActionCommand());
            }
        }
        flag = false;
        flag3=false;
    }
 
    public void btnIncrease_actionPerformed(ActionEvent e) {
        if(flag3){
            txtResult.setText(txtResult.getText());
            op = e.getActionCommand(); //得到刚刚按下的运算符
            front = txtResult.getText(); //记录加减乘除运算符之前输入的内容
        }
        else if (flag2) {
            ActionEvent ee = new ActionEvent("qq", 1, "pp");
            btnEqual_actionPerformed(ee);
            op = e.getActionCommand(); //得到刚刚按下的运算符
            front = re;
            flag2 = false;
        } else {
            front = txtResult.getText(); //记录加减乘除运算符之前输入的内容
            op = e.getActionCommand(); //得到刚刚按下的运算符
        }
        flag3=false;
        flag = true; //记录已经按下了加减乘除运算符的其中一个
    }
 
    public void btnEqual_actionPerformed(ActionEvent e) {
        if(!flag3)//未曾按下等于运算符
            behind = txtResult.getText();
        else
            front = re;
        try {
            double a1 = Double.parseDouble(front);
            double b1 = Double.parseDouble(behind);
            if (op == "+") {
                result = a1 + b1;
            } else if (op == "-") {
                result = a1 - b1;
            } else if (op == "*") {
                result = a1 * b1;
            } else {
                result = a1 / b1;
            }
            Double r = new Double(result);
            re = r.toString(result);
            txtResult.setText(re);
            } catch (ArithmeticException ce) {
                txtResult.setText("除数不能为零");
            } catch (Exception ee) {
            }
            if (!flag3)
                flag3 = true;
    }
 
    public void btnPoint_actionPerformed(ActionEvent e) {
        int num=txtResult.getText().indexOf(".");
        if(num<0 && !flag)
            txtResult.setText(txtResult.getText()+e.getActionCommand());
        if(flag)
            flag1=true;
    }
 
    public void btnBegin_actionPerformed(ActionEvent e) {//清零运算符事件处理
        flag=false;
        flag1=false;
        flag2=false;
        flag3=false;
        front="";
        behind="";
        re="";
        txtResult.setText("0");
    }
 
    public void btnMinus_actionPerformed(ActionEvent e) {//取反运算符事件处理
        if(txtResult.getText().equals("0")){//如果文本框内容为0
            txtResult.setText(txtResult.getText());
        }else if(txtResult.getText().indexOf("-")>=0){//若文本框中含有负号
            String a=txtResult.getText().replaceAll("-","");
            txtResult.setText(a);
        }else if(flag){
            txtResult.setText("0");
        }else{
            txtResult.setText("-"+txtResult.getText());
        }
    }
 
    public void btnCancel_actionPerformed(ActionEvent e) {//退格事件处理方法
        String str=txtResult.getText();
        if(str.length() == 1){//如文本框中只剩下最后一个字符,将文本框内容置为0
            txtResult.setText("0");
        }
        if(str.length()>1){
            str=str.substring(0,str.length()-1);
            txtResult.setText(str);
        }
    }
 
    public static void main(String[] args){
        Calculate fc = new Calculate();
        fc.setSize(400,310);
        fc.setLocation(200,150);
        fc.setVisible(true);
    }
}
 
class Calculate_btnCancel_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnCancel_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnCancel_actionPerformed(e);
    }
}
 
class Calculate_btnMinus_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnMinus_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnMinus_actionPerformed(e);
    }
}
 
class Calculate_btnBegin_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnBegin_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnBegin_actionPerformed(e);
    }
}
 
class Calculate_btnPoint_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnPoint_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnPoint_actionPerformed(e);
    }
}
 
class Calculate_btnEqual_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnEqual_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnEqual_actionPerformed(e);
    }
}
 
class Calculate_btnIncrease_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnIncrease_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnIncrease_actionPerformed(e);
    }
}
 
class Calculate_btnZero_actionAdapter implements ActionListener {
    private Calculate adaptee;
    Calculate_btnZero_actionAdapter(Calculate adaptee) {
        this.adaptee = adaptee;
    }
 
    public void actionPerformed(ActionEvent e) {
        adaptee.btnZero_actionPerformed(e);
    }
}
森林状的关系图 森林状的关系图, java se, java实例100 森林状的关系图
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
 
//森林状的关系图
 
public class JTreeDemo extends JFrame{
    JTextField jtfInfo; //文本域,用于显示点击的节点名称
     
    public JTreeDemo(){
        super("森林状的关系图");  //调用父类构造函数
         
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("设置"); //生成根节点
        DefaultMutableTreeNode node1=new DefaultMutableTreeNode("常规"); //生成节点一
        node1.add(new DefaultMutableTreeNode("默认路径")); //增加新节点到节点一上
        node1.add(new DefaultMutableTreeNode("保存选项"));
        root.add(node1);  //增加节点一到根节点上
        root.add(new DefaultMutableTreeNode("界面"));    
        root.add(new DefaultMutableTreeNode("提示声音"));  
        root.add(new DefaultMutableTreeNode("打印"));    
         
        JTree tree = new JTree(root);  //得到JTree的实例         
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)tree.getCellRenderer(); //得到JTree的Renderer
        renderer.setLeafIcon(null); //设置叶子节点图标为空
        renderer.setClosedIcon(null);  //设置关闭节点的图标为空
        renderer.setOpenIcon(null); //设置打开节点的图标为空
         
        tree.addTreeSelectionListener(new TreeSelectionListener() {  //选择节点的事件处理
        public void valueChanged(TreeSelectionEvent evt) {
            TreePath path = evt.getPath();  //得到选择路径
            String info=path.getLastPathComponent().toString(); //得到选择的节点名称
            jtfInfo.setText(info);  //在文本域中显示名称
        }
        });
 
 
        JScrollPane jsp=new JScrollPane(tree); //增加JTree到滚动窗格
        jtfInfo=new JTextField(); //实例化文本域
        jtfInfo.setEditable(false); //文本域不可编辑
        getContentPane().add(jsp,BorderLayout.CENTER);  //增加组件到容器上
        getContentPane().add(jtfInfo,BorderLayout.SOUTH);
         
                 
        setSize(250,200);  //设置窗口尺寸
        setVisible(true);  //设置窗口可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
    }
     
    public static void main(String[] args){
        new JTreeDemo();
    }
}
右键弹出菜单 右键弹出菜单, java se, java实例100 右键弹出菜单
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
//右键弹出菜单
 
public class JPopMenuDemo extends JFrame {
   JRadioButtonMenuItem items[]; //菜单项
   Color[] colors={Color.blue,Color.pink,Color.yellow,Color.red,Color.orange}; //颜色数组
   JPopupMenu popupMenu; //弹出菜单
 
   public JPopMenuDemo()
   {
      super( "右键弹出菜单" ); //调用父类构造函数
 
      ChangeColorAction action = new ChangeColorAction(); //菜单项事件处理
      String[] str = {"Blue","Pink","Yellow","Red","Orange"}; //菜单项名称
      ButtonGroup colorGroup=new ButtonGroup(); //实例化按钮组
      popupMenu=new JPopupMenu(); //实例化弹出菜单
      items=new JRadioButtonMenuItem[5]; //初始化数组
      for (int i=0;i<items.length;i++) { 
         items[i]=new JRadioButtonMenuItem(str[i]); //实例化菜单项
         popupMenu.add(items[i]); //增加菜单项到菜单上
         colorGroup.add(items[i]); //增加菜单项到按钮组
        items[i].addActionListener(action); //菜单项事件处理
      }     
 
      addMouseListener(new MouseAdapter(){  //窗口的鼠标事件处理
        public void mousePressed( MouseEvent event ) {  //点击鼠标
           triggerEvent(event);  //调用triggerEvent方法处理事件
        } 
 
        public void mouseReleased( MouseEvent event ) { //释放鼠标
           triggerEvent(event); 
        } 
 
        private void triggerEvent(MouseEvent event) { //处理事件
           if (event.isPopupTrigger()) //如果是弹出菜单事件(根据平台不同可能不同)
              popupMenu.show(event.getComponent(),event.getX(),event.getY());  //显示菜单
        }
    }); 
 
    getContentPane().setBackground(Color.white); //窗口的默认背景色为白色
    setSize(230,160); //设置窗口大小
    setVisible(true); //设置窗口为可视
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //关闭窗口时退出程序
   }
 
   class ChangeColorAction implements ActionListener { //菜单项事件处理
      public void actionPerformed(ActionEvent event)   {
         for (int i=0;i<items.length;i++)
            if (event.getSource()==items[i]) { //判断事件来自于哪个菜单项
               getContentPane().setBackground(colors[i]); //设置窗口背景
               repaint(); //重绘窗口
               return;
         }
      }
   }  
    
   public static void main( String args[])   {
      new JPopMenuDemo();      
   }
} 
多种风格的窗口 多种风格的窗口, java se, java实例100 多种风格的窗口
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
//显示多种风格的窗口
 
public class LookAndFeelDemo extends JFrame {
 
   public LookAndFeelDemo(){
     super("多种风格的窗口");  //调用父类构造函数
 
     Container container=getContentPane();  //得到容器
 
     JMenu menuTheme=new JMenu("窗口风格");  //初始化菜单
     JMenuItem itemNative=new JMenuItem("系统平台风格");  //初始化菜单项
     JMenuItem itemMotif=new JMenuItem("Motif风格");
     JMenuItem itemMetal=new JMenuItem("跨平台风格");
     menuTheme.add(itemNative);  //增加菜单项
     menuTheme.add(itemMotif);
     menuTheme.add(itemMetal);
     itemNative.addActionListener(new ActionListener(){  //菜单项事件处理
        public void actionPerformed(ActionEvent event){
            changeLookAndFeel("Native");  //调用方法,改变窗口风格
        }
     });
     itemMotif.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event){
            changeLookAndFeel("Motif");
        }
     });
     itemMetal.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event){
            changeLookAndFeel("Metal");
        }
     });
 
     JMenuBar menuBar=new JMenuBar();  //初始化菜单栏
     menuBar.add(menuTheme);  //增加菜单到菜单栏
     setJMenuBar(menuBar);  //设置菜单
 
     JPanel panel=new JPanel();  //初始化一个JPanel
     panel.setBorder(BorderFactory.createTitledBorder("组件样式"));  //设置边界
     panel.add(new JTextField("文本框:Look and feel测试 "));  //增加组件到panel上
     panel.add(new JCheckBox("粗体"));
     panel.add(new JCheckBox("斜体"));
     panel.add(new JCheckBox("下划线"));
     panel.add(new JButton("确定"));
     panel.add(new JButton("退出"));
     container.add(panel);  //增加panel到容器上
 
     setSize(220,200);  //设置窗口尺寸
     setVisible(true);  //设置窗口可见
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
   }
 
   //改变窗口样式
   public void changeLookAndFeel(String type){
      try{
         if (type.equals("Native")) {  //判断来自于哪个菜单项
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  //设置界面样式
         }
         else if (type.equals("Motif")) {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
         }
         else if (type.equals("Metal")) {UIManager.setLookAndFeel(
            UIManager.getCrossPlatformLookAndFeelClassName());
         }
         javax.swing.SwingUtilities.updateComponentTreeUI(this);  //更新界面
     }
     catch(Exception ex){  //捕捉错误
       ex.printStackTrace();  //输出错误
     }
   }
 
   public static void main(String[] args){
      new LookAndFeelDemo();
   }
}
显示多种字体 显示多种字体, java实例100, java se 显示多种字体
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
 
//显示多种字体,用JLabel实现
 
public class FontDemo extends JFrame {
 
   public FontDemo()
   {
      super("显示多种字体");  //调用父类构造函数
 
      Font[] fonts={new Font("Serif",Font.BOLD,12),
                    new Font("Monospaced",Font.ITALIC,24),
                    new Font("宋体",Font.PLAIN,18),
                    new Font("黑体",Font.PLAIN,20),
                    new Font("Serif",Font.BOLD + Font.ITALIC,18 )
      };  //字体数组
      String[] text={"Font Demo","Monospaced,斜体,24号","宋体字示例","黑体","Serif,粗体,斜体,18号"};  //显示的文本
 
      Container container=getContentPane();  //得到容器
      Box boxLayout=Box.createVerticalBox();  //创建一个垂直排列的Box
      boxLayout.setBorder(BorderFactory.createEmptyBorder(10,20,5,5));  //设置边界
      container.add(boxLayout);  //增加组件到容器上
      for (int i=0;i<5;i++){
        JLabel fontLabel=new JLabel();  //得到一个JLabel的实例
        fontLabel.setFont(fonts[i]);  //设置字体
        fontLabel.setText(text[i]);  //设置显示文本
        boxLayout.add(fontLabel);  //增加组件到Box上
      }
 
      setSize(380,180);  //设置窗口尺寸
      setVisible(true);  //设置窗口可ub视
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
   }
 
 
   public static void main(String args[]){
      new FontDemo();
   }
}
实线与虚线 实线与虚线, java实例100 实线与虚线
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
 
public class LineDemo extends JFrame{
 
    public LineDemo(){
        super("实线与虚线"); //调用父类构造函数      
        setSize(300,200); //设置窗口尺寸
        setVisible(true); //设置窗口可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
    }
     
    public void paint(Graphics g){ //绘制组件方法
        Graphics2D g2=(Graphics2D)g; //得到2D图形
        Dimension dim = this.getSize(); //得到组件尺寸
        g2.setColor(Color.white); //设置绘制颜色为白色
        g2.fillRect(0, 0, dim.width, dim.height); //填充整个组件
        g2.setColor(Color.black); //设置绘制颜色
        g2.drawLine(40,160,280,160); //绘制实线
        g2.drawLine(40,160,40,40);
        g2.drawString("0",30,165); //绘制字符串
        g2.drawString("100",16,50);
        g2.drawString("200",270,175);
         
        float[] dash={5,5}; //短划线图案
        BasicStroke bs = new BasicStroke(1,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f,dash,0.0f); //实例化新画刷
        g2.setStroke(bs); //设置新的画刷      
 
        g2.drawLine(40,160,100,120); //用新的画刷绘制虚线
        g2.drawLine(100,120,160,120);
        g2.drawLine(160,120,280,40);
 
    }
 
    public static void main(String[] args){
        new LineDemo();
    } 
}
密码验证框 密码验证框, java实例100 密码验证框
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class JPasswordFieldDemo extends JFrame {
    JTextField username;  //用户名输入框
   JPasswordField password;  //密码输入框
    JButton logonButton;  //登录按钮
    JButton cancelButton;  //退出按钮
 
   public JPasswordFieldDemo() {  //构造函数
 
    super("JPasswordField演示");  //调用父类构造函数
    Container container=getContentPane();  //得到容器
    container.setLayout(new GridLayout(3, 2, 2, 2));  //设置布局管理器
 
    username=new JTextField(16);  //初始化文本输入框,宽度为16列
    password=new JPasswordField(16);  //初始化密码输入框,宽度为16列
    logonButton=new JButton("登录");  //初始化登录按钮
    logonButton.addActionListener(  //登录按钮事件处理
        new ActionListener(){
        public void actionPerformed(ActionEvent evt){
            char[] pw=password.getPassword();  //得到密码
            String message="您的用户名:"+username.getText()+"\n您的密码:"+new String(pw);  //消息字符串
            JOptionPane.showMessageDialog(JPasswordFieldDemo.this, message);  //显示消息
       }
        });
        cancelButton=new JButton("退出");  //初始化退出按钮
        cancelButton.addActionListener(  //初始化按钮事件处理
            new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                System.exit(0);  //退出程序
           }
        });
 
       container.add(new JLabel("      用户名:"));  //增加组件
       container.add(username);
       container.add(new JLabel("      密码:"));
        container.add(password);
        container.add(logonButton);
        container.add(cancelButton);
        setResizable(false);  //不允许用户改变窗口大小
        setSize(300,120);  //设置窗口尺寸
        setVisible(true);  //设置窗口可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
    }
 
    public static void main(String[] args) {
        new JPasswordFieldDemo();
    }
}
圆形的按钮 圆形的按钮, java实例100 圆形的按钮
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
 
import javax.swing.*;
 
 
public class RoundButton extends JButton {
 
    public RoundButton(String label) {
        super(label);  //调用父类构造函数
        setContentAreaFilled(false);   //不自行绘制按钮背景
    }
 
 
    //绘制圆和标签
    protected void paintComponent(Graphics g) {
       if (getModel().isArmed()) {  //鼠标点击时
            g.setColor(Color.lightGray);  //颜色为灰色
        } else {
            g.setColor(getBackground());  //置按钮颜色
        }
        g.fillOval(0, 0, getSize().width, getSize().height);  //绘制圆
        super.paintComponent(g);  //调用父类函数,绘制其余部分
    }
 
 
    //绘制边框
   protected void paintBorder(Graphics g) {
       g.setColor(getForeground());  //设置边框颜色
       g.drawOval(0, 0, getSize().width-1, getSize().height-1);  //在边界上绘制一个椭圆
   }
 
}
圆形的按钮 圆形的按钮, java实例100 圆形的按钮
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
 
public class RoundButtonDemo extends JFrame{
 
    private int clickCount=0;  //记录安钮的点击次数
    private JButton button1;
    private JButton button2;
 
    public RoundButtonDemo()
    {
        button1 = new RoundButton("这是一个圆形按钮");  //初始化按钮一
 
        Dimension dim=button1.getPreferredSize();  //得到按钮一的最佳尺寸
        double maxsize=Math.max(dim.getHeight(),dim.getWidth());  //得到长宽中的最大值
        dim.setSize(maxsize,maxsize);  //更改长宽为长宽中的最大值
        button1.setPreferredSize(dim);  //设置最佳尺寸
 
        button2 = new RoundButton("点击了: "+clickCount+" 次");  //初始化按钮二
        button1.setBackground(Color.blue);  //设置按钮的背景颜色
        button2.setBackground(Color.pink);
        getContentPane().add(button1);  //增加组件
        getContentPane().add(button2);
        getContentPane().setLayout(new FlowLayout());  //设置布局管理器
 
        button2.addActionListener(new ActionListener(){  //铵钮二的事件处理
            public void actionPerformed(ActionEvent e){
                clickCount++;  //增加一次点击数
                button2.setText("点击了: "+clickCount+" 次");  //重新设置按钮二的标签
            }
        });
 
        setSize(300, 200);  //设置窗口尺寸
        setVisible(true);  //设置窗口可视
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
    }
 
    public static void main(String[] args) {
        new RoundButtonDemo();
    }
}
彩色列表框示例 彩色列表框示例, java实例100 彩色列表框示例
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (个人网页设计模板http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
 
//彩色列表框的Renderer,须实现接口ListCellRenderer
public class ColorRenderer extends JLabel implements ListCellRenderer {
 
    //实现接口中的getListCellRendererComponent方法
   public Component getListCellRendererComponent(JList list, Object obj, int row, boolean sel, boolean hasFocus) {
        if (hasFocus || sel) {   //设置选中时的边界
        setBorder(new MatteBorder(2, 10, 2, 10, list.getSelectionBackground()));
      }
      else {  //设置未选中时的边界
         setBorder(new MatteBorder(2, 10, 2, 10, list.getBackground()));
      }
      Color c=(Color)obj;  //得到该行的颜色值
      setForeground(c);  //设置颜色
      setText(c.toString());  //设置文本
        return this;
    }
}
彩色列表框示例 彩色列表框示例, java实例100 彩色列表框示例
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
 
//彩色列表框示例
 
public class JListDemo extends JFrame{
    Container container;  //容器
    JTextField selectedText;  //文本域,反映选择的颜色值
    JList list;  //列表框
    JPanel selectedColor;  //Panel,以选择的颜色为背景绘制
 
   public JListDemo(){  //构造函数
    container=getContentPane();  //得到容器
    container.setLayout(new BorderLayout());  //设置布局管理器,不是必须的,Container默认为BorderLayout
 
    Color[] colors={Color.orange,Color.pink,Color.red,Color.black,Color.blue,Color.cyan,Color.green,Color.lightGray};  //列表框内容
    list=new JList(colors);
        JScrollPane scrollPane = new JScrollPane(list);  //以list初始化滚动窗格
        selectedText=new JTextField(20);
        selectedColor=new JPanel();
        selectedColor.setPreferredSize(new Dimension(20,20));  //设置panel的首选尺寸
        container.add(selectedText,BorderLayout.NORTH);  //增加组件到容器上
    container.add(scrollPane,BorderLayout.CENTER);
    container.add(selectedColor,BorderLayout.SOUTH);
 
      list.setCellRenderer(new ColorRenderer());  //设置Renderer
      list.addListSelectionListener(  //事件处理
        new ListSelectionListener(){
           public void valueChanged(ListSelectionEvent event){  //选择值有改变
            Color c=(Color)list.getSelectedValue();  //得到选择的颜色
              selectedText.setText("选择颜色:"+" R="+c.getRed()+" G ="+c.getGreen()+" B="+c.getBlue());  //设置文本域文本
              selectedColor.setBackground(c);  //设置panel的颜色
           }
      });
 
    setSize(300,200);  //设置窗口尺寸
    setVisible(true);  //设置窗口可视
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
   }
 
 
   public static void main(String[] args){
      new JListDemo();
   }
}
控件的相互控制与消息传递 控件的相互控制与消息传递, java实例100 控件的相互控制与消息传递
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (java网络编程http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
//控件的相互控制与消息传递
 
public class ActionDemo extends JFrame{
    JTextField jtfName;  //名字输入域
    JTextArea jtaChat;  //显示聊天信息
    JTextArea jtaInput;  //输入消息
    JButton jbSend;  //发送消息按钮
    JButton jbLink;  //连接按牛
    JButton jbUnlink; //断开按牛
 
    public ActionDemo(){
        super("控件的相互控制");  //调用父类构造函数
 
        Container container=this.getContentPane();  //得到容器
        JPanel p=new JPanel();  //初始化一个面板
        jtfName=new JTextField(10);  //初始化名字输入域 
         
        Box box1=new Box(BoxLayout.X_AXIS);  //初始化一个Box
        p.add(new JLabel("昵称:"));  //增加昵称标签
        p.add(jtfName);  //增加名字输入域
        box1.add(jbLink);
        box1.add(jbUnlink);
      container.add(p,BorderLayout.NORTH);  //在容器上增加面板
      
      jtaChat=new JTextArea();  //初始化信息显示文本框
       
    container.add(new JScrollPane(jtaChat),BorderLayout.CENTER);  //在容器上增加信息显示文本框
 
        Box box=new Box(BoxLayout.X_AXIS);  //初始化一个Box
        jtaInput=new JTextArea(3,20);  //初始化消息输入域
        jbSend=new JButton();  //初始化发送按钮
 
         
        box.add(new JScrollPane(jtaInput));  //增加消息输入域
         
        box.add(jbSend);
        container.add(box,BorderLayout.SOUTH);  //在容器上增加box
 
         
     
 
       Action sendMessage = new AbstractAction() {  //发送消息Action
        public void actionPerformed(ActionEvent e){
            replaceMessage();  //更新消息显示框
            }
        };
        jtaInput.getInputMap().put(KeyStroke.getKeyStroke("ENTER"),"send");  //键盘事件处理,按受回车事件
        jtaInput.getActionMap().put("send",sendMessage);  //回车时的处理(调用发送消息Action)
 
        jbSend.setAction(sendMessage);  //设置命令为发送消息
        jbSend.setText("发送");  //设置按钮文本
       this.setLocation(300,300);
       setSize(400,200);  //设置窗口尺寸
       setVisible(true);  //设置窗口可视
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
    }
 
    private void replaceMessage(){
       String message=jtfName.getText()+"> "+jtaInput.getText()+"\n";  //得到消息文本
       jtaChat.insert(message,jtaChat.getDocument().getLength());  //插入消息到显示域未端
       jtaInput.setText("");  //清空输入消息域
    }
 
   public static void main(String[] args){
      new ActionDemo();
   }
}
控件的排布实例 java se, 图形界面, 控件的排布实例 控件的排布实例
import java.awt.*;
import javax.swing.*;
 
public class GridBagLayoutDemo extends JFrame {
 
   public GridBagLayoutDemo() {  //构造函数
    Container contentPane = getContentPane();  //得到容器
    contentPane.setLayout(new GridBagLayout());  //设置布局管理器
 
    JLabel labelName=new JLabel("姓名");  //姓名标签
    JLabel labelSex=new JLabel("性别");  //性别标签
    JLabel labelAddress=new JLabel("住址");  //住址标签
    JTextField textFieldName = new JTextField();  //性名文本域
    JTextField textFieldAddress = new JTextField(); //地址文本域
    JComboBox comboBoxSex = new JComboBox();  //性别组合框
    comboBoxSex.addItem("男");   //增加选择项
    comboBoxSex.addItem("女");
    JButton buttonConfirm=new JButton("确定");  //确定按钮
    JButton buttonCancel=new JButton("退出");  //退出按钮
 
    //增加各个组件
    contentPane.add(labelName,         new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
            ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0));
    contentPane.add(textFieldName,      new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0));
    contentPane.add(comboBoxSex,           new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0
            ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0));
    contentPane.add(labelSex,        new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
            ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 0), 0, 0));
    contentPane.add(buttonConfirm,      new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
            ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 3, 0), 0, 0));
    contentPane.add(buttonCancel,     new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
            ,GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 0, 3, 0), 0, 0));
    contentPane.add(labelAddress,     new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0));
    contentPane.add(textFieldAddress,     new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0
            ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0));
 
    setTitle("GridBagLayout 演示");  //设置窗口标题
    setSize(300,140);  //设置窗口尺寸
    setVisible(true);  //设置窗口可见
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
   }
 
   public static void main(String args[])   {
      new GridBagLayoutDemo();
   }
}
控件的排布实例 java se, 控件的排布实例 控件的排布实例
import java.awt.*;
 
    import javax.swing.*;
 
    public class BorderLayoutDemo extends JFrame{
 
       public static void main( String args[] ){  //构造函数
          Container container = getContentPane();  //得到容器
          container.setLayout( new BorderLayout() ); //设置布局管理器为Borderlayout
 
          container.add(new JButton("North"), BorderLayout.NORTH);  //增加按钮
          container.add(new JButton("South"), BorderLayout.SOUTH);
          container.add(new JButton("East"), BorderLayout.EAST);
          container.add(new JButton("West"), BorderLayout.WEST);
          container.add(new JButton("Center"), BorderLayout.CENTER);
 
          setTitle("BorderLayout 演示");  //设置窗口标题
          setSize(280,200);  //设置主窗口尺寸
          setVisible(true);  //设置主窗口可视
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
       }
 
       public static void main( String args[] ){
         new BorderLayoutDemo();
       }
    }
产生自己的控件2 产生自己的控件, java se, 图形界面 产生自己的控件
/*dkplus专业搜集和编写实用电脑软件教程,
*搜集各种软件资源和计算机周边,独立制作视频和ppt和音频微信公众号,
*点击进入 dkplus官方博客 (个人网页设计模板http://dkplus.iteye.com),
*微信搜索dkplus关注公众号可获取海量计算机周边资源。*/
 
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
 
//带图标下拉框的单元绘制器,从JLabel类扩展,实现ListCellRenderer接口
//Download by http://www.codefans.net
public class IconRenderer extends JLabel implements ListCellRenderer{
 
   public Component getListCellRendererComponent(JList list, Object obj, int row, boolean sel, boolean hasFocus) {
      Object[] cell = (Object[])obj;   //得到行的参数
      setIcon((Icon)cell[0]);  //设置图标
      setText(cell[1].toString()); //设置文本
      setToolTipText(cell[2].toString());  //设置提示文本
      setBorder(new LineBorder(Color.WHITE)); //设置边界
      if (sel){
        setForeground(Color.MAGENTA);  //如果选中了,设置文本颜色为品红色
      }
      else{
        setForeground(list.getForeground()); //如果未选中,设置文本颜色为默认色
      }
      return this;
   }
}
Global site tag (gtag.js) - Google Analytics