java-支持鼠标拖动面板

package otherexample;

import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class PanelMove
{
 public static JFrame frm=new JFrame();
 public static void main(String[] args)
 {
 
  frm.setTitle("鼠标拖动面板");
  frm.setLayout(null);
  MyPanel mp=new MyPanel();
  frm.add(mp);
  frm.setSize(500,500);
  frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frm.setVisible(true);
    }
}
class Product extends JPanel
{
 JLabel pName=null;
 JLabel pNumber=null;
 JTextField tName=null;
 JTextField tNumber=null;
 public Product()
 {
  pName=new JLabel("名称:");
  pNumber=new JLabel("数量:");
  tName=new JTextField(3);
  tNumber=new JTextField(3);
  add(pName);
  add(tName);
  add(pNumber);
  add(tNumber);
  setBackground(Color.magenta);
 }
}

class MyPanel extends JPanel
{
 int focusx=0;//下面要做的是实现拖拉功能,设定焦点坐标 
    int focusy=0;
    JLabel lab1=null;
    JLabel lab2=null;


 public MyPanel()
 {
  //在java中,标签可以用htnl的属性,但是不都是,比如你不可以设置左右滚动的字体
  lab1=new JLabel("<html><font color=white>zhan</font></html>");
  add(lab1);
  lab2=new JLabel("<html><font color=white>深圳</font></html>");
  add(lab2);

  setBackground(Color.red);
  setBorder(BorderFactory.createRaisedBevelBorder());//使面板有边框,突出显示
 
        //下面四行都是进行拖动处理
  setBounds(new Rectangle(80,80,80,100));//要进行拖拉处理,将其设为长方体
  addMouseListener(new   MouseProcess(){});  //加入监听器
        addMouseMotionListener(new   MouseMotionProcess());
  setLocale(java.util.Locale.getDefault());
 }
 
    //以下做的是面板移动处理内部类
 private class MouseProcess extends MouseAdapter 
    { 
        public void mouseClicked(MouseEvent e) 
        {
        } 
        public   void   mousePressed(MouseEvent   e) 
        { 
            focusx=e.getX(); //将鼠标的坐标赋予焦点X
            focusy=e.getY(); //将鼠标的坐标赋予焦点Y
        } 
    }
 private class MouseMotionProcess extends MouseMotionAdapter 
    {
       public void mouseDragged(MouseEvent e)   //拖动时发生的事件
       { 
            Container container=MyPanel.this.getParent(); 
            int w=container.getWidth(); 
            int h=container.getHeight(); 

            int x=MyPanel.this.getX()+e.getX()-focusx; 
            int y=MyPanel.this.getY()+e.getY()-focusy; 

            if(x+MyPanel.this.getWidth()>w)   x=w-MyPanel.this.getWidth(); 
            if(y+MyPanel.this.getHeight()>h)   y=h-MyPanel.this.getHeight(); 
            if(x<0)  x=0; 
            if(y<0)  y=0; 

            MyPanel.this.setLocation(x,y);
        } 
  }
}

java-支持鼠标拖动面板_第1张图片

你可能感兴趣的:(java,String,null,Class,import)