Читаем Основы программирования на Java полностью

public void init() {

setLayout(null);

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

Checkbox win1 = new Checkbox("Windows XP", null, true);

Checkbox win2 = new Checkbox("Windows 2000");

Checkbox win3 = new CheckboxfWindows 98");

add(win1);

add(win2);

add(win3);

win1.reshape(0,0, width, height / 3);

win2.reshape(0, height / 3, width, height / 3);

win3.reshape(0,2 * height / 3, width, height / 3);

}

}

12.7. Класс CheckboxGroup


Второй параметр конструктора Checkbox (в предыдущем примере мы ставили там null) используется для группирования нескольких объектов Checkbox. Для этого сначала создается объект CheckboxGroup, затем он передается в качестве параметра любому количеству конструкторов Checkbox, при этом предоставляемые этой группой варианты выбора становятся взаимоисключающими (только один может быть задействован). Предусмотрены и методы, которые позволяют получить и установить группу, к которой принадлежит конкретный объект Checkbox — getCheckboxGroup и setCheckboxGroup. Вы можете пользоваться методами getCurrent и setCurrent для получения и установки состояния выбранного в данный момент объекта Checkbox. Ниже приведен пример, отличающийся от предыдущего тем, что теперь различные варианты выбора в нем взаимно исключают друг друга.

import java.awt.*;

import java.applet.*;

public class CheckboxGroupDemo extends Applet {

public void init() {

setLayout(null);

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

CheckboxGroup g = new CheckboxGroup();

Checkbox winl = new Checkbox("Windows XP", g, true);

Checkbox win2 = new Checkbox("Windows 2000", g, false);

Checkbox win3 = new Checkbox("Windows 98", g, false);

add(winl);

add(win2);

add(win3);

winl.reshape(0,0, width, height / 3);

win2. reshape(0, height / 3, width, height / 3);

win3.reshape(0,2 * height / 3, width, height / 3);

}

}

12.8. Класс Choice


Класс Choice (выбор) используется при создании раскрывающихся списочных меню (выпадающих списков типа ComboBox в Windows). Компонент Choice занимает ровно столько места, сколько требуется для отображения выбранного в данный момент элемента, когда пользователь щелкает мышью на нем, раскрывается меню со всеми элементами, в котором можно сделать выбор. Каждый элемент меню — это строка, которая выводится, выровненная по левой границе. Элементы меню выводятся в том порядке, в котором они были добавлены в объект Choice. Метод countItems возвращает количество пунктов в меню выбора. Вы можете задать пункт, который выбран в данный момент, с помощью метода select, передав ему либо целый индекс (пункты меню перечисляются с нуля), либо строку, которая совпадает с меткой нужного пункта меню. Аналогично с помощью методов getSelectedItem и getSelectedIndex можно получить, соответственно, строку-метку и индекс выбранного в данный момент пункта меню. Вот очередной простой пример, в котором создается два объекта Choice.

import java.awt.*;

import java.applet.*;

public class ChoiceDemo extends Applet {

public void init() {

setLayout(null);

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

Choice os = new Choice();

Choice browser = new Choice();

os.addItem("Windows XP");

os.addItem("Windows 2000");

os.addItem("Windows 98");

browser. addItem("Netscape Navigator");

browser.addItem("Mozula");

browser.addItem("Internet Explorer ");

browser.addItem("Mosaic ");

browser.addItem("Lynx ");

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных