Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ЕВ-4791

.pdf
Скачиваний:
26
Добавлен:
07.03.2016
Размер:
3 Мб
Скачать

if(i < a.length - 1) result.append(", ");

}

result.append("]"); return result.toString();

}

public static String toString(int[] a) { StringBuffer result = new StringBuffer("[");

for(int i = 0; i < a.length; i++) { result.append(a[i]);

if(i < a.length - 1) result.append(", ");

}

result.append("]"); return result.toString();

}

public static String toString(long[] a) { StringBuffer result = new StringBuffer("[");

for(int i = 0; i < a.length; i++) { result.append(a[i]);

if(i < a.length - 1) result.append(", ");

}

result.append("]"); return result.toString();

}

public static String toString(float[] a) { StringBuffer result = new StringBuffer("[");

for(int i = 0; i < a.length; i++) { result.append(a[i]);

if(i < a.length - 1) result.append(", ");

}

result.append("]"); return result.toString();

}

public static String toString(double[] a) { StringBuffer result = new StringBuffer("[");

for(int i = 0; i < a.length; i++) { result.append(a[i]);

if(i < a.length - 1) result.append(", ");

}

result.append("]"); return result.toString();

}

// Fill an array using a generator:

public static void fill(Object[] a, Generator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(Object[] a, int from, int to, Generator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void

fill(boolean[] a, BooleanGenerator gen) { fill(a, 0, a.length, gen);

}

81

public static void

fill(boolean[] a, int from, int to,BooleanGenerator gen){ for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(byte[] a, ByteGenerator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(byte[] a, int from, int to, ByteGenerator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(char[] a, CharGenerator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(char[] a, int from, int to, CharGenerator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(short[] a, ShortGenerator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(short[] a, int from, int to, ShortGenerator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(int[] a, IntGenerator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(int[] a, int from, int to, IntGenerator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(long[] a, LongGenerator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(long[] a, int from, int to, LongGenerator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(float[] a, FloatGenerator gen) { fill(a, 0, a.length, gen);

}

public static void

fill(float[] a, int from, int to, FloatGenerator gen) { for(int i = from; i < to; i++)

a[i] = gen.next();

}

public static void fill(double[] a, DoubleGenerator gen){ fill(a, 0, a.length, gen);

}

public static void

fill(double[] a, int from, int to, DoubleGenerator gen) { for(int i = from; i < to; i++)

82

a[i] = gen.next();

}

private static Random r = new Random(); public static class

RandBooleanGenerator implements BooleanGenerator { public boolean next() { return r.nextBoolean(); }

}

public static class

RandByteGenerator implements ByteGenerator { public byte next() { return (byte)r.nextInt(); }

}

private static String ssource = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

private static char[] src = ssource.toCharArray(); public static class

RandCharGenerator implements CharGenerator { public char next() {

return src[r.nextInt(src.length)];

}

}

public static class RandStringGenerator implements Generator { private int len;

private RandCharGenerator cg = new RandCharGenerator(); public RandStringGenerator(int length) {

len = length;

}

public Object next() { char[] buf = new char[len]; for(int i = 0; i < len; i++) buf[i] = cg.next();

return new String(buf);

}

}

public static class

RandShortGenerator implements ShortGenerator { public short next() { return (short)r.nextInt(); }

}

public static class

RandIntGenerator implements IntGenerator { private int mod = 10000;

public RandIntGenerator() {}

public RandIntGenerator(int modulo) { mod = modulo; } public int next() { return r.nextInt(mod); }

}

public static class

RandLongGenerator implements LongGenerator { public long next() { return r.nextLong(); }

}

public static class

RandFloatGenerator implements FloatGenerator { public float next() { return r.nextFloat(); }

}

public static class

RandDoubleGenerator implements DoubleGenerator { public double next() {return r.nextDouble();}

}

}

interface Generator { Object next(); } interface BooleanGenerator { boolean next(); }

83

interface ByteGenerator { byte next(); } interface CharGenerator { char next(); } interface DoubleGenerator { double next(); } interface FloatGenerator { float next(); } interface IntGenerator { int next(); } interface LongGenerator { long next(); } interface ShortGenerator { short next(); }

Код html-файла

<HTML><TITLE> Applet</TITLE>

<APPLET CODE= " TextPane.class" WIDTH = 475 HEIGHT = 425></APPLET > </HTML>

Рис. 13.1. Результати дії аплета TextPane

Приклад 2. Використання прапорців.

import javax.swing.*; import java.awt.event.*; import java.awt.*;

//import com.bruceeckel.swing;

public class CheckBoxes extends JApplet{ JTextArea t = new JTextArea(6,15); JCheckBox

cb1 = new JCheckBox("Прапорець 1"), cb2 = new JCheckBox("Прапорець 2"), cb3 = new JCheckBox("Прапорець 3");

public void init(){ cb1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ trace("1",cb1);

}

});

cb2.addActionListener(new ActionListener(){

84

public void actionPerformed(ActionEvent e){ trace("2",cb2);

}

});

cb3.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ trace("3",cb3);

}

});

Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(new JScrollPane(t)); cp.add(cb1);

cp.add(cb2);

cp.add(cb3);

}

void trace(String b,JCheckBox cb){ if(cb.isSelected())

t.append("Прапорець " + b + " відмічено \n"); else

t.append("Прапорець " + b + " очищено \n");

}

public static void main(String[] args){ Console.run(new CheckBoxes(),200,200);

}

}

Код html-файла:

<HTML><TITLE> Applet</TITLE>

<APPLET CODE= " CheckBoxes.class" WIDTH = 200 HEIGHT = 200></APPLET > </HTML>

Рис. 13.2. Результати дії аплета CheckBoxes

Приклад 3. Перемикачі. import javax.swing.*; import java.awt.event.*; import java.awt.*;

//import com.bruceeckel.swing;

public class RadioButtons extends JApplet{

85

JTextField t = new JTextField(15); ButtonGroup g = new ButtonGroup(); JRadioButton

rb1 = new JRadioButton("один",false), rb2 = new JRadioButton("два",false), rb3 = new JRadioButton("три",false);

ActionListener al = new ActionListener(){ public void actionPerformed(ActionEvent e){

t.setText("Перемикач " + ((JRadioButton)e.getSource()).getText());

}

};

public void init() { rb1.addActionListener(al); rb2.addActionListener(al); rb3.addActionListener(al); g.add(rb1);

g.add(rb2);

g.add(rb3);

t.setEditable(false);

Container cp =getContentPane(); cp.setLayout(new FlowLayout()); cp.add(t);

cp.add(rb1);

cp.add(rb2);

cp.add(rb3);

}

public static void main(String[] args){ Console.run(new RadioButtons(),200,100);

}}

Код html-файла

<HTML><TITLE> Applet</TITLE>

<APPLET CODE= " RadioButtons.class" WIDTH = 200 HEIGHT = 100></APPLET > </HTML>

Рис. 13.3. Результати різних дій аплета RadioButtons

86

Приклад 4. Комбіновані (випадані) списки import javax.swing.*;

import java.awt.event.*; import java.awt.*;

//import com.bruceeckel.swing;

public class ComboBoxes extends JApplet{

String[]description = {"Поганий", "Гарний", "Скромний", "Привабливий", "Дурний", "Злий", "Ніжний", "Сильний"};

JTextField t = new JTextField(15); JComboBox c = new JComboBox();

JButton b = new JButton("Додати елементи"); int count=0;

public void init(){ for(int i=0;i<4;i++)

c.addItem(description[count++]);

t.setEditable(false); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(count< description.length) c.addItem(description[count++]);

}

});

c.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){

t.setText("індекс: "+c.getSelectedIndex()+" "+((JComboBox)e.getSource()).getSelectedItem());

}

});

Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(t);

cp.add(c);

cp.add(b);

}

public static void main(String[] args){ Console.run(new ComboBoxes(),200,100);

}

Код html-файла

<HTML><TITLE> Applet</TITLE>

<APPLET CODE= " ComboBoxes.class" WIDTH = 200 HEIGHT = 100></APPLET > </HTML>

87

Рис. 13.4. Результати дій аплета ComboBoxes

Приклад 5. Списки. import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.awt.*;

import javax.swing.border.*; //import com.bruceeckel.swing;

public class List extends JApplet{

static final String[] flavors = {"Пломбір", "Ванільне", "Шоколадне", "Фруктове", "Фіста-

шкове", "Рожок", "Тірамісу", "Ескімо", "Крем-брюле", "Сорбет", "Фруктовий льод", "Щербет"};

DefaultListModel lItems = new DefaultListModel(); JList lst = new JList(lItems);

JTextArea t = new JTextArea(flavors.length,20); JButton b = new JButton("Додати елемент!"); ActionListener bl = new ActionListener(){

public void actionPerformed(ActionEvent e){ if (count< flavors.length){

lItems.add(0,flavors[count++]);

}

else{

b.setEnabled(false);

}

}

};

ListSelectionListener ll = new ListSelectionListener(){ public void valueChanged(ListSelectionEvent e){

t.setText("");

Object[] items = lst.getSelectedValues(); for(int i=0; i<items.length;i++)

t.append(items[i]+"\n");

}

};

int count=0;

public void init(){

Container cp = getContentPane(); t.setEditable(false); cp.setLayout(new FlowLayout());

Border brd = BorderFactory.createMatteBorder(1,1,2,2,Color.black); lst.setBorder(brd);

88

t.setBorder(brd); for(int i=0; i<4;i++)

lItems.addElement(flavors[count++]);

cp.add(t);

cp.add(lst);

cp.add(b);

lst.addListSelectionListener(ll);

b.addActionListener(bl);

}

public static void main(String[] args){ Console.run(new List(),250,375);

}

}

Код html-файла

<HTML><TITLE> Applet</TITLE>

<APPLET CODE= " List.class" WIDTH = 250 HEIGHT = 375></APPLET > </HTML>

Рис. 13.5. Результати дій аплета List

Приклад 6. Панель вкладок. import javax.swing.*;

import javax.swing.event.*; import java.awt.event.*; import java.awt.*;

//import com.bruceeckel.swing;

public class TabbedPanel extends JApplet{

String[] flavors = {"Пломбір", "Ванільне", "Шоколадне", "Фруктове", "Фісташкове", "Рожок", "Тірамісу", "Ескімо", "Крем-брюле", "Сорбет", "Фруктовий льод", "Щербет"};

89

JTabbedPane tabs = new JTabbedPane(); JTextField txt = new JTextField(20); public void init(){

for (int i=0; i<flavors.length;i++)

tabs.addTab(flavors[i], new JButton("Вкладка "+ i)); tabs.addChangeListener(new ChangeListener(){

public void stateChanged(ChangeEvent e){

txt.setText(" Вибрана вкладка: " + tabs.getSelectedIndex());

}

});

Container cp = getContentPane(); cp.add(BorderLayout.SOUTH,txt); cp.add(tabs);

}

public static void main(String[] args){ Console.run(new TabbedPanel(),350,200);

}

}

Код html-файла

<HTML><TITLE> Applet</TITLE>

<APPLET CODE= " TabbedPanel.class" WIDTH = 350 HEIGHT = 200></APPLET > </HTML>

Рис. 13.6. Результати дій аплета TabbedPanel

Приклад 7. Вікно повідомлень. import javax.swing.*;

import javax.swing.event.*; import java.awt.event.*; import java.awt.*;

//import com.bruceeckel.swing;

public class MessageBoxes extends JApplet{ JButton[] b = { new JButton("Попередження!"),

new JButton("Так / Ні"), new JButton("Колір"), new JButton("Введення"),

90