似乎业界的程序员都不喜欢用java来开发图形界面,但是因为跨平台的原因,对java的桌面编程非常的感兴趣,想使用它做出一套漂亮的图形界面。
此篇文章主要介绍,java下通过swing实现win8的磁力铁
原理:继承java的swing组件,对其进行功能的扩展
java swing界面的jframe中重生之大文豪,通过setUndecorated(true)方法可以去掉周围的边框,后果是我们没法拖动这个窗口了;以下代码提供了一种方式来解决这个问题:
- public class ShowMain{
- public static void main(String[] args) {
- MyFrame frame = new MyFrame();
- }
- }
- class MyFrame extends JFrame implements MouseListener,MouseMotionListener{
- JFrame frame;
- Container container;
- int x;
- int y;
- int tempX;
- int tempY;
- int winX;
- int winY;
- int oldX;
- int oldY;
- public MyFrame() {
- init();
- }
- public void init(){
- frame = this;
- container = frame.getContentPane();
- frame.setBounds(300, 300, 300, 300);
- container.setBackground(Color.BLUE);
- frame.setUndecorated(true);
- frame.setVisible(true);
- frame.addMouseListener(this);
- frame.addMouseMotionListener(this);
- }
- @Override
- public void mouseDragged(MouseEvent e) {
- Point point = e.getPoint();
- Rectangle rec = frame.getBounds();
- winX = (int)rec.getX();
- winY = (int)rec.getY();
- x = (int)point.getX();
- y = (int)point.getY();
- tempX = x - oldX;
- tempY = y - oldY;
- frame.setLocation((int)(winX + tempX), (int)(winY + tempY));
- }
- @Override
- public void mousePressed(MouseEvent e) {
- Rectangle rec = frame.getBounds();
- Point point = e.getPoint();
- tempX = (int)point.getX();
- tempY = (int)point.getY();
- oldX = (int)point.getX();
- oldY = (int)point.getY();
- }
- @Override
- public void mouseClicked(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseEntered(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseExited(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseReleased(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseMoved(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- }
运行截图(通过鼠标可以拖动一下的方块窗体):