主要通过调用api接口来实现.
主要使用了
MouseMotionAdapter的public void mouseDragged(MouseEvent e)
和MouseListener的按压和释放方法
本来是直接在JPanel的paint方法绘制,效果还可以,但是当JPanel中含有组件时,屏幕渲染太慢,会显得很闪烁.
最终,发现在里面使用一个JPanel充当框选框是效果最好的
package com.boost; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; public class DragFrame2 extends JFrame { public JPanel paintPanel; private Point p; public Point p2; JPanel jback = new JPanel(); public DragFrame2(){ super("drag build2"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(new Point(500,200)); setSize(800+16,600+39); setPreferredSize(new Dimension(800,600)); setLayout(null); jback.setBackground(new Color(0xab,0xcd,0xef,0x55)); jback.setBounds(0,0,0,0); jback.setBorder(new LineBorder(Color.BLACK)); paintPanel = new JPanel(null); paintPanel.add(jback); paintPanel.setSize(800,600); paintPanel.setPreferredSize(new Dimension(800,600)); JButton j1 = new JButton("hello world"); j1.setBounds(100,40,100,40); paintPanel.add(j1); add(paintPanel); addListeners(); } public void addListeners(){ paintPanel.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { super.mouseDragged(e); p2 = e.getPoint(); if(p != null){ int x1 = (int) p.getX(); int y1 = (int) p.getY(); int x2 = (int) p2.getX(); int y2 = (int) p2.getY(); int x = (int) Math.abs(DragFrame2.this.p2.getX()-DragFrame2.this.p.getX()); int y = (int) Math.abs(DragFrame2.this.p2.getY()-DragFrame2.this.p.getY()); int px,py; px = Math.min(x2, x1); py = Math.min(y2, y1); jback.setBounds(px,py,x,y); paintPanel.repaint(); } } @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return super.toString(); } @Override protected void finalize() throws Throwable { super.finalize(); } }); paintPanel.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { DragFrame2.this.p = e.getPoint(); System.out.println("Click Listener PRESS"+p); } @Override public void mouseReleased(MouseEvent e) { DragFrame2.this.p = null; DragFrame2.this.p2 = null; jback.setBounds(0,0,0,0); paintPanel.repaint(); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); } public static void main(String[] args) { DragFrame2 df = new DragFrame2(); df.setVisible(true); } }