file MyApplication.java
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class MyApplication {
public static void main (String args[]) {
// Create the frame
JFrame frame = new JFrame ("My Application");
// Create some components
JButton b1 = new JButton("A Button");
b1.setToolTipText("This is the left button");
JButton b2 = new JButton(new ImageIcon("middle.gif"));
b2.setToolTipText("This is the middle button");
JLabel label = new JLabel(new ImageIcon("alb.gif"));
JTextField text = new JTextField(20);
Vector items = new Vector();
for (int i=1; i<20; i++) {
items.addElement("This is item "+i);
}
JList list = new JList(items);
list.setToolTipText("Select one item");
JScrollPane listPane = new JScrollPane(list);
//Lay out the content pane.
JPanel contentPane = new JPanel();
contentPane.setLayout(new FlowLayout());
contentPane.setPreferredSize(new Dimension(300, 300));
contentPane.add(b1);
contentPane.add(b2);
contentPane.add(label);
contentPane.add(text);
contentPane.add(listPane);
frame.setContentPane(contentPane);
frame.pack();
frame.show();
}
}
setContentPane
per indicare il Panel usato per sistemare gli oggetti da inserire nel frame.
file FirstSample.java
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class FirstSample extends JPanel {
public FirstSample() {
super();
// Create some components
JButton b1 = new JButton("A Button");
b1.setToolTipText("This is the left button");
JButton b2 = new JButton(new ImageIcon("middle.gif"));
b2.setToolTipText("This is the middle button");
JLabel label = new JLabel(new ImageIcon("alb.gif"));
JTextField text = new JTextField(20);
Vector items = new Vector();
for (int i=1; i<20; i++) {
items.addElement("This is item "+i);
}
JList list = new JList(items);
list.setToolTipText("Select one item");
JScrollPane listPane = new JScrollPane(list);
//Lay out the content pane.
setLayout(new FlowLayout());
setPreferredSize(new Dimension(300, 300));
add(b1);
add(b2);
add(label);
add(text);
add(listPane);
}
public static void main (String args[]) {
JFrame frame = new JFrame("First Sample");
frame.setContentPane(new FirstSample());
frame.pack();
frame.show();
JFrame frame2 = new JFrame("Another First Sample");
frame2.setContentPane(new FirstSample());
frame2.pack();
frame2.show();
}
}
file ToolBarSample.java
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class ToolBarSample extends JPanel {
public ToolBarSample () {
super();
// Create a toolbar
JToolBar mybar = new JToolBar();
mybar.add(new JButton(new ImageIcon("open.gif")));
mybar.add(new JButton(new ImageIcon("save.gif")));
JButton cut = new JButton(new ImageIcon("cut.gif"));
cut.setToolTipText("Cut Selection");
JButton copy = new JButton(new ImageIcon("copy.gif"));
copy.setToolTipText("Copy Selection");
mybar.add(cut);
mybar.add(copy);
// Create some components
JLabel label = new JLabel(new ImageIcon("alb.gif"));
JTextArea text = new JTextArea();
//Lay out the content pane.
setLayout(new BorderLayout());
setPreferredSize(new Dimension(300, 300));
add("North", mybar);
add("South", label);
add("Center", text);
}
public static void main (String args[]) {
// Create the frame and the content
JFrame frame = new JFrame ("My Application");
ToolBarSample tb = new ToolBarSample();
frame.setContentPane(tb);
frame.pack();
frame.show();
}
}
file ScrollSample.java
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class ScrollSample extends JPanel {
public ScrollSample() {
JTextArea text = new JTextArea();
JScrollPane textPane = new JScrollPane(text);
//Lay out the pane.
setLayout(new BorderLayout());
setPreferredSize(new Dimension(300, 300));
add("Center", textPane);
}
public static void main (String args[]) {
// Create the frame
JFrame frame = new JFrame ("My Application");
ScrollSample scroll = new ScrollSample();
frame.setContentPane(scroll);
frame.pack();
frame.show();
}
}
ScrollPane e' un contenitore generico che puo' contenere qualsiasi cosa
che vorremmo poter scorrere(testo,immagini,...).
file TableSample.java
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
class MyTableModel extends AbstractTableModel {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
}
public class TableSample extends JPanel {
public TableSample() {
super();
MyTableModel dataModel = new MyTableModel();
JTable table = new JTable(dataModel);
table.setPreferredScrollableViewportSize(new Dimension(300, 100));
JScrollPane scrollpane = new JScrollPane(table);
//Lay out the content pane.
setLayout(new FlowLayout());
// setPreferredSize(new Dimension(350, 300));
add(scrollpane);
}
public static void main (String args[]) {
// Create the frame
JFrame frame = new JFrame ("Table Sample");
frame.setContentPane(new TableSample());
frame.pack();
frame.show();
}
}
file TreeSample.java
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class TreeSample extends JPanel {
public TreeSample() {
super();
// Create the tree structure
DefaultMutableTreeNode top = new DefaultMutableTreeNode("The root of all");
DefaultMutableTreeNode primo =
new DefaultMutableTreeNode ("The First Node");
top.add(primo);
primo.add(new DefaultMutableTreeNode ("The first in the first"));
primo.add(new DefaultMutableTreeNode ("The second in the first"));
DefaultMutableTreeNode second =
new DefaultMutableTreeNode ("The Second Node");
top.add(second);
second.add(new DefaultMutableTreeNode ("The first in the second"));
second.add(new DefaultMutableTreeNode ("The second in the second"));
DefaultMutableTreeNode category =
new DefaultMutableTreeNode ("Category");
second.add(category);
category.add(new DefaultMutableTreeNode("Bussines"));
category.add(new DefaultMutableTreeNode ("Science"));
JTree tree = new JTree(top);
JScrollPane scrollpane = new JScrollPane(tree);
//Lay out the content pane.
setLayout(new BorderLayout());
setPreferredSize(new Dimension(350,300));
add("Center", scrollpane);
}
public static void main (String args[]) {
TreeSample app = new TreeSample();
JFrame frame = new JFrame ("My Application");
frame.setContentPane(app);
frame.pack();
frame.show();
}
}
file SplitSample.java
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class SplitSample extends JPanel {
public SplitSample() { super();
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
TreeSample tree = new TreeSample();
ScrollSample text = new ScrollSample();
pane.setLeftComponent(tree);
pane.setRightComponent(text);
pane.setDividerLocation(150);
pane.setDividerSize(10);
//Lay out the content pane.
setPreferredSize(new Dimension(350, 300));
setLayout(new GridLayout(1,1));
add(pane, new Dimension(1,1));
}
public static void main (String args[]) { SplitSample app = new SplitSample();
JFrame frame = new JFrame ("My Application");
frame.setContentPane(app);
frame.pack();
frame.show();
}}
SplitPanel e' un contenitore generico che permette a 2 altri componenti di condividere lo stesso spazio con un separatore in mezzo che si puo' spostare a piacere.
file TabbedSample.java
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class TabbedSample extends JPanel {
public TabbedSample() {
super();
JTabbedPane tpane = new JTabbedPane();
tpane.addTab("ScrollSample", new ImageIcon("open.gif"),
new ScrollSample(), "The Previous Scroll Sample");
tpane.addTab("SplitSample", null,
new SplitSample(), null);
tpane.addTab("TreeSample", new ImageIcon("save.gif"),
new TreeSample(), "The Tree Sample");
tpane.addTab("TableSample", null,
new TableSample(), "The Table Sample");
//Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));
add(tpane);
}
public static void main (String args[]) {
TabbedSample app = new TabbedSample();
JFrame frame = new JFrame ("My Application");
frame.setContentPane(app);
frame.pack();
frame.show();
}
}
TabPanel permette a un numero qualsiasi di componenti di condividere lo
stesso spazio.
file InternalFrameSample.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class InternalFrameSample extends JFrame implements ActionListener{
JDesktopPane desktop;
JButton b1, b2, b3, b4, b5;
int offsetx=50; int offsety=50;
public InternalFrameSample() {
super("Internal Frame Demo");
desktop = new JDesktopPane();
JToolBar toolbar = new JToolBar();
b1 = new JButton ("Scroll Sample");
b2 = new JButton ("Split Sample");
b3 = new JButton ("Tree Sample");
b4 = new JButton ("Table Sample");
b5 = new JButton ("Tabs Sample");
toolbar.add(b1); b1.addActionListener(this);
toolbar.add(b2); b2.addActionListener(this);
toolbar.add(b3); b3.addActionListener(this);
toolbar.add(b4); b4.addActionListener(this);
toolbar.add(b5); b5.addActionListener(this);
//Add the desktop pane to this panel.
desktop.setLayout(new BorderLayout());
desktop.add("North", toolbar);
setContentPane(desktop);
}
public void actionPerformed (ActionEvent e) {
JInternalFrame frame;
if (e.getSource() == b1) {
createInternalFrame("Scroll", new ScrollSample());
} else if (e.getSource() == b2) {
createInternalFrame("Split", new SplitSample());
} else if (e.getSource() == b3) {
createInternalFrame("Tree", new TreeSample());
} else if (e.getSource() == b4) {
createInternalFrame("Table", new TableSample());
} else if (e.getSource() == b5) {
createInternalFrame("Tab", new TabbedSample());
}
}
public void createInternalFrame(String title, Container what) {
JInternalFrame fr = new JInternalFrame(title, true, true, true, true);
fr.setContentPane(what);
fr.setSize(300,300);
fr.setLocation(offsetx,offsety);
offsetx = offsetx+20;
offsety = offsety+20;
desktop.add(fr);
try {
fr.setSelected(true);
} catch (java.beans.PropertyVetoException e2) {}
fr.setVisible(true);
}
public static void main (String args[]) {
InternalFrameSample frame = new InternalFrameSample();
frame.pack();
frame.show();
}
}
DesktopPane permette di realizzare un vero e proprio desktop. Notate come il trattamento degli eventi e' quello di AWT.
file InternalFrameSample.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class InternalFrameSample extends JFrame implements ActionListener{
JDesktopPane desktop;
JButton b1, b2, b3, b4, b5, b6, b7,b8;
int offsetx=50; int offsety=50;
public InternalFrameSample() {
super("Internal Frame Demo");
desktop = new JDesktopPane();
JToolBar toolbar = new JToolBar();
b1 = new JButton ("Scroll");
b2 = new JButton ("Split");
b3 = new JButton ("Tree");
b4 = new JButton ("Table");
b5 = new JButton ("Tabs");
b6 = new JButton ("Motif LF");
b7 = new JButton ("Metal LF");
b8 = new JButton ("Windows LF");
toolbar.add(b1); b1.addActionListener(this);
toolbar.add(b2); b2.addActionListener(this);
toolbar.add(b3); b3.addActionListener(this);
toolbar.add(b4); b4.addActionListener(this);
toolbar.add(b5); b5.addActionListener(this);
toolbar.add(b6); b6.addActionListener(this);
toolbar.add(b7); b7.addActionListener(this);
toolbar.add(b8); b8.addActionListener(this);
//Add the desktop pane to this panel.
desktop.setLayout(new BorderLayout());
desktop.add("North", toolbar);
setContentPane(desktop);
}
public void actionPerformed (ActionEvent e) {
JInternalFrame frame;
if (e.getSource() == b1) {
createInternalFrame("Scroll", new ScrollSample());
} else if (e.getSource() == b2) {
createInternalFrame("Split", new SplitSample());
} else if (e.getSource() == b3) {
createInternalFrame("Tree", new TreeSample());
} else if (e.getSource() == b4) {
createInternalFrame("Table", new TableSample());
} else if (e.getSource() == b5) {
createInternalFrame("Tab", new TabbedSample());
} else if (e.getSource() == b6) {
changeLF(1);
} else if (e.getSource() == b7) {
changeLF(2);
} else if (e.getSource() == b8) {
changeLF(3);
}
}
public void changeLF(int what) {
String lf ="";
if (what==1) { lf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";}
else if (what==2) { lf = "javax.swing.plaf.metal.MetalLookAndFeel";}
else if (what==3) { lf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";}
try {
UIManager.setLookAndFeel(lf);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) { e.printStackTrace(); }
}
public void createInternalFrame(String title, Container what) {
JInternalFrame fr = new JInternalFrame(title, true, true, true, true);
fr.setContentPane(what);
fr.setSize(300,300);
fr.setLocation(offsetx,offsety);
offsetx = offsetx+20;
offsety = offsety+20;
desktop.add(fr);
try {
fr.setSelected(true);
} catch (java.beans.PropertyVetoException e2) {}
fr.setVisible(true);
}
public static void main (String args[]) {
InternalFrameSample frame = new InternalFrameSample();
frame.pack();
frame.show();
}
}
changLF permette di cambiare
l'apparenza del desktop (Look e Feel) solo cliccando un bottone.
| nome | implementa | modificandolo possiamo cambiare | Esempio |
| Model Object | Modello dei dati e dello stato | i dati | TableModel definisce i dati da caricare in una tabella |
| ChangeListener | Indica cosa fare quando il modello cambia | ||
| ComponentObject | Rappresentazione dell'oggetto:prende i dati dai 2 oggetti precedenti | Le proprieta' fisiche dell'oggetto | JTable |
| UI Object | Rappresentazione dell'oggetto:fa l'effettivo disegno prendendo i dati dall'oggetto precedente | Il Look e Feel dell'oggetto |
import java.util.*;
import javax.swing.tree.*;
import javax.swing.*;
import java.awt.*;
public class EsempioTree extends JApplet {
public void init() {
// Create the tree structure
DefaultMutableTreeNode top = new DefaultMutableTreeNode("The root of all");
DefaultMutableTreeNode primo =
new DefaultMutableTreeNode ("The First Node");
top.add(primo);
primo.add(new DefaultMutableTreeNode ("The first in the first"));
primo.add(new DefaultMutableTreeNode ("The second in the first"));
DefaultMutableTreeNode second =
new DefaultMutableTreeNode ("The Second Node");
top.add(second);
second.add(new DefaultMutableTreeNode ("The first in the second"));
second.add(new DefaultMutableTreeNode ("The second in the second"));
DefaultMutableTreeNode category =
new DefaultMutableTreeNode ("Category");
second.add(category);
category.add(new DefaultMutableTreeNode("Bussines"));
category.add(new DefaultMutableTreeNode ("Science"));
JTree tree = new JTree(top);
JScrollPane scrollpane = new JScrollPane(tree);
//Lay out the content pane.
getContentPane().setLayout(new BorderLayout());
scrollpane.setPreferredSize(new Dimension(350,300));
getContentPane().add("Center", scrollpane);
}
}
getContentPane()
setPreferredSize
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Pick1 extends JApplet implements ActionListener{
int maxcol = 158;
Color col[]=new Color[maxcol];
PickCanvas disegno;
Button b1;
Panel p1,p2;
TextField c1val,c2val;
Label l1,l2;
double c1,c2;
public void init(){
c1 = Math.random()-5.;
c2 = Math.random()-5.;
Julia1.setcol(col);
disegno = new PickCanvas(this);
p1 = new Panel();
p1.add(l1 = new Label("c1"));
p1.add(c1val=new TextField(5));
c1val.setText(Double.toString(c1));
p1.add(l2 = new Label("c2"));
p1.add(c2val=new TextField(5));
c2val.setText(Double.toString(c2));
p2 = new Panel();
p2.add(b1 = new Button("Disegna"));
b1.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North",p1);
getContentPane().add("Center",disegno);
getContentPane().add("South",p2);
disegno.repaint();
}
public void actionPerformed(ActionEvent e){
c1 = Double.valueOf(c1val.getText()).doubleValue();
if(c1<-5.)c1=-5.;
if(c1 > -.4)c1=-4.;
c2 = Double.valueOf(c2val.getText()).doubleValue();
if(c2<-5.)c2=-5.;
if(c2 > -.4)c2=-4.;
disegno.repaint();
}
}
class PickCanvas extends JPanel{
Pick1 appl;
PickCanvas(Pick1 appl1){
super();
appl=appl1;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int i,j,ncol;
for(i=0;i<getSize().width;i++){
for(j=0;j<getSize().height;j++){
ncol = (int)(appl.c1*(Math.sin(-11.+appl.c2*i)+Math.sin(-12.+appl.c2*j)));
ncol = Math.abs(ncol)%appl.maxcol+1;
g.setColor(appl.col[ncol]);
g.fillRect(i,j,1,1);
}
}
}
}
getContentPane
Se i componenti Swing sono lightweight essi non sono purtroppo
leggeri in termini di consumo di risorse. Un programma Swing e' molto piu'
lento e voluminoso di un programma AWT. Questo e' un problema specie per
gli applet che gia' sono penalizzati dalla lentezza di Java. Un'alternativa
leggera in termini di consumo di risorse a Java e' Javascript.
Se potete fare qualcosa anche in Javascript, allora non pensateci 2 volte,
fatelo in Javascript. Purtroppo Javascript e' limitato e non permette di fare
molte cose. E' possibile pero con le ultime versioni dei browsers scrivere
una rudimentale interfaccia per un programma Java direttamente in Javascript.
Applet 13:Riscrivete l'applet 17 della lezione precedente sostituendo l'interfaccia AWT con un'interfaccia Javascript . S
import java.awt.*;
import java.applet.*;
public class Pick2 extends Applet {
int maxcol = 158;
Color col[]=new Color[maxcol];
PickCanvas2 disegno;
Panel p1;
TextField c1val,c2val;
Label l1,l2;
double c1=-4.5,c2=-4.5;
public void init(){
p1 = new Panel();
p1.add(l1 = new Label("c1"));
p1.add(c1val=new TextField(5));
c1val.setText(Double.toString(c1));
p1.add(l2 = new Label("c2"));
p1.add(c2val=new TextField(5));
c2val.setText(Double.toString(c2));
Julia1.setcol(col);
disegno = new PickCanvas2(this);
setLayout(new BorderLayout());
add("North",p1);
add("Center",disegno);
disegno.repaint();
}
public void startdisegno(String s1,String s2){
System.out.println(s1+" "+s2);
c1 = Double.valueOf(s1).doubleValue();
c2 = Double.valueOf(s2).doubleValue();
c1val.setText(Double.toString(c1));
c2val.setText(Double.toString(c2));
disegno.repaint();
}
public void startrandom(){
c1 = Math.random()-5.;
c1val.setText(Double.toString(c1).substring(0,5));
c2 = Math.random()-5.;
c2val.setText(Double.toString(c2).substring(0,5));
disegno.repaint();
}
class PickCanvas2 extends Canvas{
Pick2 appl;
PickCanvas2(Pick2 appl1){
super();
appl=appl1;
}
public void paint(Graphics g){
int i,j,ncol;
for(i=0;i < getSize().width;i++){
for(j=0;j < getSize().height;j++){
ncol = (int)(appl.c1*(Math.sin(-11.+appl.c2*i)+Math.sin(-12.+appl.c2*j)));
ncol = Math.abs(ncol)%appl.maxcol+1;
g.setColor(appl.col[ncol]);
g.fillRect(i,j,1,1);
}
}
}
}
}
startdisegno e startrandom richiamati dal programma Javascript quando si clicca il tasto "Fai il disegno" e quando si clicca su "Qui...".
name="nomeapplet"
MAYSCRIPT="MAYSCRIPT"