Resolução dos exercícios da aula prática

Propaganda
Conceitos de Programação com Componentes
•
Resolução do exercício 1.2
BorderLayout
import javax.swing.*;
import java.awt.*;
public class BorderLayout1 extends JApplet {
public void init() {
Container cp = getContentPane();
cp.add(BorderLayout.NORTH,
new JButton("North"));
cp.add(BorderLayout.SOUTH,
new JButton("South"));
cp.add(BorderLayout.EAST,
new JButton("East"));
cp.add(BorderLayout.WEST,
new JButton("West"));
cp.add(BorderLayout.CENTER,
new JButton("Center"));
}
}
FlowLayout
import javax.swing.*;
import java.awt.*;
public class FlowLayout1 extends JApplet {
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
for(int i = 0; i < 20; i++)
cp.add(new JButton("Button " + i));
}
}
GridLayout
import javax.swing.*;
import java.awt.*;
public class GridLayout1 extends JApplet {
public void init() {
Container cp = getContentPane();
cp.setLayout(new GridLayout(7,3));
for(int i = 0; i < 20; i++)
cp.add(new JButton("Button " + i));
}
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 1.3
import
import
import
import
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.*;
public class TrackEvent extends JApplet {
HashMap h = new HashMap();
String[] event = {
"focusGained", "focusLost", "keyPressed",
"keyReleased", "keyTyped", "mouseClicked",
"mouseEntered", "mouseExited","mousePressed",
"mouseReleased", "mouseDragged", "mouseMoved"
};
MyButton
b1 = new MyButton(Color.blue, "test1"),
b2 = new MyButton(Color.red, "test2");
class MyButton extends JButton {
void report(String field, String msg) {
((JTextField)h.get(field)).setText(msg);
}
FocusListener fl = new FocusListener() {
public void focusGained(FocusEvent e) {
report("focusGained", e.paramString());
}
public void focusLost(FocusEvent e) {
report("focusLost", e.paramString());
}
};
KeyListener kl = new KeyListener() {
public void keyPressed(KeyEvent e) {
report("keyPressed", e.paramString());
}
public void keyReleased(KeyEvent e) {
report("keyReleased", e.paramString());
}
public void keyTyped(KeyEvent e) {
report("keyTyped", e.paramString());
}
};
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
report("mouseClicked", e.paramString());
}
public void mouseEntered(MouseEvent e) {
report("mouseEntered", e.paramString());
}
public void mouseExited(MouseEvent e) {
report("mouseExited", e.paramString());
}
public void mousePressed(MouseEvent e) {
report("mousePressed", e.paramString());
}
public void mouseReleased(MouseEvent e) {
report("mouseReleased", e.paramString());
}
};
MouseMotionListener mml =
new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
report("mouseDragged", e.paramString());
}
public void mouseMoved(MouseEvent e) {
report("mouseMoved", e.paramString());
}
};
public MyButton(Color color, String label) {
super(label);
setBackground(color);
addFocusListener(fl);
addKeyListener(kl);
addMouseListener(ml);
addMouseMotionListener(mml);
}
}
public void init() {
Container c = getContentPane();
c.setLayout(new GridLayout(event.length+1,2));
for(int i = 0; i < event.length; i++) {
JTextField t = new JTextField();
t.setEditable(false);
c.add(new JLabel(event[i], JLabel.RIGHT));
c.add(t);
h.put(event[i], t);
}
c.add(b1);
c.add(b2);
}
public static void main(String[] str) {
JApplet ap = new TrackEvent ();
JFrame frame = new JFrame("Appx");
frame.getContentPane().add(ap);
frame.setSize(500,300);
ap.init();
// simula o focus do browser
ap.start();
frame.setVisible(true);
// torna a frame visível
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 1.4
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestMenu extends JApplet {
JTextArea tx = new JTextArea(20,40);
ActionListener bt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = ( (JMenuItem) e.getSource()).getText();
tx.append(s + "\n");
}
};
JMenu[] menus = {
new JMenu("Menu1"), new JMenu("Menu2"), new JMenu("Menu3")
};
JMenuItem[] itens = {
new JMenuItem("Item11"), new JMenuItem("Item12"),
new JMenuItem("Item21"), new JMenuItem("Item22"),
new JMenuItem("Item31"), new JMenuItem("Item32") };
public void init() {
for( int i=0; i < itens.length; i++) {
itens[i].addActionListener(bt);
// regista observador
menus[i/2].add(itens[i]);
// controi os menus
}
JMenuBar m = new JMenuBar();
for( int i=0; i<menus.length; i++)
m.add(menus[i]);
// controi barra de menu
Container ct = getContentPane();
ct.setLayout(new FlowLayout());
ct.add(m);
ct.add(new JScrollPane(tx));
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 2.3
package frogbean;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frog extends JApplet {
private JTextArea tx = new JTextArea(10,10);
private int croaks;
private boolean quiet;
public Frog() {
quiet = false;
Container ct = getContentPane();
ct.setLayout(new FlowLayout());
ct.add(tx);
}
public boolean isQuiet() { return quiet; }
public void setQuiet(boolean q) { quiet = q; }
public int getCroaks() { return croaks; }
public void setCroaks(int c) { croaks = c; }
public void croak() {
if (quiet!=true) {
croaks++;
tx.append("Croak!");
}
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 2.4
import java.awt.*;
public class Counter extends Canvas {
private int count;
private boolean operate;
public Counter() {
count = 0;
operate = true;
setSize(100,100);
}
public void reset() {
count = 0;
repaint();
}
public void start( ) {
operate = true;
}
public void stop() {
operate = false;
}
public synchronized void increment() {
if(operate) {
++count;
repaint();
}
}
public void paint(Graphics g) {
Dimension d = getSize();
int x = d.width-50;
int y = d.height-50;
g.drawString("" + count, x, y);
g.drawRect(0, 0, d.width - 1, d.height - 1);
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 3.2 (e 3.1)
// TickEvent.java
package tick;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TickEvent extends EventObject {
public TickEvent(Object source) {
super(source);
}
}
// TickListener.java
package tick;
import java.util.*;
public interface TickListener extends EventListener {
public void tick(TickEvent ce);
}
// TickReceiver.java
(receptor dos eventos tick, i.e., observador)
package tick;
import java.awt.*;
public class TickReceiver extends Panel implements TickListener {
TextArea tx = new TextArea(30,30);
public TickReceiver() {
add(tx);
setSize(50, 50);
}
public void tick(TickEvent e) {
tx.append("tick");
}
}
// Ticksource.java
package tick;
import
import
import
import
import
(gerador dos eventos, i.é., o assunto)
java.awt.*;
java.awt.event.*;
java.beans.*;
java.util.*;
java.io.*;
public class TickSource extends Panel implements Runnable {
private int cont;
private int iniCont=100;
private TextField tx = new TextField(10);
private Vector listeners = new Vector();
private transient Thread thread;
public TickSource() {
add(tx);
cont=iniCont;
startThread();
}
private void startThread() {
thread = new Thread(this);
thread.start();
}
public int getCont() { return iniCont; }
public void setCont(int c) { this.iniCont = c;
}
public void run() {
try {
while(true) {
Thread.sleep(100);
cont--;
tx.setText("cont=" + cont);
if (cont==0) {
fireTickEvent(new TickEvent(this));
cont = iniCont;
}
}
}
catch(Exception e) { e.printStackTrace(); }
}
public void addTickListener(TickListener cl) {
listeners.addElement(cl);
}
public void removeTickListener(TickListener cl) {
listeners.removeElement(cl);
}
public void fireTickEvent(TickEvent ce) {
Vector v;
synchronized(this) {
v = (Vector)listeners.clone();
}
for(int i = 0; i < v.size(); i++) {
TickListener cl = (TickListener)v.elementAt(i);
cl.tick(ce);
}
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
try {
ois.defaultReadObject();
startThread();
}
catch(Exception ex) { ex.printStackTrace(); }
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 3.3
import java.lang.reflect.*;
import java.io.*;
public class MyReflect
{
public MyReflect() {}
public static void main(String[] str) {
//System.out.println("Procurar" + str[0]);
try {
Class c = Class.forName("java.io.FileWriter");
System.out.println("-----Fields---------");
Field f[] = c.getFields();
for(int i=0; i<f.length; i++) {
System.out.println(f[i].getName());
}
System.out.println("-----Constructors---------");
Constructor[] ct = c.getConstructors();
for(int i=0; i<ct.length; i++) {
System.out.println(ct[i].getName());
}
System.out.println("-----Methods---------");
Method[] m = c.getMethods();
for(int i=0; i<m.length; i++) {
System.out.println(m[i].getName());
}
} catch(Exception e) { e.printStackTrace(); }
}
}
Conceitos de Programação com Componentes
•
Resolução do exercício 3.4
// Frog2.java
package frogbean2;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
public class Frog2 extends Panel {
private TextArea tx = new TextArea(10,10);
private int croaks;
private boolean quiet;
public Frog2() {
quiet = false;
setLayout(new FlowLayout());
add(tx);
}
public boolean isQuiet() { return quiet; }
public void setQuiet(boolean q) { quiet = q; }
public int getCroaks() { return croaks; }
public void setCroaks(int c) { croaks = c; }
public void croak() {
if (quiet!=true) {
croaks++;
tx.append("Croak!" + "\n");
}
}
}
// Frog2BeanInfo.java (controla a informação visível do bean)
package frogbean2;
import java.beans.*;
import java.awt.event.*;
import java.lang.reflect.*;
public class Frog2BeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor pd1, pd2;
pd1 = new PropertyDescriptor("quiet",Frog2.class);
pd2 = new PropertyDescriptor("croaks",Frog2.class);
PropertyDescriptor pds[] = { pd1, pd2 };
return pds;
}
catch(Exception ex) { }
return null;
}
public EventSetDescriptor[] getEventSetDescriptors() {
EventSetDescriptor esds[] = { };
return esds;
}
public MethodDescriptor[] getMethodDescriptors() {
try {
// utiliza a reflexão para contruir o método croak
Method[] m = (Frog2.class).getMethods();
Method m1= m[0];
for(int i=0; i<m.length; i++) { // procura o método na lista
if ((m[i].getName()).equals("croak")) m1=m[i];
}
ParameterDescriptor pds[] = new ParameterDescriptor[1];
pds[0] = new ParameterDescriptor();
MethodDescriptor md1 = new MethodDescriptor(m1, pds);
MethodDescriptor mds[] = { new MethodDescriptor(m1, pds) };
return mds;
}
catch(Exception ex) { ex.printStackTrace(); }
return null;
}
}
Download