Skip to content

Month: February 2008

Gato em JavaFX, versão 2

Lembra daquele nosso gato em Java FX? Agora ele move os olhos com cliques em botões.



Código fonte:

import javafx.ui.canvas.*;
import javafx.ui.*;
 
class Cat extends CompositeNode{
    attribute look: Number; // -1.0 to 1.0
    operation lookLeft();
    operation lookCenter();
    operation lookRight();
}
 
attribute Cat.look = 0; // 0 = middle
 
operation Cat.lookLeft(){
    look = [look, look - 0.1 .. -1.0] dur 1000;
}
 
operation Cat.lookCenter(){
    var step = if look < 0 then 0.1 else -0.1;
    look = [look, look+step .. 0.0] dur 1000;
}
 
operation Cat.lookRight(){
    look = [look, look + 0.1 .. 1.0] dur 1000;
}
 
function Cat.composeNode(){
    var head =  Ellipse {cx:100, cy:100, radiusX:100, radiusY:50, fill:black };
    var rightEar =  Arc {x:100, y:10, height:150, width:100,
                       startAngle:-20, length:90, closure:PIE, fill:black};
    var leftEar = Arc {x:000, y:10, height:150, width:100,
                     startAngle:110, length:90, closure:PIE, fill:black};
    var leftEye = Ellipse { cx:60, cy:100, radiusX:30, radiusY:15, fill:white};
    var rightEye = Ellipse { cx:140, cy:100, radiusX:30, radiusY:15, fill:white};
    var nose = Arc { x:85, y:110, height:20, width:30,
                     startAngle:45, length:90, closure:PIE, fill:white};
 
    var rightIris = Ellipse { cx: bind 140+look*20, cy:100,
                     radiusX:5, radiusY:15, fill:black};
    var leftIris = Ellipse { cx: bind 60+look*20, cy:100,
                     radiusX:5, radiusY:15, fill:black};    
 
    return Group{content: [head, rightEar, leftEar, leftEye,
                     leftIris, rightEye, rightIris, nose]};
}
 
var myCat = Cat{};
 
var myCatControl = View {
            transform: [translate(0, 150)]
            content: GroupPanel {
                cursor: DEFAULT
                var row = Row {alignment: BASELINE}
                var column1 = Column { }
                var column2 = Column { }
                var column3 = Column { }
                var column4 = Column { }
                var column5 = Column { }
                rows: [row]
                columns: [column1, column2, column3, column4]
                content:
                [SimpleLabel {
                    row: row
                    column: column1
                    text: "Look:"
                },
                Button {
                    row: row
                    column: column2
                    mnemonic: L
                    text: "Left"
                    action: operation() {
                        myCat.lookLeft();
                    }
                },
                Button {
                    row: row
                    column: column3
                    mnemonic: C
                    text: "Center"
                    action: operation() {
                        myCat.lookCenter();
                    }
                },
                Button {
                    row: row
                    column: column4
                    mnemonic: R
                    text: "Right"
                    action: operation() {
                        myCat.lookRight();
                    }
                }]
                }
            };
 
Canvas {
    content: [myCatControl, myCat]
}

Downloads:

JavaFX, Exemplos Básicos

Alguns exemplo básicos de JavaFX usando a construção de interfaces de forma declarativa.
Para testa-los eu recomendo o JavaFX Pad ou o plugin JavaFX para Netbeans.

import javafx.ui.*; 
 
Frame {
    title: "Label JavaFX"
    width:  300
    height: 50
    content: Label {
            text: "Olá Mundo!"
    }
    visible: true   
}

JavaFX label

import javafx.ui.*;
import java.lang.System;
 
Frame {
    title: "Botão JavaFX"
    width:  300
    height: 100
    content: Button {
           text: "Clique-me"
           action: operation(){
              System.out.println("Botão pressionado");
           }
    }
    visible: true   
}

Botão em JavaFX

import javafx.ui.*;
import java.lang.System;
 
Frame {
  title: "Menu JavaFX"
  width:  300
  height: 100
  menubar: MenuBar {
    menus: Menu {
      text: "Menu"
      items:  foreach (name in ["Menu1", "Menu2", "Menu3"])  
              MenuItem {
                text: name
                action: operation() {
                  System.out.println("MenuItem: {name}");
                }
             }
     }
  }
    visible: true
}

JavaFX Menu

import javafx.ui.*;
import java.lang.System;
 
var N = 4;
 
Frame {
    title: "Tabela JavaFX"
    width:  300
    height: 150
    onClose: operation(){ System.exit(0); }
    content: Table {
        columns: [
        TableColumn {
            text: "numero"
        },
        TableColumn {
            text: "quadrado"
        },
        TableColumn {
            text: "cubo"
        }]
 
        cells: bind foreach(n in [1..N])[
        TableCell {
            text: "{n}"
        },
        TableCell {
            text: bind "{n * n}"
        },
        TableCell {
            text: bind "{n * n * n}"
        },
        ]
    }
    visible: true
}

JavaFX Tabela

import javafx.ui.*;
 
var selectedTab = 0;
 
Frame{
    title: "Tab Example"
    width: 300
    height: 120
    content: BorderPanel{
        top: Label { text: bind "Selected tab: {selectedTab + 1}" }
        center: TabbedPane{
            selectedIndex: bind selectedTab
            tabs: foreach(i in [1..5])
            Tab {
                title: "Tab{i}"
                content: Label{ text: "Label{i} "}
            }            
        }
    }
    visible: true
}

JavaFX abas

import javafx.ui.*;
 
Frame {
    title: "FlowPanel JavaFX"
    width:  300
    height: 100
    content: FlowPanel{
        content: [
        Label{ text: "Label1" },
        Label{ text: "Label2" },
        Label{ text: "Label3" },
        ]
    }
    visible: true
}

JavaFX FlowPanel

import javafx.ui.*;
 
Frame {
    title: "BorderPanel JavaFX"
    width:  400
    height: 200
    content: BorderPanel{
        top   :  Button{ text: "Topo" }
        center:  Button{ text: "Centro" }
        bottom:  Button{ text: "Fundo" }
        left  :  Button{ text: "Esquerda" }
        right :  Button{ text: "Direita" }
    }
    visible: true
}

JavaFX BorderPanel

Esses exemplos eu retirei da página de exemplos do Wiki do JavaFX (russo). Se você quiser saber mais sobre componentes de interface gráfica em JavaFX veja o tutorial
Learning More About the JavaFX Script Language (for Swing Programmers).

Hóspede de Carnaval

Olha só quem veio me visitar e acabou passando o carnaval comigo e com a Deborah.


E deixou várias lembranças. :P


Um ponto a mais para a idéia de colocar rede sem fio.

Java: métodos com número variável de parâmetros

A partir do Java 5 podemos escrever métodos com um número variável de parâmetros, é o chamado varargs. Com isso podemos criar métodos bem flexíveis e elegantes, principalmente se aplicando isso juntamente com outros recursos como o loop melhorado e polimorfismo.

Esse exemplo cria uma classe Estatistica com o método media que pode receber um número variável de argumentos do tipo int.

public class Estatistica {
    public float media(int... numeros){
        float soma = 0;
        for(int num: numeros)
            soma += num;
        return soma/numeros.length;
    }
    public static void main(String[] args) {
        Estatistica est = new Estatistica();
        System.out.println( est.media(1,2,3) );
        System.out.println( est.media(0,1,2,3,4,5,6,7,8,9,10) );
        System.out.println( est.media(10,20,30) );
    }
}

$ javac Estatistica.java
$ java Estatistica
2.0
5.0
20.0

Legal, né? Isso sim é sobrecarga de método. ;)

Os canos da Internet

É bom provável que os bits que compõe esse post tenham chegado até você passando por baixo d’água.

Cabo submarino
Aspecto de um cabo submarino.

A maioria do tráfego da Internet circula através de cabos submarinos que atravessam os oceanos ligando todos continentes. Eu achei alguns gráficos legais que mostram a topologia dos cabos submarinos no globo. Clique nas imagens abaixo para amplia-las.

mapa dos cabos da internet
Retirado de Guardian.co.uk
Mapa dos cabos submarinos da Internet
Retirado de telegeography.com
Já pensou se alguém resolve atacar um desses cabos?