package pack;
import java.awt.Button;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;
public class Figuri extends Frame{
private static final long serialVersionUID=1L;
Canvas c;
int x,y,x1,y1;
Random opt;
Image img;
public Figuri(){
super("My app");
//setLayout(new BorderLayout());
Panel p=new Panel(new FlowLayout());
this.add(p,BorderLayout.NORTH);
final TextField tf1 =new TextField();
final TextField tf2 =new TextField();
final TextField tf3 =new TextField();
final TextField tf4 =new TextField();
p.add(new Label("x:"));
p.add(tf1);
p.add(new Label("y:"));
p.add(tf2);
p.add(new Label("x1:"));
p.add(tf3);
p.add(new Label("y1:"));
p.add(tf4);
Button b=new Button("Deseneaza");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int x=Integer.parseInt(tf1.getText());
int y=Integer.parseInt(tf2.getText());
int x1=Integer.parseInt(tf3.getText());
int y1=Integer.parseInt(tf4.getText());
Figuri.this.x=x;
Figuri.this.y=y;
Figuri.this.x1=x1;
Figuri.this.y1=y1;
c.repaint();
}
});
p.add(b);
opt=new Random();
img=Toolkit.getDefaultToolkit().getImage("timp.png");
c=new Canvas(){
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g){
switch(opt.nextInt(5)){
case 0:g.drawOval(x,y,x1,y1);break;
case 1:g.drawRect(x, y, x1, y1);break;
case 2:g.drawLine(x, y, x1, y1);break;
case 3:g.drawImage(img,x,y,this);break;
case 4:g.drawOval(x,y,x1,x1);break;
}
}
};
p.add(b);
this.add(c);
this.setPreferredSize(new Dimension(600,600));
this.pack();
setVisible(true);
Button close= new Button("close");
close.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
p.add(close);
}
}
miercuri, 6 iunie 2012
Enunturi
filiobogdan: Bogdan: subiecte date
Bogdan:
evident. Se ofera butoane pt: repozitionarea nodului curent la inceputul listei,
trecerea la urmatorul nod, stergere nod curent si,printr-un text, introducerea unui
nou nod inainte/dupa cel curent.
Concepeti diagrama de clase/interfete.
2.
returneaza false),element si peek(returneaza primul element din coada, daca nu mai
sunt elemente, primafunctie genereaza exceptie, iar a doua returneaza null), pop si
pool(similar cu functiile anterioare
filiobogdan: decat ca elementul returnat este si scos din coada)
Concepeti o interfata pt stiva si o implementare a acestei stive. elementele stivei
pot fi d orice tip(folosityi tipuri generice). Realizati clasele exceptie
corespunzatoare cerintelor.
Concepeti diagrama d clase/interfete
Realizati o aplicatie (consola sau Swing)pentru testare
exceptie,iar a doua returneaza false),element si peek(returneaza primul
element din coada, daca nu mai sunt elemente, prima functie genereaza
exceptie, iar a doua returneaza null),remove si poll(similar cu functiile
anterioare,decat ca elementul returnat este si scos din coada).
Concepeti o interfata pentru coada si o implementare a acestei cozi.
Elementele cozii sunt numere. Realizati clasele exceptie corespunzatoare
cerintelor.
filiobogdan: Concepeti diagrama de clase/interfete.
Realizati o aplicatie(consola/swing) pentru testare.
Folosind AspectJ aplicati un filtru asupra numerelor introduse in
coada(de ex numerele negative nu vor fi introduse). Cand un numar nu este
introdus, un mesaj corespunzator va fi afisate la consola.
iar o alta componenta grafica trebuie sa afiseze un ceas realistic
grafic, cu minutare si secundar. Cele 2 componente sunt legate prin
pattern-ul observer, si trebuie sa reflecte aceeasi ora.
Concepeti diagrama de clase/interfete
anaxor_roxy: mc
filiobogdan: np
George Grosu: pai mi-a dat 2 probleme
pesse: asa
pesse: kt ai luat?
George Grosu: una sa implementez o coada generica
George Grosu: cu o interfata
George Grosu: cu 6 functii in interfatas
George Grosu: 3 dintre ele arunca exceptii
George Grosu: cand e plina sau goala coada
pesse:
George Grosu: si separat, 2 clase de excepetii
George Grosu: si a doua problema
George Grosu: studentul are mai multe obiecte
George Grosu: fiecare obiect are o nota si un nr de credite
George Grosu: si fiecare student are o medie
George Grosu: media poate fi aritmetica, dar si ponderata, iar o nota poate fi luata
in calcul sau nu
George Grosu: in functie daca e de trecere sau nu
pesse: asa..
George Grosu: faci cate o clasa pentru fiecare mod de calcul a mediei
George Grosu: si pentru celelalte ... adik student si obiecte
George Grosu: si o interfata
George Grosu: in care alegerea clasei de calcul a mediei este facuta de sablonul
Factory nu siu cum
George Grosu: am luat 8
George Grosu: ca ne-a lasat 6 ore
George Grosu: cu internetul la dispozitie
George Grosu: adik dupa 6 ore am plecat eu
George Grosu: ca nu m-a dat afara
Mircea Dan Potur: suna interesant
pesse: Lista simplu inlantuita, generic stack,. pt arbori->3 panneluri+observer,
Calc, server, factoryMethod, graf, designPatterns, AspectJ+Adapter
pesse: tot lui teiar la celalat pct folosind aspectj sa faca suna,produsul si media
unor nr si sa le puna intr-o interfata
Conversation with filiobogdan
(03:18:54 PM) filiobogdan: subiecte date
(03:18:57 PM) filiobogdan:
1.Ralizati o aplicatioe care sa prezintye grafic o lista simplu inlantuita de elemente(numere), se deseneaza
nodurile si legaturile dintre ele.nodul curent este evident. Se ofera butoane pt: repozitionarea nodului
curent la inceputul listei, trecerea la urmatorul nod, stergere nod curent si,printr-un text, introducerea unui
nou nod inainte/dupa cel curent.
Concepeti diagrama de clase/interfete.
2.
Se cere implementarea unei stive cu urmatoarea interfata:push si offer(adauga element,in caz de depasire
capacitate, prima functie genereaza exceptie, iar a doua returneaza false),element si peek(returneaza
primul element din coada, daca nu mai sunt elemente, primafunctie genereaza exceptie, iar a doua
returneaza null), pop si pool(similar cu functiile anterioare, decat ca elementul returnat
(03:20:14 PM) filiobogdan: este si scos din coada)
Concepeti o interfata pt stiva si o implementare a acestei stive. elementele stivei pot fi d orice tip(folosityi
tipuri generice). Realizati clasele exceptie corespunzatoare cerintelor.
Concepeti diagrama d clase/interfete
Realizati o aplicatie (consola sau Swing)pentru testare
PS:dati un semn d viata daca ati primit msg ca sa stiu daca va mai trimit odata sau nu;)
Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.
Date: Fri, 6 Jul 2007 23:13:35 -0700 (PDT)
From: "punk 4 life" <cojan4punk@yahoo.com>
Subject: ce kkt!!
To: "punk 4 life" <cojan4punk@yahoo.com>, "balenush" <fia725@yahoo.com>
HTML Attachment [ Scan and Save to Computer ]
nasol =))
-----------------
..from cojan
(03:20:19 PM) filiobogdan: Se cere implementarea unei cozi cu urmatoarea interfata: add si
offer(adauga element,in caz de depasire capacitate,prima functie genereaza
exceptie,iar a doua returneaza false),element si peek(returneaza primul
element din coada, daca nu mai sunt elemente, prima functie genereaza
exceptie, iar a doua returneaza null),remove si poll(similar cu functiile
anterioare,decat ca elementul returnat este si scos din coada).
Concepeti o interfata pentru coada si o implementare a acestei cozi.
Elementele cozii sunt numere. Realizati clasele exceptie corespunzatoare
cerintelor.
Concepeti diagrama de clase/interfete.
Realizati o aplicatie(consola/swing) pentru testare.
Folosind AspectJ aplicati un filtru asupra numerelor introduse in
coada(de ex numerele negative nu vor fi introduse
(03:20:37 PM) filiobogdan: Cand un numar nu este
introdus, un mesaj corespunzator va fi afisate la consola.
Realizati o aplicatie care sa ajute la setarea orei. O componenta
grafica trebuie sa cuprinda texte prin care se poate seta ora si minutele,
iar o alta componenta grafica trebuie sa afiseze un ceas realistic
grafic, cu minutare si secundar. Cele 2 componente sunt legate prin
pattern-ul observer, si trebuie sa reflecte aceeasi ora.
Concepeti diagrama de clase/interfete
Bogdan:
1.Ralizati o aplicatioe care sa prezintye grafic o lista simplu inlantuita de
elemente(numere), se deseneaza nodurile si legaturile dintre ele.nodul curent esteevident. Se ofera butoane pt: repozitionarea nodului curent la inceputul listei,
trecerea la urmatorul nod, stergere nod curent si,printr-un text, introducerea unui
nou nod inainte/dupa cel curent.
Concepeti diagrama de clase/interfete.
2.
Se cere implementarea unei stive cu urmatoarea interfataush si offer(adauga
element,in caz de depasire capacitate, prima functie genereaza exceptie, iar a douareturneaza false),element si peek(returneaza primul element din coada, daca nu mai
sunt elemente, primafunctie genereaza exceptie, iar a doua returneaza null), pop si
pool(similar cu functiile anterioare
filiobogdan: decat ca elementul returnat este si scos din coada)
Concepeti o interfata pt stiva si o implementare a acestei stive. elementele stivei
pot fi d orice tip(folosityi tipuri generice). Realizati clasele exceptie
corespunzatoare cerintelor.
Concepeti diagrama d clase/interfete
Realizati o aplicatie (consola sau Swing)pentru testare
filiobogdan: Se cere implementarea unei cozi cu urmatoarea interfata: add si
offer(adauga element,in caz de depasire capacitate,prima functie genereazaexceptie,iar a doua returneaza false),element si peek(returneaza primul
element din coada, daca nu mai sunt elemente, prima functie genereaza
exceptie, iar a doua returneaza null),remove si poll(similar cu functiile
anterioare,decat ca elementul returnat este si scos din coada).
Concepeti o interfata pentru coada si o implementare a acestei cozi.
Elementele cozii sunt numere. Realizati clasele exceptie corespunzatoare
cerintelor.
filiobogdan: Concepeti diagrama de clase/interfete.
Realizati o aplicatie(consola/swing) pentru testare.
Folosind AspectJ aplicati un filtru asupra numerelor introduse in
coada(de ex numerele negative nu vor fi introduse). Cand un numar nu este
introdus, un mesaj corespunzator va fi afisate la consola.
Realizati o aplicatie care sa ajute la setarea orei. O componenta
grafica trebuie sa cuprinda texte prin care se poate seta ora si minutele,iar o alta componenta grafica trebuie sa afiseze un ceas realistic
grafic, cu minutare si secundar. Cele 2 componente sunt legate prin
pattern-ul observer, si trebuie sa reflecte aceeasi ora.
Concepeti diagrama de clase/interfete
anaxor_roxy: mc
filiobogdan: np
George Grosu: pai mi-a dat 2 probleme
pesse: asa
pesse: kt ai luat?
George Grosu: una sa implementez o coada generica
George Grosu: cu o interfata
George Grosu: cu 6 functii in interfatas
George Grosu: 3 dintre ele arunca exceptii
George Grosu: cand e plina sau goala coada
pesse:
George Grosu: si separat, 2 clase de excepetii
George Grosu: si a doua problema
George Grosu: studentul are mai multe obiecte
George Grosu: fiecare obiect are o nota si un nr de credite
George Grosu: si fiecare student are o medie
George Grosu: media poate fi aritmetica, dar si ponderata, iar o nota poate fi luata
in calcul sau nu
George Grosu: in functie daca e de trecere sau nu
pesse: asa..
George Grosu: faci cate o clasa pentru fiecare mod de calcul a mediei
George Grosu: si pentru celelalte ... adik student si obiecte
George Grosu: si o interfata
George Grosu: in care alegerea clasei de calcul a mediei este facuta de sablonul
Factory nu siu cum
George Grosu: am luat 8
George Grosu: ca ne-a lasat 6 ore
George Grosu: cu internetul la dispozitie
George Grosu: adik dupa 6 ore am plecat eu
George Grosu: ca nu m-a dat afara
lui teo i-a dat d facut o lista cu generics,iar folosind adaptorul sa formeze pana
la urma o coada, apoi sa faca o interfata cu asteaMircea Dan Potur: suna interesant
pesse: Lista simplu inlantuita, generic stack,. pt arbori->3 panneluri+observer,
Calc, server, factoryMethod, graf, designPatterns, AspectJ+Adapter
pesse: tot lui teiar la celalat pct folosind aspectj sa faca suna,produsul si media
unor nr si sa le puna intr-o interfata
Conversation with filiobogdan
(03:18:54 PM) filiobogdan: subiecte date
(03:18:57 PM) filiobogdan:
1.Ralizati o aplicatioe care sa prezintye grafic o lista simplu inlantuita de elemente(numere), se deseneaza
nodurile si legaturile dintre ele.nodul curent este evident. Se ofera butoane pt: repozitionarea nodului
curent la inceputul listei, trecerea la urmatorul nod, stergere nod curent si,printr-un text, introducerea unui
nou nod inainte/dupa cel curent.
Concepeti diagrama de clase/interfete.
2.
Se cere implementarea unei stive cu urmatoarea interfata:push si offer(adauga element,in caz de depasire
capacitate, prima functie genereaza exceptie, iar a doua returneaza false),element si peek(returneaza
primul element din coada, daca nu mai sunt elemente, primafunctie genereaza exceptie, iar a doua
returneaza null), pop si pool(similar cu functiile anterioare, decat ca elementul returnat
(03:20:14 PM) filiobogdan: este si scos din coada)
Concepeti o interfata pt stiva si o implementare a acestei stive. elementele stivei pot fi d orice tip(folosityi
tipuri generice). Realizati clasele exceptie corespunzatoare cerintelor.
Concepeti diagrama d clase/interfete
Realizati o aplicatie (consola sau Swing)pentru testare
PS:dati un semn d viata daca ati primit msg ca sa stiu daca va mai trimit odata sau nu;)
Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.
Date: Fri, 6 Jul 2007 23:13:35 -0700 (PDT)
From: "punk 4 life" <cojan4punk@yahoo.com>
Subject: ce kkt!!
To: "punk 4 life" <cojan4punk@yahoo.com>, "balenush" <fia725@yahoo.com>
HTML Attachment [ Scan and Save to Computer ]
nasol =))
-----------------
..from cojan
(03:20:19 PM) filiobogdan: Se cere implementarea unei cozi cu urmatoarea interfata: add si
offer(adauga element,in caz de depasire capacitate,prima functie genereaza
exceptie,iar a doua returneaza false),element si peek(returneaza primul
element din coada, daca nu mai sunt elemente, prima functie genereaza
exceptie, iar a doua returneaza null),remove si poll(similar cu functiile
anterioare,decat ca elementul returnat este si scos din coada).
Concepeti o interfata pentru coada si o implementare a acestei cozi.
Elementele cozii sunt numere. Realizati clasele exceptie corespunzatoare
cerintelor.
Concepeti diagrama de clase/interfete.
Realizati o aplicatie(consola/swing) pentru testare.
Folosind AspectJ aplicati un filtru asupra numerelor introduse in
coada(de ex numerele negative nu vor fi introduse
(03:20:37 PM) filiobogdan: Cand un numar nu este
introdus, un mesaj corespunzator va fi afisate la consola.
Realizati o aplicatie care sa ajute la setarea orei. O componenta
grafica trebuie sa cuprinda texte prin care se poate seta ora si minutele,
iar o alta componenta grafica trebuie sa afiseze un ceas realistic
grafic, cu minutare si secundar. Cele 2 componente sunt legate prin
pattern-ul observer, si trebuie sa reflecte aceeasi ora.
Concepeti diagrama de clase/interfete
Calculator
package pack;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class Calc extends JFrame implements ActionListener{
private JTextField txtDisplay;
private CalcModel model;
public Calc(){
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
pack();
model = new DefaultCalcModel();
}
private void initComponents(){
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
txtDisplay = new JTextField();
txtDisplay.setEditable(false);
txtDisplay.setBackground(Color.WHITE);
txtDisplay.setHorizontalAlignment(JTextField.RIGHT);
add(txtDisplay,BorderLayout.NORTH);
Commands[] cmdButtons = Commands.values();
// group 1
JPanel pnlGroup1 = new JPanel();
for (int btnIndex = 0; btnIndex < 3; btnIndex++) {
CommandButton btn = new CommandButton(cmdButtons[btnIndex]);
btn.addActionListener(this);
pnlGroup1.add(btn);
}
add(pnlGroup1, BorderLayout.EAST);
// group2
JPanel pnlGroup2 = new JPanel(new GridLayout(4, 5, 5, 5));
for (int btnIndex = 3; btnIndex < cmdButtons.length; btnIndex++) {
CommandButton btn = new CommandButton(cmdButtons[btnIndex]);
btn.addActionListener(this);
pnlGroup2.add(btn);
}
add(pnlGroup2, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e){
CommandButton btn = (CommandButton) e.getSource();
model.processCommand(btn.getCommand());
txtDisplay.setText(model.getDisplayText());
}
}
package pack;
public interface CalcModel {
void processCommand(Commands cmd);
String getDisplayText();
}
package pack;
import javax.swing.JButton;
@SuppressWarnings("serial")
public class CommandButton extends JButton {
private Commands cmd;
public Commands getCommand() {
return cmd;
}
public CommandButton(Commands cmd) {
super(cmd.displayText());
this.cmd = cmd;
}
}
package pack;
public enum Commands {
BACKSPACE("Backspace"),
CE("CE"),
C("C"),
NR_7("7", 7),
NR_8("8", 8),
NR_9("9", 9),
DIV("/"),
SQRT("sqrt"),
NR_4("4", 4),
NR_5("5", 5),
NR_6("6", 6),
MUL("*"),
MOD("%"),
NR_1("1", 1),
NR_2("2", 2),
NR_3("3", 3),
MINUS("-"),
DIV_BY("1/x"),
NR_0("0", 0),
PLUS_MINUS("+/-"),
PERIOD("."),
PLUS("+"), EQUALS("=");
private int number;
private String displayText;
int number() {
return number;
}
String displayText() {
return displayText;
}
Commands(String displayText) {
this(displayText, -1);
}
Commands(String displayText, int number) {
this.displayText = displayText;
this.number = number;
}
}
package pack;
public class DefaultCalcModel implements CalcModel {
private double currentRezult;
private double currentValue;
private String operatie;
private int flag;
private double k;
public DefaultCalcModel() {
currentRezult = 0;
currentValue = 0;
}
public void processCommand(Commands cmd) {
if (cmd.number() != -1) {
addCifre(cmd.number());
}
else {
switch (cmd) {
case BACKSPACE:
break;
case CE:
currentValue = 0;
break;
case C:
currentValue = 0;
currentRezult = 0;
break;
case MUL:
flag=0;
currentRezult=currentValue;
currentValue=0;
operatie="*";
break;
case DIV:
flag=0;
currentRezult=currentValue;
currentValue=0;
operatie="/";
break;
case MINUS:
flag=0;
currentRezult=currentValue-currentRezult;
currentValue=0;
operatie="-";
break;
case PLUS:
flag=0;
System.out.println(currentValue);
currentRezult=currentValue+currentRezult;
System.out.println(currentRezult);
currentValue=0;
operatie="+";
break;
case MOD:
flag=0;
currentRezult=currentValue;
currentValue=0;
operatie="%";
break;
case DIV_BY:
flag=0;
currentRezult=currentValue;
currentValue=1/currentRezult;
break;
case PLUS_MINUS:
flag=0;
currentRezult=currentValue;
currentRezult=(-1)*currentRezult;
currentValue=currentRezult;
System.out.println(currentValue);
break;
case SQRT:
flag=0;
currentRezult=currentValue;
currentValue=Math.sqrt(currentRezult);
break;
case PERIOD:
k=0;
flag=1;
break;
case EQUALS:
if(operatie.compareTo("*")==0)
{
currentValue*=currentRezult;
}
else
{
if(operatie.compareTo("/")==0)
{
currentRezult/=currentValue;
currentValue=currentRezult;
}
else
{
if(operatie.compareTo("-")==0)
{
currentRezult-=currentValue;
currentValue=currentRezult;
}
else
if(operatie.compareTo("+")==0)
{
currentValue+=currentRezult;
}
else
{
if(operatie.compareTo("%")==0)
{
currentRezult%=currentValue;
currentValue=currentRezult;
}
else
{
currentValue=Math.sqrt(currentRezult);
}
}
}
}
break;
}
}
}
public String getDisplayText() {
return ""+currentValue;
}
private void addCifre(int cifre) {
if(flag==0)
{
currentValue=currentValue*10+cifre;
}
else
{
k++;
double r=Math.pow(10, k);
currentValue=(currentValue*r+cifre)/r;
}
}
}
package pack;
public class Main {
public static void main(String[] args) {
new Calc();
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class Calc extends JFrame implements ActionListener{
private JTextField txtDisplay;
private CalcModel model;
public Calc(){
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
pack();
model = new DefaultCalcModel();
}
private void initComponents(){
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
txtDisplay = new JTextField();
txtDisplay.setEditable(false);
txtDisplay.setBackground(Color.WHITE);
txtDisplay.setHorizontalAlignment(JTextField.RIGHT);
add(txtDisplay,BorderLayout.NORTH);
Commands[] cmdButtons = Commands.values();
// group 1
JPanel pnlGroup1 = new JPanel();
for (int btnIndex = 0; btnIndex < 3; btnIndex++) {
CommandButton btn = new CommandButton(cmdButtons[btnIndex]);
btn.addActionListener(this);
pnlGroup1.add(btn);
}
add(pnlGroup1, BorderLayout.EAST);
// group2
JPanel pnlGroup2 = new JPanel(new GridLayout(4, 5, 5, 5));
for (int btnIndex = 3; btnIndex < cmdButtons.length; btnIndex++) {
CommandButton btn = new CommandButton(cmdButtons[btnIndex]);
btn.addActionListener(this);
pnlGroup2.add(btn);
}
add(pnlGroup2, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e){
CommandButton btn = (CommandButton) e.getSource();
model.processCommand(btn.getCommand());
txtDisplay.setText(model.getDisplayText());
}
}
package pack;
public interface CalcModel {
void processCommand(Commands cmd);
String getDisplayText();
}
package pack;
import javax.swing.JButton;
@SuppressWarnings("serial")
public class CommandButton extends JButton {
private Commands cmd;
public Commands getCommand() {
return cmd;
}
public CommandButton(Commands cmd) {
super(cmd.displayText());
this.cmd = cmd;
}
}
package pack;
public enum Commands {
BACKSPACE("Backspace"),
CE("CE"),
C("C"),
NR_7("7", 7),
NR_8("8", 8),
NR_9("9", 9),
DIV("/"),
SQRT("sqrt"),
NR_4("4", 4),
NR_5("5", 5),
NR_6("6", 6),
MUL("*"),
MOD("%"),
NR_1("1", 1),
NR_2("2", 2),
NR_3("3", 3),
MINUS("-"),
DIV_BY("1/x"),
NR_0("0", 0),
PLUS_MINUS("+/-"),
PERIOD("."),
PLUS("+"), EQUALS("=");
private int number;
private String displayText;
int number() {
return number;
}
String displayText() {
return displayText;
}
Commands(String displayText) {
this(displayText, -1);
}
Commands(String displayText, int number) {
this.displayText = displayText;
this.number = number;
}
}
package pack;
public class DefaultCalcModel implements CalcModel {
private double currentRezult;
private double currentValue;
private String operatie;
private int flag;
private double k;
public DefaultCalcModel() {
currentRezult = 0;
currentValue = 0;
}
public void processCommand(Commands cmd) {
if (cmd.number() != -1) {
addCifre(cmd.number());
}
else {
switch (cmd) {
case BACKSPACE:
break;
case CE:
currentValue = 0;
break;
case C:
currentValue = 0;
currentRezult = 0;
break;
case MUL:
flag=0;
currentRezult=currentValue;
currentValue=0;
operatie="*";
break;
case DIV:
flag=0;
currentRezult=currentValue;
currentValue=0;
operatie="/";
break;
case MINUS:
flag=0;
currentRezult=currentValue-currentRezult;
currentValue=0;
operatie="-";
break;
case PLUS:
flag=0;
System.out.println(currentValue);
currentRezult=currentValue+currentRezult;
System.out.println(currentRezult);
currentValue=0;
operatie="+";
break;
case MOD:
flag=0;
currentRezult=currentValue;
currentValue=0;
operatie="%";
break;
case DIV_BY:
flag=0;
currentRezult=currentValue;
currentValue=1/currentRezult;
break;
case PLUS_MINUS:
flag=0;
currentRezult=currentValue;
currentRezult=(-1)*currentRezult;
currentValue=currentRezult;
System.out.println(currentValue);
break;
case SQRT:
flag=0;
currentRezult=currentValue;
currentValue=Math.sqrt(currentRezult);
break;
case PERIOD:
k=0;
flag=1;
break;
case EQUALS:
if(operatie.compareTo("*")==0)
{
currentValue*=currentRezult;
}
else
{
if(operatie.compareTo("/")==0)
{
currentRezult/=currentValue;
currentValue=currentRezult;
}
else
{
if(operatie.compareTo("-")==0)
{
currentRezult-=currentValue;
currentValue=currentRezult;
}
else
if(operatie.compareTo("+")==0)
{
currentValue+=currentRezult;
}
else
{
if(operatie.compareTo("%")==0)
{
currentRezult%=currentValue;
currentValue=currentRezult;
}
else
{
currentValue=Math.sqrt(currentRezult);
}
}
}
}
break;
}
}
}
public String getDisplayText() {
return ""+currentValue;
}
private void addCifre(int cifre) {
if(flag==0)
{
currentValue=currentValue*10+cifre;
}
else
{
k++;
double r=Math.pow(10, k);
currentValue=(currentValue*r+cifre)/r;
}
}
}
package pack;
public class Main {
public static void main(String[] args) {
new Calc();
}
}
Linkuri
http://users.cs.tuiasi.ro/~aalexandrescu/ - Site pp
http://www.techit.ro/tutorial_uml_5.php - Tutorial UML
https://skydrive.live.com/?cid=617755603139C621&id=617755603139C621!10809 - De la Strat.
http://andr3y23.blogspot.ro/ ----- Andrei
http://sdrv.ms/Llc0Xu
interfetele vs clase abstracte
http://thor.info.uaic.ro/~acf/java/curs/4/interfete.html
pachete java
http://www.opendrum.upt.ro/labs/poo/lab8.html
clase imbricate
http://thor.info.uaic.ro/~acf/java/curs/2/obiecte_clase.html#clase_imbricate
redefinirea metodelor
http://veclenit.3x.ro/save/java/Poo/05/Subclase.html
componente awt
http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/package-summary.html
componente swing
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/package-summary.html
I/O
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/package-summary.html
NET
http://docs.oracle.com/javase/1.4.2/docs/api/java/net/package-summary.html
Colectii
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/package-summary.html
laboratoare rezolvate
http://laboratoarepp.blogspot.ro/
M-V-C
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
FROM Turcu --http://thor.info.uaic.ro/~acf/java/curs/cursuri.html
http://www.techit.ro/tutorial_uml_5.php - Tutorial UML
https://skydrive.live.com/?cid=617755603139C621&id=617755603139C621!10809 - De la Strat.
http://andr3y23.blogspot.ro/ ----- Andrei
http://sdrv.ms/Llc0Xu
interfetele vs clase abstracte
http://thor.info.uaic.ro/~acf/java/curs/4/interfete.html
pachete java
http://www.opendrum.upt.ro/labs/poo/lab8.html
clase imbricate
http://thor.info.uaic.ro/~acf/java/curs/2/obiecte_clase.html#clase_imbricate
redefinirea metodelor
http://veclenit.3x.ro/save/java/Poo/05/Subclase.html
componente awt
http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/package-summary.html
componente swing
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/package-summary.html
I/O
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/package-summary.html
NET
http://docs.oracle.com/javase/1.4.2/docs/api/java/net/package-summary.html
Colectii
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/package-summary.html
laboratoare rezolvate
http://laboratoarepp.blogspot.ro/
M-V-C
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
FROM Turcu --http://thor.info.uaic.ro/~acf/java/curs/cursuri.html
Minichat
package pack;
import javax.swing.*;
import java.io.*;
import java.net.*;
class ClientWorker implements Runnable {
private Socket client;
private JTextArea textArea;
ClientWorker(Socket client, JTextArea textArea) {
this.client = client;
this.textArea = textArea;
}
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
line = in.readLine();
out.println(line);
textArea.append("\n");
textArea.append(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
import javax.swing.*;
import java.io.*;
import java.net.*;
class ClientWorker implements Runnable {
private Socket client;
private JTextArea textArea;
ClientWorker(Socket client, JTextArea textArea) {
this.client = client;
this.textArea = textArea;
}
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
line = in.readLine();
out.println(line);
textArea.append("\n");
textArea.append(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
Thread
package pack;
import java.io.*;
import java.util.*;
public class fileWriterThread extends Thread {
BufferedWriter bw;
BufferedReader br;
public fileWriterThread(BufferedWriter bw, BufferedReader br) {
this.bw = bw;
this.br = br;
}
public void run() {
try {
while (br.ready()) {
String readln = br.readLine();
StringTokenizer st = new StringTokenizer(readln," ");
while (st.hasMoreTokens()) {
synchronized (bw) {
bw.write(st.nextToken() + '\n');
}
}
}
br.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(new File("writeme"))));
fileWriterThread th1 = new fileWriterThread(bw, new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("first")))));
fileWriterThread th2 = new fileWriterThread(bw, new BufferedReader(
new InputStreamReader(new FileInputStream(
new File("second")))));
fileWriterThread th3 = new fileWriterThread(bw, new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("third")))));
th1.start();
th2.start();
th3.start();
while (th1.isAlive() || th2.isAlive() || th3.isAlive()) {
sleep(100);
}
System.out.println("Finished");
bw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
import java.io.*;
import java.util.*;
public class fileWriterThread extends Thread {
BufferedWriter bw;
BufferedReader br;
public fileWriterThread(BufferedWriter bw, BufferedReader br) {
this.bw = bw;
this.br = br;
}
public void run() {
try {
while (br.ready()) {
String readln = br.readLine();
StringTokenizer st = new StringTokenizer(readln," ");
while (st.hasMoreTokens()) {
synchronized (bw) {
bw.write(st.nextToken() + '\n');
}
}
}
br.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(new File("writeme"))));
fileWriterThread th1 = new fileWriterThread(bw, new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("first")))));
fileWriterThread th2 = new fileWriterThread(bw, new BufferedReader(
new InputStreamReader(new FileInputStream(
new File("second")))));
fileWriterThread th3 = new fileWriterThread(bw, new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("third")))));
th1.start();
th2.start();
th3.start();
while (th1.isAlive() || th2.isAlive() || th3.isAlive()) {
sleep(100);
}
System.out.println("Finished");
bw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Stack
package lab3;
public interface Stack <T>{
public boolean isEmpty (T[] a, int dim);
public boolean isFull (T[] a, int dim);
public void push(T k) throws StackFullException ;
public boolean offer (T k);
public T pop() throws StackEmptyException;
public T pool ();
public T peek() throws StackInvalidArgumentException;
public T element ();
}
package lab3;
public class ArrayStack<T> implements Stack<T> {
private T[] a;
private int dim;
@SuppressWarnings("unchecked")
public ArrayStack()
{
this.a=(T[])(new Object[5]);
this.dim=-1;
}
public boolean isEmpty(T[] a, int dim)
{
if (-1==dim)
{
return true;
}
else
{
return false;
}
}
public boolean isFull(T[] a, int dim)
{
if (4==dim)
{
return true;
}
else
{
return false;
}
}
public void push (T k) throws StackFullException
{
if (isFull(a,dim))
throw new StackFullException();
dim=dim+1;
a[dim]=k;
}
public boolean offer(T k)
{
if (isFull(a,dim))
{
return false;
}
else
{
dim=dim+1;
a[dim]=k;
return true;
}
}
public T pop() throws StackEmptyException
{
if (isEmpty(a,dim))
{
throw new StackEmptyException();
}
T k;
k=a[dim];
dim=dim-1;
return k;
}
public T pool()
{
if (isEmpty(a,dim))
{
return null;
}
else
{
T k;
k=a[dim];
dim=dim-1;
return k;
}
}
public T element()
{
if (isEmpty(a,dim))
{
return null;
}
else
{
return a[dim];
}
}
public T peek() throws StackInvalidArgumentException
{
if (isEmpty(a,dim))
throw new StackInvalidArgumentException();
return a[dim];
}
}
package lab3;
public class StackEmptyException extends Throwable {
private static final long serialVersionUID = 1L;
public String getMessage()
{
return "Exceptie: Stiva goala!";
}
}
package lab3;
public class StackFullException extends Throwable {
private static final long serialVersionUID = 1L;
public String getMessage()
{
return "Exceptie: Stiva plina!";
}
}
package lab3;
public class StackInvalidArgumentException extends Throwable {
private static final long serialVersionUID = 1L;
public String getMessage()
{
return "Exceptie: Argumentul este invalid!";
}
}
package lab3;
public class Test {
public static void main(String args[])
{
Stack <Integer> mystack=new ArrayStack <Integer> ();
Integer s=mystack.element();
System.out.println(s);
Integer s1=mystack.pool();
System.out.println(s1);
mystack.offer(10);
System.out.println(mystack.element());
System.out.println(mystack.pool());
System.out.println(mystack.pool());
try{
Integer vf1;
vf1=mystack.peek();
System.out.println(vf1);
}
catch (StackInvalidArgumentException ex){
System.out.println(ex.getMessage());
}
try{
double vf2;
vf2=mystack.pop();
System.out.println(vf2);
}
catch (StackEmptyException ex){
System.out.println(ex.getMessage());
}
try{
mystack.offer(3);
mystack.offer(5);
mystack.offer(34);
mystack.offer(86);
mystack.offer(35);
mystack.push(29);
mystack.push(103);
System.out.println(mystack.element());
}
catch (StackFullException ex){
System.out.println(ex.getMessage());
}
}
}
public interface Stack <T>{
public boolean isEmpty (T[] a, int dim);
public boolean isFull (T[] a, int dim);
public void push(T k) throws StackFullException ;
public boolean offer (T k);
public T pop() throws StackEmptyException;
public T pool ();
public T peek() throws StackInvalidArgumentException;
public T element ();
}
package lab3;
public class ArrayStack<T> implements Stack<T> {
private T[] a;
private int dim;
@SuppressWarnings("unchecked")
public ArrayStack()
{
this.a=(T[])(new Object[5]);
this.dim=-1;
}
public boolean isEmpty(T[] a, int dim)
{
if (-1==dim)
{
return true;
}
else
{
return false;
}
}
public boolean isFull(T[] a, int dim)
{
if (4==dim)
{
return true;
}
else
{
return false;
}
}
public void push (T k) throws StackFullException
{
if (isFull(a,dim))
throw new StackFullException();
dim=dim+1;
a[dim]=k;
}
public boolean offer(T k)
{
if (isFull(a,dim))
{
return false;
}
else
{
dim=dim+1;
a[dim]=k;
return true;
}
}
public T pop() throws StackEmptyException
{
if (isEmpty(a,dim))
{
throw new StackEmptyException();
}
T k;
k=a[dim];
dim=dim-1;
return k;
}
public T pool()
{
if (isEmpty(a,dim))
{
return null;
}
else
{
T k;
k=a[dim];
dim=dim-1;
return k;
}
}
public T element()
{
if (isEmpty(a,dim))
{
return null;
}
else
{
return a[dim];
}
}
public T peek() throws StackInvalidArgumentException
{
if (isEmpty(a,dim))
throw new StackInvalidArgumentException();
return a[dim];
}
}
package lab3;
public class StackEmptyException extends Throwable {
private static final long serialVersionUID = 1L;
public String getMessage()
{
return "Exceptie: Stiva goala!";
}
}
package lab3;
public class StackFullException extends Throwable {
private static final long serialVersionUID = 1L;
public String getMessage()
{
return "Exceptie: Stiva plina!";
}
}
package lab3;
public class StackInvalidArgumentException extends Throwable {
private static final long serialVersionUID = 1L;
public String getMessage()
{
return "Exceptie: Argumentul este invalid!";
}
}
package lab3;
public class Test {
public static void main(String args[])
{
Stack <Integer> mystack=new ArrayStack <Integer> ();
Integer s=mystack.element();
System.out.println(s);
Integer s1=mystack.pool();
System.out.println(s1);
mystack.offer(10);
System.out.println(mystack.element());
System.out.println(mystack.pool());
System.out.println(mystack.pool());
try{
Integer vf1;
vf1=mystack.peek();
System.out.println(vf1);
}
catch (StackInvalidArgumentException ex){
System.out.println(ex.getMessage());
}
try{
double vf2;
vf2=mystack.pop();
System.out.println(vf2);
}
catch (StackEmptyException ex){
System.out.println(ex.getMessage());
}
try{
mystack.offer(3);
mystack.offer(5);
mystack.offer(34);
mystack.offer(86);
mystack.offer(35);
mystack.push(29);
mystack.push(103);
System.out.println(mystack.element());
}
catch (StackFullException ex){
System.out.println(ex.getMessage());
}
}
}
Citire caracter cu caracter
public static void main(String[] args) throws IOException
{
File f = new File("intrare.txt");
BufferedReader br = new BufferedReader(new FileReader("intrare.txt"));
char c;
c = (char) br.read();
while(c != -1 && br.ready())
{
System.out.print(c);
c = (char) br.read();
}
}
{
File f = new File("intrare.txt");
BufferedReader br = new BufferedReader(new FileReader("intrare.txt"));
char c;
c = (char) br.read();
while(c != -1 && br.ready())
{
System.out.print(c);
c = (char) br.read();
}
}
Counting
long start = System.nanoTime();
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;
KeyListener
package pack;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyListenerTester extends Frame implements KeyListener {
private static final boolean VK_A = false;
TextField t1;
Label l1;
public KeyListenerTester(String s) {
super(s);
Panel p = new Panel();
l1 = new Label("Key Listener!");
p.add(l1);
add(p);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void keyTyped(KeyEvent e) {
l1.setText("Key Typed");
char c=e.getKeyChar();
if(c=='2')
{
System.out.println("bun");
}
}
public void keyPressed(KeyEvent e) {
l1.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l1.setText("Key Released");
}
public static void main(String[] args) {
new KeyListenerTester("Key Listener Tester");
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyListenerTester extends Frame implements KeyListener {
private static final boolean VK_A = false;
TextField t1;
Label l1;
public KeyListenerTester(String s) {
super(s);
Panel p = new Panel();
l1 = new Label("Key Listener!");
p.add(l1);
add(p);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void keyTyped(KeyEvent e) {
l1.setText("Key Typed");
char c=e.getKeyChar();
if(c=='2')
{
System.out.println("bun");
}
}
public void keyPressed(KeyEvent e) {
l1.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l1.setText("Key Released");
}
public static void main(String[] args) {
new KeyListenerTester("Key Listener Tester");
}
}
Mouse Listener Draw Rectangle
package pack;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class MouseTracker4July extends JFrame
implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private JLabel mousePosition;
int x, y;
int x1, x2, y1, y2;
int w, h;
private JLabel recStart;
private JLabel recStop;
private JLabel cords;
// set up GUI and register mouse event handlers
public MouseTracker4July()
{
super( "Rectangle Drawer" );
mousePosition = new JLabel();
mousePosition.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add( mousePosition, BorderLayout.CENTER );
JLabel text1 = new JLabel();
text1.setText( "At the center the mouse pointer's coordinates will be displayed." );
getContentPane().add( text1, BorderLayout.SOUTH );
recStart = new JLabel();
getContentPane().add(recStart, BorderLayout.WEST);
recStop = new JLabel();
getContentPane().add(recStop, BorderLayout.EAST);
cords = new JLabel();
getContentPane().add(cords, BorderLayout.NORTH);
addMouseListener( this ); // listens for own mouse and
addMouseMotionListener( this ); // mouse-motion events
setSize( 800, 600 );
setVisible( true );
}
// MouseListener event handlers
// handle event when mouse released immediately after press
public void mouseClicked( MouseEvent event )
{
mousePosition.setText( "Clicked at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse pressed
public void mousePressed( MouseEvent event )
{
mousePosition.setText( "Pressed at [" +(x1 = event.getX()) +
", " + (y1 = event.getY()) + "]" );
recStart.setText( "Start: [" + x1 +
", " + y1 + "]" );
}
// handle event when mouse released after dragging
public void mouseReleased( MouseEvent event )
{
mousePosition.setText( "Released at [" +(x2 = event.getX()) +
", " + (y2 = event.getY()) + "]" );
recStop.setText( "End: [" + x2 +
", " + y2 + "]" );
}
// handle event when mouse enters area
public void mouseEntered( MouseEvent event )
{
mousePosition.setText( "Mouse entered at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse exits area
public void mouseExited( MouseEvent event )
{
mousePosition.setText( "Mouse outside window" );
}
// MouseMotionListener event handlers
// handle event when user drags mouse with button pressed
public void mouseDragged( MouseEvent event )
{
mousePosition.setText( "Dragged at [" + (x = event.getX()) +
", " + (y = event.getY()) + "]" );
// call repaint which calls paint
repaint();
}
// handle event when user moves mouse
public void mouseMoved( MouseEvent event )
{
mousePosition.setText( "Moved at [" + event.getX() +
", " + event.getY() + "]" );
}
public void paint(Graphics g)
{
super.paint(g); // clear the frame surface
g.drawString("Start Rec Here", x1, y1);
g.drawString("End Rec Here", x, y);
w = x1 - x;
h = y1 - y;
w = w * -1;
h = h * -1;
g.drawRect(x1, y1, w, h);
cords.setText( "w = " + w + ", h = " + h);
}
public static void main( String args[] )
{
MouseTracker4July application = new MouseTracker4July();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MouseTracker
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class MouseTracker4July extends JFrame
implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private JLabel mousePosition;
int x, y;
int x1, x2, y1, y2;
int w, h;
private JLabel recStart;
private JLabel recStop;
private JLabel cords;
// set up GUI and register mouse event handlers
public MouseTracker4July()
{
super( "Rectangle Drawer" );
mousePosition = new JLabel();
mousePosition.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add( mousePosition, BorderLayout.CENTER );
JLabel text1 = new JLabel();
text1.setText( "At the center the mouse pointer's coordinates will be displayed." );
getContentPane().add( text1, BorderLayout.SOUTH );
recStart = new JLabel();
getContentPane().add(recStart, BorderLayout.WEST);
recStop = new JLabel();
getContentPane().add(recStop, BorderLayout.EAST);
cords = new JLabel();
getContentPane().add(cords, BorderLayout.NORTH);
addMouseListener( this ); // listens for own mouse and
addMouseMotionListener( this ); // mouse-motion events
setSize( 800, 600 );
setVisible( true );
}
// MouseListener event handlers
// handle event when mouse released immediately after press
public void mouseClicked( MouseEvent event )
{
mousePosition.setText( "Clicked at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse pressed
public void mousePressed( MouseEvent event )
{
mousePosition.setText( "Pressed at [" +(x1 = event.getX()) +
", " + (y1 = event.getY()) + "]" );
recStart.setText( "Start: [" + x1 +
", " + y1 + "]" );
}
// handle event when mouse released after dragging
public void mouseReleased( MouseEvent event )
{
mousePosition.setText( "Released at [" +(x2 = event.getX()) +
", " + (y2 = event.getY()) + "]" );
recStop.setText( "End: [" + x2 +
", " + y2 + "]" );
}
// handle event when mouse enters area
public void mouseEntered( MouseEvent event )
{
mousePosition.setText( "Mouse entered at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse exits area
public void mouseExited( MouseEvent event )
{
mousePosition.setText( "Mouse outside window" );
}
// MouseMotionListener event handlers
// handle event when user drags mouse with button pressed
public void mouseDragged( MouseEvent event )
{
mousePosition.setText( "Dragged at [" + (x = event.getX()) +
", " + (y = event.getY()) + "]" );
// call repaint which calls paint
repaint();
}
// handle event when user moves mouse
public void mouseMoved( MouseEvent event )
{
mousePosition.setText( "Moved at [" + event.getX() +
", " + event.getY() + "]" );
}
public void paint(Graphics g)
{
super.paint(g); // clear the frame surface
g.drawString("Start Rec Here", x1, y1);
g.drawString("End Rec Here", x, y);
w = x1 - x;
h = y1 - y;
w = w * -1;
h = h * -1;
g.drawRect(x1, y1, w, h);
cords.setText( "w = " + w + ", h = " + h);
}
public static void main( String args[] )
{
MouseTracker4July application = new MouseTracker4July();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MouseTracker
marți, 5 iunie 2012
Transformare baza
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class Baza2Transformer implements Transformer
{
int numar;
@SuppressWarnings("unchecked")
List listenerList = new ArrayList();
@SuppressWarnings("unchecked")
public void addNumarChangeListener(NumarChangeListener listener)
{
listenerList.add(listener);
}
public void setNumar(int numar)
{
this.numar=numar;
for(Object o:listenerList)
{
NumarChangeListener listener = (NumarChangeListener) o;
listener.numarChanged(numar);
}
}
public String toString ()
{
return Integer.toBinaryString(numar);
}
public NumarChangeListener createOwnListener()
{
return new ListenerBaza2();
}
public class ListenerBaza2 implements NumarChangeListener
{
public void numarChanged(int numar)
{
Baza2Transformer.this.numar=numar;
}
}
}
................................................
import java.util.ArrayList;
import java.util.List;
public class Baza3Transformer implements Transformer
{
int numar;
List listenerList = new ArrayList();
@SuppressWarnings("unchecked")
public void addNumarChangeListener(NumarChangeListener listener)
{
listenerList.add(listener);
}
public void setNumar(int numar)
{
this.numar=numar;
for(Object o:listenerList)
{
NumarChangeListener listener = (NumarChangeListener) o;
listener.numarChanged(numar);
}
}
public String toString ()
{
return Integer.toString(numar,3);
}
public NumarChangeListener createOwnListener()
{
return new ListenerBaza3();
}
public class ListenerBaza3 implements NumarChangeListener
{
public void numarChanged(int numar)
{
Baza3Transformer.this.numar=numar;
}
}
}
..........................................
import java.util.ArrayList;
import java.util.List;
public class Baza4Transformer implements Transformer
{
int numar;
List listenerList = new ArrayList();
public void addNumarChangeListener(NumarChangeListener listener)
{
listenerList.add(listener);
}
public void setNumar(int numar)
{
this.numar=numar;
for(Object o:listenerList)
{
NumarChangeListener listener = (NumarChangeListener) o;
listener.numarChanged(numar);
}
}
public String toString ()
{
return Integer.toString(numar,4);
}
public NumarChangeListener createOwnListener()
{
return new ListenerBaza4();
}
public class ListenerBaza4 implements NumarChangeListener
{
public void numarChanged(int numar)
{
Baza4Transformer.this.numar=numar;
}
}
}
..........................................
public class Main
{
public static void main(String[] args)
{
Transformer trans2 = TransformerFactory.createTransformer(2);
Transformer trans3 = TransformerFactory.createTransformer(3);
Transformer trans4 = TransformerFactory.createTransformer(4);
NumarChangeListener listener2 = trans2.createOwnListener();
NumarChangeListener listener3 = trans3.createOwnListener();
NumarChangeListener listener4 = trans4.createOwnListener();
trans2.addNumarChangeListener(listener3);
trans2.addNumarChangeListener(listener4);
trans3.addNumarChangeListener(listener2);
trans3.addNumarChangeListener(listener4);
trans4.addNumarChangeListener(listener2);
trans4.addNumarChangeListener(listener3);
trans3.setNumar(5);
System.out.println("Numarul initial: 5");
System.out.println("Numarul in baza 2: " + trans2.toString());
System.out.println("Numarul in baza 3: " + trans3.toString());
System.out.println("Numarul in baza 4: " + trans4.toString());
trans2.setNumar(13);
System.out.println("Numarul initial: 13");
System.out.println("Numarul in baza 2: " + trans2.toString());
System.out.println("Numarul in baza 3: " + trans3.toString());
System.out.println("Numarul in baza 4: " + trans4.toString());
}
}
.........................
public interface NumarChangeListener
{
void numarChanged(int numar);
}
........................
public interface Transformer
{
public void setNumar(int numar);
public void addNumarChangeListener(NumarChangeListener listener);
public NumarChangeListener createOwnListener();
}
........................
public class TransformerFactory
{
public static Transformer createTransformer(int baza)
{
switch(baza)
{
case 2: return new Baza2Transformer();
case 3: return new Baza3Transformer();
case 4: return new Baza4Transformer();
default: throw new RuntimeException();
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Baza2Transformer implements Transformer
{
int numar;
@SuppressWarnings("unchecked")
List listenerList = new ArrayList();
@SuppressWarnings("unchecked")
public void addNumarChangeListener(NumarChangeListener listener)
{
listenerList.add(listener);
}
public void setNumar(int numar)
{
this.numar=numar;
for(Object o:listenerList)
{
NumarChangeListener listener = (NumarChangeListener) o;
listener.numarChanged(numar);
}
}
public String toString ()
{
return Integer.toBinaryString(numar);
}
public NumarChangeListener createOwnListener()
{
return new ListenerBaza2();
}
public class ListenerBaza2 implements NumarChangeListener
{
public void numarChanged(int numar)
{
Baza2Transformer.this.numar=numar;
}
}
}
................................................
import java.util.ArrayList;
import java.util.List;
public class Baza3Transformer implements Transformer
{
int numar;
List listenerList = new ArrayList();
@SuppressWarnings("unchecked")
public void addNumarChangeListener(NumarChangeListener listener)
{
listenerList.add(listener);
}
public void setNumar(int numar)
{
this.numar=numar;
for(Object o:listenerList)
{
NumarChangeListener listener = (NumarChangeListener) o;
listener.numarChanged(numar);
}
}
public String toString ()
{
return Integer.toString(numar,3);
}
public NumarChangeListener createOwnListener()
{
return new ListenerBaza3();
}
public class ListenerBaza3 implements NumarChangeListener
{
public void numarChanged(int numar)
{
Baza3Transformer.this.numar=numar;
}
}
}
..........................................
import java.util.ArrayList;
import java.util.List;
public class Baza4Transformer implements Transformer
{
int numar;
List listenerList = new ArrayList();
public void addNumarChangeListener(NumarChangeListener listener)
{
listenerList.add(listener);
}
public void setNumar(int numar)
{
this.numar=numar;
for(Object o:listenerList)
{
NumarChangeListener listener = (NumarChangeListener) o;
listener.numarChanged(numar);
}
}
public String toString ()
{
return Integer.toString(numar,4);
}
public NumarChangeListener createOwnListener()
{
return new ListenerBaza4();
}
public class ListenerBaza4 implements NumarChangeListener
{
public void numarChanged(int numar)
{
Baza4Transformer.this.numar=numar;
}
}
}
..........................................
public class Main
{
public static void main(String[] args)
{
Transformer trans2 = TransformerFactory.createTransformer(2);
Transformer trans3 = TransformerFactory.createTransformer(3);
Transformer trans4 = TransformerFactory.createTransformer(4);
NumarChangeListener listener2 = trans2.createOwnListener();
NumarChangeListener listener3 = trans3.createOwnListener();
NumarChangeListener listener4 = trans4.createOwnListener();
trans2.addNumarChangeListener(listener3);
trans2.addNumarChangeListener(listener4);
trans3.addNumarChangeListener(listener2);
trans3.addNumarChangeListener(listener4);
trans4.addNumarChangeListener(listener2);
trans4.addNumarChangeListener(listener3);
trans3.setNumar(5);
System.out.println("Numarul initial: 5");
System.out.println("Numarul in baza 2: " + trans2.toString());
System.out.println("Numarul in baza 3: " + trans3.toString());
System.out.println("Numarul in baza 4: " + trans4.toString());
trans2.setNumar(13);
System.out.println("Numarul initial: 13");
System.out.println("Numarul in baza 2: " + trans2.toString());
System.out.println("Numarul in baza 3: " + trans3.toString());
System.out.println("Numarul in baza 4: " + trans4.toString());
}
}
.........................
public interface NumarChangeListener
{
void numarChanged(int numar);
}
........................
public interface Transformer
{
public void setNumar(int numar);
public void addNumarChangeListener(NumarChangeListener listener);
public NumarChangeListener createOwnListener();
}
........................
public class TransformerFactory
{
public static Transformer createTransformer(int baza)
{
switch(baza)
{
case 2: return new Baza2Transformer();
case 3: return new Baza3Transformer();
case 4: return new Baza4Transformer();
default: throw new RuntimeException();
}
}
}
Student observer
package pack;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DisplayFrom extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
InputForm inputForm;
Observable obsInput;
JTextField display;
public DisplayFrom() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
inputForm = new InputForm();
obsInput = inputForm.getInputInfo();
obsInput.addObserver(new InputFormObserver());
display = new JTextField(10);
add(display);
setTitle("Observer form");
setSize(200, 100);
setLocation(200, 100);
setVisible(true);
}
private class InputFormObserver implements Observer {
public void update(Observable ob, Object o) {
doSomeUpdate();
}
}
public void doSomeUpdate() {
display.setText(inputForm.getText());
JOptionPane.showMessageDialog(DisplayFrom.this,
"This form has been updated");
}
public static void main(String args[]) {
new DisplayFrom();
}
}
.........................................
package pack;
import java.awt.event.*;
import java.util.Observable;
import javax.swing.*;
public class InputForm extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public InformDisplay inform = new InformDisplay();
JTextField input = new JTextField(10);
public InputForm() {
JPanel panel = new JPanel();
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inform.notifyObservers();
}
});
panel.add(new JLabel("Enter: "));
panel.add(input);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
getContentPane().add(panel);
setTitle("Observable form");
setSize(200, 100);
setVisible(true);
}
public Observable getInputInfo() {
return inform;
}
public String getText() {
return input.getText();
}
private class InformDisplay extends Observable {
public void notifyObservers() {
setChanged();
super.notifyObservers();
}
}
}
...................................
package pack;
import java.util.Observable;
public class MessageBoard extends Observable {
private String message;
public String getMessage() {
return message;
}
public void changeMessage(String message) {
this.message = message;
setChanged();
notifyObservers(message);
}
public static void main(String[] args) {
MessageBoard board = new MessageBoard();
Student bob = new Student();
Student joe = new Student();
board.addObserver(bob);
board.addObserver(joe);
board.changeMessage("More Homework!");
}
}
...................................
package pack;
import java.util.Observable;
import java.util.Observer;
public class Student implements Observer{
public void update(Observable o, Object arg) {
System.out.println("Message board changed: " + arg);
}
}
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DisplayFrom extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
InputForm inputForm;
Observable obsInput;
JTextField display;
public DisplayFrom() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
inputForm = new InputForm();
obsInput = inputForm.getInputInfo();
obsInput.addObserver(new InputFormObserver());
display = new JTextField(10);
add(display);
setTitle("Observer form");
setSize(200, 100);
setLocation(200, 100);
setVisible(true);
}
private class InputFormObserver implements Observer {
public void update(Observable ob, Object o) {
doSomeUpdate();
}
}
public void doSomeUpdate() {
display.setText(inputForm.getText());
JOptionPane.showMessageDialog(DisplayFrom.this,
"This form has been updated");
}
public static void main(String args[]) {
new DisplayFrom();
}
}
.........................................
package pack;
import java.awt.event.*;
import java.util.Observable;
import javax.swing.*;
public class InputForm extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public InformDisplay inform = new InformDisplay();
JTextField input = new JTextField(10);
public InputForm() {
JPanel panel = new JPanel();
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inform.notifyObservers();
}
});
panel.add(new JLabel("Enter: "));
panel.add(input);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
getContentPane().add(panel);
setTitle("Observable form");
setSize(200, 100);
setVisible(true);
}
public Observable getInputInfo() {
return inform;
}
public String getText() {
return input.getText();
}
private class InformDisplay extends Observable {
public void notifyObservers() {
setChanged();
super.notifyObservers();
}
}
}
...................................
package pack;
import java.util.Observable;
public class MessageBoard extends Observable {
private String message;
public String getMessage() {
return message;
}
public void changeMessage(String message) {
this.message = message;
setChanged();
notifyObservers(message);
}
public static void main(String[] args) {
MessageBoard board = new MessageBoard();
Student bob = new Student();
Student joe = new Student();
board.addObserver(bob);
board.addObserver(joe);
board.changeMessage("More Homework!");
}
}
...................................
package pack;
import java.util.Observable;
import java.util.Observer;
public class Student implements Observer{
public void update(Observable o, Object arg) {
System.out.println("Message board changed: " + arg);
}
}
Stiva generica
package pack;
public class Stack <T> {
private T[] v;
private int dim;
private int sp=-1;
public Stack(int dim)
{
this.dim=dim;
//v=new int[dim];
v=(T[])new Object[dim];
}
public Stack()
{
this(20);
}
public boolean isEmpty()
{
return sp==-1;
}
public boolean isFull()
{
return sp==dim-1;
}
public void push (T val) throws StackFullException, StackInvalidArgumentException
{
if (isFull())
{
throw new StackFullException();
}
else
{
if (val == null)
{
throw new StackInvalidArgumentException();
}
v[++sp]=val;
}
}
public T pop() throws StackEmptyException
{
if (isEmpty())
{
throw new StackEmptyException();
}
else
{
return v[sp--];
}
}
public T top() throws StackEmptyException
{
if (isEmpty())
{
throw new StackEmptyException();
}
else
{
return v[sp];
}
}
public static void main(String[] args)
throws Exception
{
new Frame1();
}
}
.......clasa exceptii....
package pack;
public class StackEmptyException extends Exception{
public String toString()
{
return "Stiva este goala: "+super.toString();
}
public String getMessage()
{
return "Stiva e goala"+super.getMessage();
}
}
........
package pack;
public class StackFullException extends Exception {
public String toString()
{
return "Stiva este plina: "+super.toString();
}
public String getMessage()
{
return "Stiva e plina"+super.getMessage();
}
}
...........
package pack;
public class StackInvalidArgumentException extends Exception{
public String toString()
{
return "Stiva este goala: null "+super.toString();
}
public String getMessage()
{
return "Stiva e goala: null"+super.getMessage();
}
}
..............frame....
package pack;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Frame1 extends JFrame implements ActionListener {
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btnClear;
private JTextField txtMess;
Stack <String> s=new Stack <String> ();
public Frame1() {
super("Stiva");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
pack();
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
}
private void initComponents() {
// setLayout(new FlowLayout());
setLayout(new BorderLayout());
JPanel pnlWest = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btn1 = new JButton("PUSH");
btn1.addActionListener(this);
pnlWest.add(btn1);
btn2 = new JButton("POP");
btn2.addActionListener(this);
pnlWest.add(btn2);
btn3=new JButton("TOP");
btn3.addActionListener(this);
pnlWest.add(btn3);
btn4=new JButton("Stack");
btn4.addActionListener(this);
pnlWest.add(btn4);
btnClear = new JButton("CLEAR");
btnClear.addActionListener(this);
pnlWest.add(btnClear);
add(pnlWest, BorderLayout.SOUTH);
txtMess = new JTextField();
add(txtMess);
txtMess.setBackground(Color.white);
}
public void actionPerformed(ActionEvent e) {
String a,b = null,c = null;
if (e.getSource() == btn1) {
a=txtMess.getText();
try {
s.push(a);
} catch (StackFullException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (StackInvalidArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText("Valoarea "+a+" a fost introdusa in stiva!!");
return;
}
if (e.getSource() == btn2) {
try {
b=s.pop();
} catch (StackEmptyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText("Valoarea extrasa= "+b);
return;
}
if (e.getSource() == btn3) {
try {
b=s.top();
} catch (StackEmptyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText("Valoarea din varf= "+b);
return;
}
if (e.getSource() == btn4) {
txtMess.setText("Elementele stivei: ");
do{
try {
c=s.pop();
} catch (StackEmptyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText(txtMess.getText()+c+" ");
}while (!s.isEmpty());
return;
}
if (e.getSource() == btnClear) {
txtMess.setText("");
return;
}
}
}
public class Stack <T> {
private T[] v;
private int dim;
private int sp=-1;
public Stack(int dim)
{
this.dim=dim;
//v=new int[dim];
v=(T[])new Object[dim];
}
public Stack()
{
this(20);
}
public boolean isEmpty()
{
return sp==-1;
}
public boolean isFull()
{
return sp==dim-1;
}
public void push (T val) throws StackFullException, StackInvalidArgumentException
{
if (isFull())
{
throw new StackFullException();
}
else
{
if (val == null)
{
throw new StackInvalidArgumentException();
}
v[++sp]=val;
}
}
public T pop() throws StackEmptyException
{
if (isEmpty())
{
throw new StackEmptyException();
}
else
{
return v[sp--];
}
}
public T top() throws StackEmptyException
{
if (isEmpty())
{
throw new StackEmptyException();
}
else
{
return v[sp];
}
}
public static void main(String[] args)
throws Exception
{
new Frame1();
}
}
.......clasa exceptii....
package pack;
public class StackEmptyException extends Exception{
public String toString()
{
return "Stiva este goala: "+super.toString();
}
public String getMessage()
{
return "Stiva e goala"+super.getMessage();
}
}
........
package pack;
public class StackFullException extends Exception {
public String toString()
{
return "Stiva este plina: "+super.toString();
}
public String getMessage()
{
return "Stiva e plina"+super.getMessage();
}
}
...........
package pack;
public class StackInvalidArgumentException extends Exception{
public String toString()
{
return "Stiva este goala: null "+super.toString();
}
public String getMessage()
{
return "Stiva e goala: null"+super.getMessage();
}
}
..............frame....
package pack;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Frame1 extends JFrame implements ActionListener {
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btnClear;
private JTextField txtMess;
Stack <String> s=new Stack <String> ();
public Frame1() {
super("Stiva");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
pack();
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
}
private void initComponents() {
// setLayout(new FlowLayout());
setLayout(new BorderLayout());
JPanel pnlWest = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btn1 = new JButton("PUSH");
btn1.addActionListener(this);
pnlWest.add(btn1);
btn2 = new JButton("POP");
btn2.addActionListener(this);
pnlWest.add(btn2);
btn3=new JButton("TOP");
btn3.addActionListener(this);
pnlWest.add(btn3);
btn4=new JButton("Stack");
btn4.addActionListener(this);
pnlWest.add(btn4);
btnClear = new JButton("CLEAR");
btnClear.addActionListener(this);
pnlWest.add(btnClear);
add(pnlWest, BorderLayout.SOUTH);
txtMess = new JTextField();
add(txtMess);
txtMess.setBackground(Color.white);
}
public void actionPerformed(ActionEvent e) {
String a,b = null,c = null;
if (e.getSource() == btn1) {
a=txtMess.getText();
try {
s.push(a);
} catch (StackFullException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (StackInvalidArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText("Valoarea "+a+" a fost introdusa in stiva!!");
return;
}
if (e.getSource() == btn2) {
try {
b=s.pop();
} catch (StackEmptyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText("Valoarea extrasa= "+b);
return;
}
if (e.getSource() == btn3) {
try {
b=s.top();
} catch (StackEmptyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText("Valoarea din varf= "+b);
return;
}
if (e.getSource() == btn4) {
txtMess.setText("Elementele stivei: ");
do{
try {
c=s.pop();
} catch (StackEmptyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtMess.setText(txtMess.getText()+c+" ");
}while (!s.isEmpty());
return;
}
if (e.getSource() == btnClear) {
txtMess.setText("");
return;
}
}
}
Shopping
package pack;
import java.util.ArrayList;
import java.util.List;
public class Inventory {
private List<Item> _items = new ArrayList<Item>();
public void addItem(Item item) {
_items.add(item);
}
public void removeItem(Item item) {
_items.remove(item);
}
}
...............................
package pack;
import java.util.logging.*;
public class Item {
private static Logger _logger = Logger.getLogger("cart");
private String _id;
private float _price;
public Item(String id, float price) {
_id = id;
_price = price;
}
public String getID() {
_logger.logp(Level.INFO, "Item", "getID", "Entering");
return _id;
}
public float getPrice() {
_logger.logp(Level.INFO, "Item", "getPrice", "Entering");
return _price;
}
public String toString() {
_logger.logp(Level.INFO, "Item", "toString", "Entering");
return "Item: " + _id;
}
}
............................
package pack;
import java.util.*;
public class ShoppingCart {
private List<Item> _items = new ArrayList<Item>();
public void addItem(Item item) {
_items.add(item);
}
public void removeItem(Item item) {
_items.remove(item);
}
public void empty() {
_items.clear();
}
public float totalValue() {
// unimplemented... free!
return 0;
}
}
..................................
package pack;
public class ShoppingCartOperator {
public static void addShoppingCartItem(ShoppingCart sc,
Inventory inventory, Item item) {
inventory.removeItem(item);
sc.addItem(item);
}
public static void removeShoppingCartItem(ShoppingCart sc,
Inventory inventory, Item item) {
sc.removeItem(item);
inventory.addItem(item);
}
}
.............................
package pack;
public class Test {
public static void main(String[] args) {
Inventory inventory = new Inventory();
Item item1 = new Item("1", 30);
Item item2 = new Item("2", 31);
Item item3 = new Item("3", 32);
inventory.addItem(item1);
inventory.addItem(item2);
inventory.addItem(item3);
ShoppingCart sc = new ShoppingCart();
ShoppingCartOperator.addShoppingCartItem(sc, inventory, item1);
ShoppingCartOperator.addShoppingCartItem(sc, inventory, item2);
}
}
.............................
package pack;
import org.aspectj.lang.*;
import java.util.logging.*;
public aspect TraceAspect {
private Logger _logger = Logger.getLogger("trace");
pointcut traceMethods()
: (execution(* *.*(..)) || execution(*.new(..)))
&& !within(TraceAspect);
before() : traceMethods() && !execution(String *.toString()) {
Signature sig = thisJoinPointStaticPart.getSignature();
_logger.logp(Level.INFO, sig.getDeclaringType().getName(), sig
.getName(), createParameterMessage(thisJoinPoint));
}
private String createParameterMessage(JoinPoint joinPoint) {
StringBuffer paramBuffer = new StringBuffer("\n\t[This: ");
paramBuffer.append(joinPoint.getThis());
Object[] arguments = joinPoint.getArgs();
paramBuffer.append("]\n\t[Args: (");
for (int length = arguments.length, i = 0; i < length; ++i) {
Object argument = arguments[i];
paramBuffer.append(argument);
if (i != length - 1) {
paramBuffer.append(',');
}
}
paramBuffer.append(")]");
return paramBuffer.toString();
}
}
import java.util.ArrayList;
import java.util.List;
public class Inventory {
private List<Item> _items = new ArrayList<Item>();
public void addItem(Item item) {
_items.add(item);
}
public void removeItem(Item item) {
_items.remove(item);
}
}
...............................
package pack;
import java.util.logging.*;
public class Item {
private static Logger _logger = Logger.getLogger("cart");
private String _id;
private float _price;
public Item(String id, float price) {
_id = id;
_price = price;
}
public String getID() {
_logger.logp(Level.INFO, "Item", "getID", "Entering");
return _id;
}
public float getPrice() {
_logger.logp(Level.INFO, "Item", "getPrice", "Entering");
return _price;
}
public String toString() {
_logger.logp(Level.INFO, "Item", "toString", "Entering");
return "Item: " + _id;
}
}
............................
package pack;
import java.util.*;
public class ShoppingCart {
private List<Item> _items = new ArrayList<Item>();
public void addItem(Item item) {
_items.add(item);
}
public void removeItem(Item item) {
_items.remove(item);
}
public void empty() {
_items.clear();
}
public float totalValue() {
// unimplemented... free!
return 0;
}
}
..................................
package pack;
public class ShoppingCartOperator {
public static void addShoppingCartItem(ShoppingCart sc,
Inventory inventory, Item item) {
inventory.removeItem(item);
sc.addItem(item);
}
public static void removeShoppingCartItem(ShoppingCart sc,
Inventory inventory, Item item) {
sc.removeItem(item);
inventory.addItem(item);
}
}
.............................
package pack;
public class Test {
public static void main(String[] args) {
Inventory inventory = new Inventory();
Item item1 = new Item("1", 30);
Item item2 = new Item("2", 31);
Item item3 = new Item("3", 32);
inventory.addItem(item1);
inventory.addItem(item2);
inventory.addItem(item3);
ShoppingCart sc = new ShoppingCart();
ShoppingCartOperator.addShoppingCartItem(sc, inventory, item1);
ShoppingCartOperator.addShoppingCartItem(sc, inventory, item2);
}
}
.............................
package pack;
import org.aspectj.lang.*;
import java.util.logging.*;
public aspect TraceAspect {
private Logger _logger = Logger.getLogger("trace");
pointcut traceMethods()
: (execution(* *.*(..)) || execution(*.new(..)))
&& !within(TraceAspect);
before() : traceMethods() && !execution(String *.toString()) {
Signature sig = thisJoinPointStaticPart.getSignature();
_logger.logp(Level.INFO, sig.getDeclaringType().getName(), sig
.getName(), createParameterMessage(thisJoinPoint));
}
private String createParameterMessage(JoinPoint joinPoint) {
StringBuffer paramBuffer = new StringBuffer("\n\t[This: ");
paramBuffer.append(joinPoint.getThis());
Object[] arguments = joinPoint.getArgs();
paramBuffer.append("]\n\t[Args: (");
for (int length = arguments.length, i = 0; i < length; ++i) {
Object argument = arguments[i];
paramBuffer.append(argument);
if (i != length - 1) {
paramBuffer.append(',');
}
}
paramBuffer.append(")]");
return paramBuffer.toString();
}
}
Abonați-vă la:
Postări (Atom)