Buscar este blog

Mostrando entradas con la etiqueta JAVA. Mostrar todas las entradas
Mostrando entradas con la etiqueta JAVA. Mostrar todas las entradas

jueves, 6 de junio de 2013

SUMAR TRES DIMENSIONES, MIL PERSONAS,LIST SET, TRON, MISTERMIND PROGRAMADO EN JAVA.

EJERCICIO PARA SUMAR UNA MATRIZ DE TRES DIMENSIONES:
package ejercicio130517;
public class matriz3d {
public static void main(String[] args) {
int i, j, k;
int matriz[][][] = new int [3] [3] [3];
for(i = 0; i < matriz.length; i++);{
for(j = 0; j < matriz[i].length; j++);{
for(k = 0; k < matriz[i][j].length; k++);{
matriz[i][j][k] = i;
System.out.println(i);
}}} }}
EJERCICIO PARA CONTABILIZAR "MIL PERSONAS"
package ejercicio130521;
public class milpersonas {
public static void main(String[] args) {
int m = 10;
for (int i=0; i<m; i++){
for (int j=0; j<m; j++){
for (int k=0; k<m; k++){
System.out.println("PERSONA "+i+", FAMILIA DE PERSONA "+j+",AMIGO DE FAMILIA DE PERSONA " +k);
}}}}}
EJERCICIO LIST SET
package ejercicio130522;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


public class ListSet {

  public static void main(String[] args) {

    //LIST Y SET
      
      ArrayList<String> yes = new ArrayList();
      List<String> yeso = new ArrayList<String>();
      yeso.add("Placido Domingo");
      yeso.add("Cesaria Evora");
      yeso.add("Runa Yacu");
      yeso.add("Placido Domingo");

      // RECORRER MEDIANTE UN FOR
      for (String e:yeso)
        System.out.println(e);
      
      // USO DEL ITERADOR
      Iterator p = yeso.iterator();
      while(p.hasNext()){
        System.out.println(p.next());
      }
     System.out.println();
      Set<String> yeset = new HashSet<String>();
      yeset.add("Placido Domingo");
      yeset.add("Cesaria Evora");
      yeset.add("Runa Yacu");
      yeset.add("Placido Domingo");
      for(String e:yeset)
        System.out.println(e);
}}

TRON DE 2 SERPIENTES EN JAVA CON SALTOS ALEATORIOS
package ejercicio130528;

import java.awt.Image;
import java.util.ArrayList;
public class Animation {
private ArrayList scenes;
private int sceneIndex;
private long movieTime;
private long totalTime;
public Animation(){
scenes = new ArrayList();
totalTime = 0;
start();
}
public synchronized void addScene(Image i, long t){
totalTime += t;
scenes.add(new oneScene(i,totalTime));
}
public synchronized void start(){
movieTime = 0;
sceneIndex = 0;
}
public synchronized void update(long timePassed){
if(scenes.size()>1){
movieTime += timePassed;
if(movieTime>=totalTime){
movieTime = 0;
sceneIndex = 0;
}
while(movieTime > getScene(sceneIndex).endTime){
sceneIndex++;
}
}
}
public synchronized Image getImage(){
if(scenes.size()==0)
{
return null;
}else{
return getScene(sceneIndex).pic;
}
}
private oneScene getScene(int x){
return (oneScene)scenes.get(x);
}
private class oneScene{
Image pic;
long endTime;
public oneScene(Image pic,long endTime){
this.pic = pic;
this.endTime = endTime;
}}}
package ejercicio130528;
import java.awt.*;
import java.awt.image.BufferedImage;

public abstract class Core {

private static final DisplayMode modes[] = 
{
//new DisplayMode(1920,1080,32,0),
new DisplayMode(1680,1050,32,0),
//new DisplayMode(1280,1024,32,0),
new DisplayMode(800,600,32,0),
new DisplayMode(800,600,24,0),
new DisplayMode(800,600,16,0),
new DisplayMode(640,480,32,0),
new DisplayMode(640,480,24,0),
new DisplayMode(640,480,16,0),
};
private boolean running;
protected ScreenManager sm;
public void stop(){
running = false;
}
public void run(){
try{
init();
gameLoop();
}finally{
sm.restoreScreen();
}
}
public void init(){
sm = new ScreenManager();
DisplayMode dm = sm.findFirstCompatibaleMode(modes);
sm.setFullScreen(dm);
Window w = sm.getFullScreenWindow();
w.setFont(new Font("Arial",Font.PLAIN,20));
w.setBackground(Color.WHITE);
w.setForeground(Color.RED);
w.setCursor(w.getToolkit().createCustomCursor(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), new Point(0, 0),"null")); 
running = true;
}
public void gameLoop(){
long startTime = System.currentTimeMillis();
long cumTime = startTime;
while (running){
long timePassed = System.currentTimeMillis()-cumTime;
cumTime+= timePassed;
update(timePassed);
Graphics2D g = sm.getGraphics();
draw(g);
g.dispose();
sm.update();
try{
Thread.sleep(20);
}catch(Exception ex){}
}
}
public void update(long timePassed){}
public abstract void draw(Graphics2D g);
}
package ejercicio130528;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class ScreenManager {
private GraphicsDevice vc;
public ScreenManager(){
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = e.getDefaultScreenDevice();
}
public DisplayMode[] getCompatibleDisplayModes(){
return vc.getDisplayModes();
}
public DisplayMode findFirstCompatibaleMode(DisplayMode[] modes){
DisplayMode goodModes[] = vc.getDisplayModes();
for(int x = 0; x<modes.length;x++){
for(int y = 0;y<goodModes.length;y++){
if(displayModesMatch(modes[x],goodModes[y])){
return modes[x];
}
}
}
return null;
}
public DisplayMode getCurrentDM(){
return vc.getDisplayMode();
}
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2){
if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
return false;
}
if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){
return false;
}
if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){
return false;
}
return true;
}
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true);
f.setIgnoreRepaint(true);
f.setResizable(false);
vc.setFullScreenWindow(f);
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch(Exception ex){}
f.createBufferStrategy(2);
}
}
public Graphics2D getGraphics(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy bs = w.getBufferStrategy();
return (Graphics2D)bs.getDrawGraphics();
}
else{
return null;
}
}
public void update(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy bs = w.getBufferStrategy();
if(!bs.contentsLost()){
bs.show();
}}}
public Window getFullScreenWindow(){
return vc.getFullScreenWindow();}
public int getWidth(){
Window w = vc.getFullScreenWindow();
if(w != null){
return w.getWidth();
}else{
return 0;
}
}
public int getHeight(){
Window w = vc.getFullScreenWindow();
if(w != null){
return w.getHeight();
}else{
return 0;
}}
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if(w != null){
w.dispose();
}
vc.setFullScreenWindow(null);
}
public BufferedImage createCompatibaleimage(int w, int h, int t){
Window win = vc.getFullScreenWindow();
if(win != null){
GraphicsConfiguration gc = win.getGraphicsConfiguration();
return gc.createCompatibleImage(w,h,t);
}else{
return null;
}}}
package ejercicio130528;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;

public class yourclass extends Core implements KeyListener, MouseListener,
MouseMotionListener {
int centrex1 = 40;
int centrey1 = 40;
int centrex2 = 600;
int centrey2 = 440;
int currentDirection1 = 1; 
int currentDirection2 = 3;
int moveAmount = 1; //velocidad de las serpientes
ArrayList<Integer> pathx1 = new ArrayList();
ArrayList<Integer> pathy1 = new ArrayList();
ArrayList<Integer> pathx2 = new ArrayList();
ArrayList<Integer> pathy2 = new ArrayList();

public void init() {
super.init();

Window w = sm.getFullScreenWindow();
w.addKeyListener(this);
w.addMouseListener(this);
w.addMouseMotionListener(this);
}

public static void main(String[] args) {
new yourclass().run();
}

public void draw(Graphics2D g) {
switch(currentDirection1){
case 0:
if (centrey1>0){
centrey1-=moveAmount;
} else {
centrey1 = sm.getHeight();
}
break;
case 1:
if (centrex1 < sm.getWidth()){
centrex1+=moveAmount;
} else {
centrex1 = 0;
}
break;
case 2:
if (centrey1 < sm.getHeight()){
centrey1+=moveAmount;
} else {
centrey1 = 0;
}
break;
case 3:
if (centrex1>0){
centrex1-=moveAmount;
} else {
centrex1 = sm.getWidth();
}
break;
}
switch(currentDirection2){
case 0:
if (centrey2>0){
centrey2-=moveAmount;
} else {
centrey2 = sm.getHeight();
}
break;
case 1:
if (centrex2 < sm.getWidth()){
centrex2+=moveAmount;
} else {
centrex2 = 0;
}
break;
case 2:
if (centrey2 < sm.getHeight()){
centrey2+=moveAmount;
} else {
centrey2 = 0;
}
break;
case 3:
if (centrex2>0){
centrex2-=moveAmount;
} else {
centrex2 = sm.getWidth();
}
break;
}
   for (int x = 0;x<pathx1.size();x++){
    if (((centrex1 == pathx1.get(x)) && (centrey1 == pathy1.get(x))) || ((centrex2 == pathx2.get(x)) && (centrey2 == pathy2.get(x))) || ((centrex1 == pathx2.get(x)) && (centrey1 == pathy2.get(x))) || ((centrex2 == pathx1.get(x)) && (centrey2 == pathy1.get(x)))){
    System.exit(0);
    }
   }//colisiones
pathx1.add(centrex1);
pathy1.add(centrey1);
pathx2.add(centrex2);
pathy2.add(centrey2);
g.setColor(Color.BLACK);
g.fillRect(0, 0, sm.getWidth(), sm.getHeight());
for (int x = 0;x<pathx1.size();x++){
int mh= (int)(Math.random()*6 + 1) ;
if (mh%2==0){
}
else {
g.setColor(Color.green);
g.fillRect(pathx1.get(x), pathy1.get(x), 1, 1);
g.setColor(Color.red);
g.fillRect(pathx2.get(x), pathy2.get(x), 1, 1);
}
}
}

public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
if (currentDirection1 != 2){
currentDirection1 = 0;
}
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (currentDirection1 != 0){
currentDirection1 = 2;
}
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (currentDirection1 != 3){
currentDirection1 = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (currentDirection1 != 1){
currentDirection1 = 3;
}
}
if (e.getKeyCode() == KeyEvent.VK_W){
if (currentDirection2 != 2){
currentDirection2 = 0;
}
} else if (e.getKeyCode() == KeyEvent.VK_S) {
if (currentDirection2 != 0){
currentDirection2 = 2;
}
} else if (e.getKeyCode() == KeyEvent.VK_D) {
if (currentDirection2 != 3){
currentDirection2 = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_A) {
if (currentDirection2 != 1){
currentDirection2 = 3;
}}}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent arg0) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {

}
}

MISTERMIND DE 5 FICHAS (COLORES O NUMEROS) EN JAVA
package ejercicio130604;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MM {
static String f = "";

public static void main(String[] args) {
int s = 0;
String n = "";
String diff = "";
boolean ans = false;
int[] d = new int[5]; //habia un 4
int[] pos = new int[5]; //habia un 4
pos[0] = (int) (Math.random() * 100);
pos[1] = (int) (Math.random() * 100);
pos[2] = (int) (Math.random() * 100);
pos[3] = (int) (Math.random() * 100);
pos[4] = (int) (Math.random() * 100); //esta línea no estaba
f = readLine("Welcome to MasterMind by Greg Cawthorne!\nIn this game you attempt to crack a code with only the aid of minor hints and you own ingenuity!\nPress enter to begin! ");
f = readLine("Would you like to play with letters (1) or numbers (2)? ");
do {
if (f.equals("letters") || f.equals("1")) {
diff = "letters";
ans = true;
System.out
.println("The code will be made up 5 letters of either R,G,B,Y,P,T "); //habia 4 letters
} else if (f.equals("numbers") || f.equals("2")) {
diff = "numbers";
ans = true;
System.out
.println("The code will be made up of 5 numbers of either 1,2,3,4,5,6 ");   //habia 4 numbers
} else {
f = readLine("Sorry, I didn't quite get that. Would you like to play with letters (1) or numbers (2)? ");
}
} while (ans == false);
for (int x = 0; x <= 4; x++) { //había x<=3
if (pos[x] <= 17) {
d[x] = 1;
} else if (pos[x] <= 34) {
d[x] = 2;
} else if (pos[x] <= 51) {
d[x] = 3;
} else if (pos[x] <= 68) {
d[x] = 4;
} else if (pos[x] <= 85) {
d[x] = 5;
} else if (pos[x] <= 100) {
d[x] = 6;
}}
if (diff.equals("numbers")) {
n = "numbers either 1,2,3,4,5 or 6";
} else if (diff.equals("letters")) {
n = "letters either R,B,G,Y,P or T all caps";
}

System.out.println("The computer has thought of his sequence.");
if(diff == "letters"){
check(d, n, s);
} else if (diff == "numbers"){
check2(n, d, s);
}
}

public static void check(int[] d, String n, int s) {
int count2= 0;
String r = "R";
String b = "B";
String g = "G";
String y = "Y";
String p = "P";
String tq = "T";
String f = "";
boolean z = false;
int v = 0;
f = readLine("Take a guess! ");
if ((f.length() == 5) //había if ((f.length() == 4)
&& (f.charAt(0) == r.charAt(0) || f.charAt(0) == b.charAt(0)
|| f.charAt(0) == g.charAt(0)
|| f.charAt(0) == y.charAt(0)
|| f.charAt(0) == p.charAt(0) || f.charAt(0) == tq
.charAt(0))
&& (f.charAt(1) == r.charAt(0) || f.charAt(1) == b.charAt(0)
|| f.charAt(1) == g.charAt(0)
|| f.charAt(1) == y.charAt(0)
|| f.charAt(1) == p.charAt(0) || f.charAt(1) == tq
.charAt(0))
&& (f.charAt(2) == r.charAt(0) || f.charAt(2) == b.charAt(0)
|| f.charAt(2) == g.charAt(0)
|| f.charAt(2) == y.charAt(0)
|| f.charAt(2) == tq.charAt(0) || f.charAt(2) == p
.charAt(0))
&& (f.charAt(3) == r.charAt(0) || f.charAt(3) == b.charAt(0)
|| f.charAt(3) == g.charAt(0)
|| f.charAt(3) == y.charAt(0)
|| f.charAt(3) == tq.charAt(0) || f.charAt(3) == p.charAt(0))
//estas cuatro lineas de abajo no estaban
&& (f.charAt(4) == r.charAt(0) || f.charAt(4) == b.charAt(0)
|| f.charAt(4) == g.charAt(0)
|| f.charAt(4) == y.charAt(0)
|| f.charAt(4) == tq.charAt(0) || f.charAt(4) == p.charAt(0))
) {
z = true;
System.out.println();
s++;
int chin[] = new int[6];
int chin2[] = new int[6];
char bin[] = new char[6];
bin[0] = 'R'; bin[1] = 'B'; bin[2] = 'G'; bin[3] = 'Y'; bin[4] = 'P'; bin[5] = 'T';
char a[] = new char[5]; //había char a[] = new char[4];
int t[] = new int[5]; //había int t[] = new int[4];
for (int x = 0;x<5;x++){ //había for (int x = 0;x<4;x++){
a[x] = (f.charAt(x));
}
for (int eye = 0; eye< 5;eye++){ //había for (int eye = 0; eye< 4;eye++){
for (int tim = 0; tim<6;tim++){
if (a[eye] == bin[tim]){
t[eye] = tim +1;
}}
}for (int x = 0;x<5;x++){ //había }for (int x = 0;x<4;x++){
if (t[x] == 1){
chin[0] = chin[0]+1;
} else if (t[x] == 2){
chin[1] = chin[1]+1;
} else if (t[x] == 3){
chin[2] = chin[2]+1;
} else if (t[x] == 4){
chin[3] = chin[3]+1;
} else if (t[x] == 5){
chin[4] = chin[4]+1;
} else if (t[x] == 6){
chin[5] = chin[5]+1;
}
if (d[x] == 1){
chin2[0] = chin2[0]+1;
} else if (d[x] == 2){
chin2[1] = chin2[1]+1;
} else if (d[x] == 3){
chin2[2] = chin2[2]+1;
} else if (d[x] == 4){
chin2[3] = chin2[3]+1;
} else if (d[x] == 5){
chin2[4] = chin2[4]+1;
} else if (d[x] == 6){
chin2[5] = chin2[5]+1;
}
}
for (int x = 0; x <= 4; x++) { //había for (int x = 0; x <= 3; x++) {
if (d[x] == t[x]) {
v++;
}
}
for (int x = 0;x<6;x++){
if (chin[x] <= chin2[x]){
count2 = count2 + chin[x];
} else {
count2 = count2 + chin2[x]; }
} count2 = count2 - v;
}
if (z == false) {
System.out.println("Invalid guess. Please guess four " + n
+ " with no spaces. :)");
} else { 
System.out.println("You guessed: " + f);
System.out.println("There are "+v+" letters in the right place,\nand "+count2+" other letters which are right, but in the wrong place.");
}
if (v == 4) {
System.out.print("Well done you cracked the code in " + s
+ " attempts!\n");
do{ f = readLine("Do you want to play again? ");
if (f.equals("yes") || f.equals("y") || f.equals("YES")){
main(null);
} else if (f.equals("no") || f.equals("n") || f.equals("NO")){
System.out.println("I hope you enjoyed MasterMind by Greg Cawthorne!");
System.exit(0);
} else {
System.out.print("Sorry I didn't quite get that. ");
z = false;
}} while (z == false);
} check(d, n, s);
}

public static void check2(String n, int[] d, int s){
int count2 = 0;
boolean z = false;
int v = 0;
String one = "1";
String two = "2";
String three = "3";
String four = "4";
String five = "5";
String six = "6";
f = readLine("Take a guess! ");
//había if((f.length() == 4) && (f.charAt(0) == one.charAt(0) || f.charAt(0) == two.charAt(0) || f.charAt(0) == three.charAt(0)

if((f.length() == 5) && (f.charAt(0) == one.charAt(0) || f.charAt(0) == two.charAt(0) || f.charAt(0) == three.charAt(0)
|| f.charAt(0) == four.charAt(0) || f.charAt(0) == five.charAt(0) || f.charAt(0) == six.charAt(0))
&& (f.charAt(1) == one.charAt(0) || f.charAt(1) == two.charAt(0)
|| f.charAt(1) == three.charAt(0)
|| f.charAt(1) == four.charAt(0)
|| f.charAt(1) == five.charAt(0) || f.charAt(1) == six.charAt(0))
&& (f.charAt(2) == one.charAt(0) || f.charAt(2) == two.charAt(0)
|| f.charAt(2) == three.charAt(0)
|| f.charAt(2) == four.charAt(0)
|| f.charAt(2) == five.charAt(0) || f.charAt(2) == six.charAt(0))
&& (f.charAt(3) == one.charAt(0) || f.charAt(3) == two.charAt(0)
|| f.charAt(3) == three.charAt(0)
|| f.charAt(3) == four.charAt(0)
|| f.charAt(3) == five.charAt(0) || f.charAt(3) == six.charAt(0))
//estas cuatro lineas de abajo no estaban
&& (f.charAt(4) == one.charAt(0) || f.charAt(4) == two.charAt(0)
|| f.charAt(4) == three.charAt(0)
|| f.charAt(4) == four.charAt(0)
|| f.charAt(4) == five.charAt(0) || f.charAt(4) == six.charAt(0))
){
z = true;
System.out.println();
s++;
int chin[] = new int[6];
int chin2[] = new int[6];
String a[] = new String[5]; //había String a[] = new String[4];
int t[] = new int[5]; //había int t[] = new int[4];
for (int x = 0;x<=4;x++){ //había for (int x = 0;x<=3;x++){
a[x] = String.valueOf(f.charAt(x));
t[x] = Integer.parseInt(a[x]);
if (t[x] == 1){
chin[0] = chin[0]+1;
} else if (t[x] == 2){
chin[1] = chin[1]+1;
} else if (t[x] == 3){
chin[2] = chin[2]+1;
} else if (t[x] == 4){
chin[3] = chin[3]+1;
} else if (t[x] == 5){
chin[4] = chin[4]+1;
} else if (t[x] == 6){
chin[5] = chin[5]+1;
}
if (d[x] == 1){
chin2[0] = chin2[0]+1;
} else if (d[x] == 2){
chin2[1] = chin2[1]+1;
} else if (d[x] == 3){
chin2[2] = chin2[2]+1;
} else if (d[x] == 4){
chin2[3] = chin2[3]+1;
} else if (d[x] == 5){
chin2[4] = chin2[4]+1;
} else if (d[x] == 6){
chin2[5] = chin2[5]+1;
}
}
System.out.println("You guessed: " + f);
for (int x = 0; x <= 4; x++) { // había for (int x = 0; x <= 3; x++) {
if (d[x] == t[x]) {
v++;
}
}
for (int x = 0;x<6;x++){
if (chin[x] <= chin2[x]){
count2 = count2 + chin[x];
} else {
count2 = count2 + chin2[x]; }
} count2 = count2 - v;
}
if (z == false) {
System.out.println("Invalid guess. Please guess five " + n
+ " with no spaces. :)");
} else { 
System.out.println("There are "+v+" numbers in the right place,\nand "+count2+" other numbers which are right, but in the wrong place.");
}
if (v == 5) { //había if (v == 4) {
System.out.print("Well done you cracked the code in " + s
+ " attempts!\n");
do{ f = readLine("Do you want to play again? ");
if (f.equals("yes") || f.equals("y") || f.equals("YES")){
main(null);
} else if (f.equals("no") || f.equals("n") || f.equals("NO")){
System.out.println("I hope you enjoyed MasterMind by Greg Cawthorne!");
System.exit(0);
} else {
System.out.print("Sorry I didn't quite get that. ");
z = false;
}} while (z == false);
} check2(n, d, s);
}
public static String readLine(String prompt) {
String input = "";
System.out.print(prompt);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {

input = br.readLine();

} catch (IOException ioe) {
}
return input;
}
}



jueves, 23 de mayo de 2013

TECLADO JAVA ENTORNO GRAFICO

package editor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class Editor extends JFrame implements MouseListener{
    String firstRow[] = {"~","1","2","3","4","5","6","7","8","9","0","-","+","<<<<<"};
    String secondRow[] = {"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]","\\"};
    String thirdRow[] = {"Caps","A","S","D","F","G","H","J","K","L",":","\"","Enter"};
    String fourthRow[] = {"Shift","Z","X","C","V","B","N","M",",",".","?","   ^" };
    String fifthRow[]={"      " ,"<" ,"\\/",">" };
    String noShift="`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./";
    String specialChars ="~-+[]\\;',.?";
   
    JButton first[];
    JButton second[];
    JButton third[];
    JButton fourth[];
    JButton fifth[];
    Color cc = new JButton().getBackground();
    JTextArea  text;
    Boolean mayusculas = false;

   
    public static void main(String[] args) {
        new Editor().setVisible(true);
    }

    public Editor()
    {
        this.setResizable(false);
         this.getContentPane().setPreferredSize(new Dimension(1000,600));
        this.setLocation(50,50);
        iniciar();
    }

    private void iniciar()
    {

        text = new JTextArea();
        text.setPreferredSize(new Dimension(800,200));
        JLabel info = new JLabel("");
        setLayout(new BorderLayout());
        JPanel jpNorth = new JPanel();
        JPanel jpCenter = new JPanel();
        JPanel jpKeyboard = new JPanel();
        JPanel jpNote = new JPanel();
        add( jpNorth, BorderLayout.NORTH);
        add( jpNote);
        add( jpCenter, BorderLayout.CENTER);
        add(jpKeyboard, BorderLayout.SOUTH);

        jpNorth.setLayout(new BorderLayout());
        jpNorth.add(info, BorderLayout.WEST);
        jpNorth.add(info, BorderLayout.SOUTH);

        jpCenter.setLayout( new BorderLayout());
        jpCenter.add(text, BorderLayout.WEST);
        jpCenter.add(text, BorderLayout.CENTER);

        jpKeyboard.setLayout(new GridLayout(5,1));
        pack();

        first = new JButton[firstRow.length];
        JPanel p = new JPanel(new GridLayout(1, firstRow.length));
        for(int i = 0; i < firstRow.length; ++i)
        {
            JButton b= new JButton(firstRow[i]);
            b.setPreferredSize(new Dimension(100,50));
            first[i] = b;
            first[i].addMouseListener(this);
            p.add(first[i]);
        }
        jpKeyboard.add(p);
        second = new JButton[secondRow.length];
        p = new JPanel(new GridLayout(1, secondRow.length));
        for(int i = 0; i < secondRow.length; ++i)
        {
            second[i] = new JButton(secondRow[i]);
            second[i].addMouseListener(this);
            p.add(second[i]);

        }
        jpKeyboard.add(p);
        third = new JButton[thirdRow.length];
        p = new JPanel(new GridLayout(1, thirdRow.length));
        for(int i = 0; i < thirdRow.length; ++i)
        {
            third[i] = new JButton(thirdRow[i]);
            third[i].addMouseListener(this);
            p.add(third[i]);
        }
        jpKeyboard.add(p);
        fourth = new JButton[fourthRow.length];
        p = new JPanel(new GridLayout(1, fourthRow.length));
        for(int i = 0; i < fourthRow.length; ++i)
        {
            fourth[i] = new JButton(fourthRow[i]);
            fourth[i].addMouseListener(this);
            p.add(fourth[i]);
            if(i==fourthRow.length-2)
                p.add(new JPanel());

        }
        p.add(new JPanel());
        jpKeyboard.add(p);
        fifth = new JButton[fifthRow.length];
        p = new JPanel(new GridLayout(1, fifthRow.length));
        for(int i = 0; i < 1; ++i)
        {
            JPanel  spacePanel = new JPanel();
            p.add(spacePanel);
        }
        for(int i = 0; i < fifthRow.length; ++i)
        {
            if(i==1)
            {
                JButton b = new JButton(fifthRow[i]);
                b.setPreferredSize(new Dimension(400,10));
                b.setBounds(10, 10, 600, 100);
                fifth[i]=b;
                fifth[i].addMouseListener(this);
                p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());
            }
            else
            {
                fifth[i]=new JButton(fifthRow[i]);
                fifth[i].addMouseListener(this);
            }
            if(i==0)
            {
                   JPanel  spacePanel = new JPanel();
                   p.add(spacePanel);
            }
            p.add(fifth[i]);
        }
        jpKeyboard.add(p);
        }

    @Override
    public void mouseClicked(MouseEvent e) {
            JButton btn = (JButton) e.getSource();
            switch(btn.getText()) {
            case "Enter":
            case "\\/":
                text.setText(""+text.getText()+btn.getText()+"\n");
                break;
               
            case "<<<<<":
               String sCadena = text.getText();
               text.setText(sCadena.substring(0,text.getDocument().getLength()-1));
               break;
            case ">":          
                 text.grabFocus();
                break;
            case "<":
                    text.grabFocus();
                    int i = text.getDocument().getLength();
                    text.setCaretPosition(i - 1);
                    break;
              
            case "Caps":
            case "Shift":
                if (mayusculas){
                    mayusculas = false;
                    btn.setBackground(cc);               
                } else{
                mayusculas = true;
                btn.setBackground(Color.DARK_GRAY);
                }
                break;

               
            default:
                if (!mayusculas) {
                    String texto = (btn.getText()).toLowerCase();
                    text.setText(""+text.getText()+texto);   
                } else {
                    text.setText(""+text.getText()+btn.getText());
                }
            }
           
        }


    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    }

miércoles, 1 de mayo de 2013

TEMA 8 Eventos en Java.


Problema 1:
Confeccionar una ventana que muestre un botón. Cuando se presione finalizar la ejecución del
programa Java.
Programa:
import javax.swing.*;
import java.awt.event.*;
public class Formulario extends JFrame implements ActionListener {
JButton boton1;
public Formulario() {
setLayout(null);
boton1=new JButton("Finalizar");
boton1.setBounds(300,250,100,30);
add(boton1);
boton1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==boton1) {
System.exit(0);
}
}
public static void main(String[] ar) {
Formulario formulario1=new Formulario();
formulario1.setBounds(0,0,450,350);
formulario1.setVisible(true);
}
}
La mecánica para atrapar el clic del objeto de la clase JButton se hace mediante la implementación de
una interface. Una interface es un protocolo que permite la comunicación entre dos clases. Una
interface contiene uno o más cabecera de métodos, pero no su implementación.
Por ejemplo la interface ActionListener tiene la siguiente estructura:
interface ActionListener {
public void actionPerformed(ActionEvent e) {
}
Luego las clases que implementen la interface ActionListener deberán especificar el algoritmo del
método actionPerformed.
Mediante el concepto de interfaces podemos hacer que desde la clase JButton se puede llamar a un
método que implementamos en nuestra clase.
Para indicar que una clase implementará una interface lo hacemos en la declaración de la clase con la
sintaxis:
public class Formulario extends JFrame implements ActionListener {
Con esto estamos diciendo que nuestra clase implementa la interface ActionListener, luego estamos
obligados a codificar el método actionPerformed.
Definimos un objeto de la clase JButton:
JButton boton1;
En el constructor creamos el objeto de la clase JButton y mediante la llamada del método
addActionListener le pasamos la referencia del objeto de la clase JButton utilizando la palabra clave this
(this almacena la dirección de memoria donde se almacena el objeto de la clase JFrame, luego mediante
dicha dirección podemos llamar al método actionPerformed):
public Formulario() {
setLayout(null);
boton1=new JButton("Finalizar");
boton1.setBounds(300,250,100,30);
add(boton1);
boton1.addActionListener(this);
}
El método actionPerformed (este método de la interface ActionListener debe implementarse
obligatoriamente, en caso de no codificarlo o equivocarnos en su nombre aparecerá un mensaje de
error en tiempo de compilación de nuestro programa.
El método actionPerformed se ejecutará cada vez que hagamos clic sobre el objeto de la clase JButton.
La interface ActionListener y el objeto de la clase ActionEvent que llega como parámetro están definidos
en el paquete:
import java.awt.event.*;
Es decir que cada vez que se presiona el botón desde la clase JButton se llama al método
actionPerformed y recibe como parámetro un objeto de la clase ActionEvent.
En el método actionPerformed mediante el acceso al método getSource() del objeto que llega como
parámetro podemos analizar que botón se presionó:
public void actionPerformed(ActionEvent e) {
if (e.getSource()==boton1) {
System.exit(0);
}
}
Si se presionó el boton1 luego el if se verifica verdadero y por lo tanto llamando al método exit de la
clase System se finaliza la ejecución del programa.
Problema 2:
Confeccionar una ventana que contenga tres objetos de la clase JButton con las etiquetas "1", "2" y "3".
Al presionarse cambiar el título del JFrame indicando cuál botón se presionó.
Programa:
import javax.swing.*;
import java.awt.event.*;
public class Formulario extends JFrame implements ActionListener{
private JButton boton1,boton2,boton3;
public Formulario() {
setLayout(null);
boton1=new JButton("1");
boton1.setBounds(10,100,90,30);
add(boton1);
boton1.addActionListener(this);
boton2=new JButton("2");
boton2.setBounds(110,100,90,30);
add(boton2);
boton2.addActionListener(this);
boton3=new JButton("3");
boton3.setBounds(210,100,90,30);
add(boton3);
boton3.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==boton1) {
setTitle("boton 1");
}
if (e.getSource()==boton2) {
setTitle("boton 2");
}
if (e.getSource()==boton3) {
setTitle("boton 3");
}
}
public static void main(String[] ar){
Formulario formulario1=new Formulario();
formulario1.setBounds(0,0,350,200);
formulario1.setVisible(true);
}
}
Debemos declarar 3 objetos de la clase JButton:
private JButton boton1,boton2,boton3;
En el constructor creamos los tres objetos de la clase JButton y los ubicamos dentro del control JFrame
(también llamamos al método addActionListener para enviarle la dirección del objeto de la clase
Formulario):
public Formulario() {
setLayout(null);
boton1=new JButton("1");
boton1.setBounds(10,100,90,30);
add(boton1);
boton1.addActionListener(this);
boton2=new JButton("2");
boton2.setBounds(110,100,90,30);
add(boton2);
boton2.addActionListener(this);
boton3=new JButton("3");
boton3.setBounds(210,100,90,30);
add(boton3);
boton3.addActionListener(this);
}
Cuando se presiona alguno de los tres botones se ejecuta el método actionPerformed y mediante tres if
verificamos cual de los botones se presionó:
public void actionPerformed(ActionEvent e) {
if (e.getSource()==boton1) {
setTitle("boton 1");
}
if (e.getSource()==boton2) {
setTitle("boton 2");
}
if (e.getSource()==boton3) {
setTitle("boton 3");
}
}
Según el botón presionado llamamos al método setTitle que se trata de un método heredado de la clase
JFrame y que tiene por objetivo mostrar un String en el título de la ventana.
Problema propuesto
1. Disponer dos objetos de la clase JButton con las etiquetas: "varón" y "mujer", al presionarse
mostrar en la barra de títulos del JFrame la etiqueta del botón presionado.
package EJERCICIOS1;
import javax.swing.*;
import java.awt.event.*;
public class problema3 extends JFrame implements ActionListener{
private JButton mujer,varon;

public problema3() {
setLayout(null);
mujer=new JButton("mujer");
mujer.setBounds(10,100,90,30);
add(mujer);
mujer.addActionListener(this);
varon=new JButton("varon");
varon.setBounds(110,100,90,30);
add(varon);
varon.addActionListener(this);}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==mujer) {
setTitle("mujer");}
if (e.getSource()==varon) {
setTitle("varon");}}
public static void main(String[] ar){
problema3 formulario1=new problema3();
formulario1.setBounds(0,0,350,200);
formulario1.setVisible(true);
}}

Ejercicios resueltos 2.
Ejercicio 1. Eventos de Ratón (MouseListener)
package EJERCICIOS2;
//Demostración de los eventos de ratón.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ejercicio201 extends JFrame implements MouseListener, MouseMotionListener
{private JLabel barraEstado;
//configurar GUI y registrar manejadores de eventos de ratón
public ejercicio201()
{super( "Demostración de los eventos de ratón" );
barraEstado = new JLabel();
getContentPane().add( barraEstado, BorderLayout.SOUTH);
getContentPane().addMouseListener( this ); // escucha sus propios eventos de ratón
getContentPane().addMouseMotionListener( this ); // y de movimiento de ratón
setSize( 300, 125 );
setVisible( true );}
//Manejadores de eventos de MouseListener
//manejar el evento cuando el botón del ratón se suelta inmediatamente después de oprimir
public void mouseClicked( MouseEvent evento )
{barraEstado.setText( "Se hizo clic en [" + evento.getX() +
", " + evento.getY() + "]" );}
//manejar evento cuando se oprime el botón del ratón
public void mousePressed( MouseEvent evento )
{barraEstado.setText( "Se oprimió en [" + evento.getX() +
", " + evento.getY() + "]" );}
//manejar evento cuando se suelta el ratón después de arrastrar
public void mouseReleased( MouseEvent evento )
{barraEstado.setText( "Se soltó en [" + evento.getX() +
", " + evento.getY() + "]" );}
//manejar el evento cuando el ratón entra al área
public void mouseEntered( MouseEvent evento )
{barraEstado.setText( "Ratón entro en [" + evento.getX() +
", " + evento.getY() + "]" );
getContentPane().setBackground( Color.GREEN );}
//manejar evento cuando el ratón sale del área
public void mouseExited( MouseEvent evento )
{barraEstado.setText( "Ratón fuera de la ventana" );
getContentPane().setBackground( Color.WHITE );}
//Manejadores de eventos de MouseMotionListener
//manejar el evento cuando el usuario arrastra el ratón con el botón oprimido
public void mouseDragged( MouseEvent evento )
{barraEstado.setText( "Se arrastró en [" + evento.getX() +
", " + evento.getY() + "]" );}
//manejar el evento cuando el usuario mueve el ratón
public void mouseMoved( MouseEvent evento )
{barraEstado.setText( "Se movió en [" + evento.getX() +
", " + evento.getY() + "]" );}
public static void main( String args[] )
{JFrame.setDefaultLookAndFeelDecorated(true);
ejercicio201 aplicacion = new ejercicio201();
aplicacion.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}} // fin de la clase RastreadorRaton
 Ejercicio 2. Eventos de teclado (KeyListener)
package EJERCICIOS2;
// Demostración de los eventos de pulsación de tecla.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ejercicio202 extends JFrame implements KeyListener {
private String linea1 = "", linea2 = "", linea3 = "";
private JTextArea areaTexto;
// configurar GUI
public Ejercicio202()
{super( "Demostración de eventos de pulsación de tecla" );
// establecer objeto JTextArea
areaTexto = new JTextArea( 10, 15 );
areaTexto.setText( "Oprima cualquier tecla en el teclado..." );
areaTexto.setEnabled( false );
areaTexto.setDisabledTextColor( Color.blue );
getContentPane().add( areaTexto );
addKeyListener( this ); // permitir al marco procesar eventos de teclas
setSize( 350, 100 );
setVisible( true );
} // fin del constructor de DemoTeclas
// manejar evento de pulsación de cualquier tecla
public void keyPressed( KeyEvent evento )
{linea1 = "Se oprimió tecla: " + evento.getKeyText( evento.getKeyCode() );
establecerLineas2y3( evento );}
// manejar evento de liberación de cualquier tecla
public void keyReleased( KeyEvent evento )
{linea1 = "Se soltó tecla: " + evento.getKeyText( evento.getKeyCode() );
establecerLineas2y3( evento );}
// manejar evento de pulsación de una tecla de acción
public void keyTyped( KeyEvent evento )
{linea1 = "Se escribió tecla: " + evento.getKeyChar();
establecerLineas2y3( evento );}
// establecer segunda y tercera líneas de salida
private void establecerLineas2y3( KeyEvent evento )
{linea2 = "Esta tecla " + ( evento.isActionKey() ? "" : "no " ) +
"es una tecla de acción";
String temp = evento.getKeyModifiersText( evento.getModifiers() );
linea3 = "Teclas modificadoras oprimidas: " +
( temp.equals( "" ) ? "ninguna" : temp );
areaTexto.setText( linea1 + "\n" + linea2 + "\n" + linea3 + "\n" );}
public static void main( String args[] )
{JFrame.setDefaultLookAndFeelDecorated(true);
Ejercicio202 aplicacion = new Ejercicio202();
aplicacion.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}
} // fin de la clase DemoTeclas