Friday, July 13, 2012

JFrame to JApplet Conversion Project | Dragging JButton

Design Free Website with Free Internet Marketing Tools

Program Description:

This is a simple Java project, a conversion project from JFrame to JApplet which was requested by someone in my Fan Page. I am trying to make the code as simple as possible and as short as possible so it can be understood easily.

Output:




Original Code:

import java.awt.event.*;
import javax.swing.*;

public class Demo extends JFrame implements MouseMotionListener{
JButton btn;
Demo(){
setSize(300, 300);
setVisible(true);
btn = new JButton("Drag me");
getContentPane().setLayout(null);
add(btn);
btn.setBounds(50, 50, 100, 40);
btn.addMouseMotionListener(this);
}
public static void main(String[] args){
new Demo();
}
public void mouseDragged(MouseEvent e) {
int x=(int) getMousePosition().getX();
int y=(int) getMousePosition().getY();
btn.setLocation(x, y);
}
public void mouseMoved(MouseEvent e) {

}

}

Code:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class DemoApplet extends JApplet implements MouseMotionListener{
 JButton btn = new JButton("Drag Me");
 
 public void init() {
  btn.setBounds(40,40,100,40);
  Container pane = getContentPane();
  FlowLayout flow = new FlowLayout();
  pane.setLayout(flow);
  pane.add(btn);
  btn.addMouseMotionListener(this);
 }
 
 public void mouseDragged(MouseEvent e) {
  int x=(int) getMousePosition().getX();
  int y=(int) getMousePosition().getY();
  btn.setLocation(x, y);
 }
 public void mouseMoved(MouseEvent e) {
 }
}

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hostgator Discount Code