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

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

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

for (int i = 0; i < n; i++) {

for (int j = 0; j < ri; j++) {

float g = (i * n + j) / (float) (n * n);

Canvas с = new GrayCanvas(g);

add(c);

c.resize(width / n, height / n);

c.move(i * width / n, j * height / n);

}

}

Мы устанавливаем размер каждого из объектов Canvas на основе значения, полученного с помощью метода size, который возвращает объект класса Dimension. Обратите внимание на то, что для размещения объектов Canvas в нужные места используются методы resize и move. Такой способ станет очень утомительным, когда мы перейдем к более сложным компонентам и более интересным вариантам расположения. А пока для выключения упомянутого механизма использован вызов метода setLayout(null).

12.4. Класс Label


Функциональность класса Label сводится к тому, что он знает, как нарисовать объект String — текстовую строку, выровнив ее нужным образом. Шрифт и цвет, которыми отрисовывается строка метки, являются частью базового определения класса Component. Для работы с этими атрибутами предусмотрены пары методов getFont/setFont и getForeground/setForeground. Задать или изменить текст строки после создания объекта с помощью метода setText. Для задания режимов выравнивания в классе Label определены три константы — LEFT, RIGHT и CENTER. Ниже приведен пример, в котором создаются три метки, каждая — со своим режимом выравнивания.

import java.awt.*;

import java.applet. *;

public class LabelDemo extends Applet {

public void init() {

setLayout(null);

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

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

Label left = new LabelC'Left", LabeLLEFT);

Label right = new Label("Right", LabeLRIGHT);

Label center = new Label("Center", Label.CENTER);

add(left);

add(right);

add(center);

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

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

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

}

}

На этот раз, чтобы одновременно переместить и изменить размер объектов Label, мы использовали метод reshape. Ширина каждой из меток равна полной ширине апплета, высота— 1/3 высоты апплета.

12.5. Класс Button


Объекты-кнопки помечаются строками, причем эти строки нельзя выравнивать подобно строкам объектов Label (они всегда центрируются внутри кнопки). Позднее в данной главе речь пойдет о том, как нужно обрабатывать события, возникающие при нажатии и отпускании пользователем кнопки. Ниже приведен пример, в котором создаются три расположенные по вертикали кнопки.

import java.awt.*;

import j ava.applet. *;

public class ButtonDemo extends Applet {

public void init() {

setLayout(null);

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

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

Button yes = new Button("Yes");

Button no = new Button("No");

Button maybe = new Button("Undecided");

add(yes);

add(no);

add(maybe);

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

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

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

}

}

12.6. Класс Checkbox


Класс Checkbox часто используется для выбора одной из двух возможностей. При создании объекта Checkbox ему передается текст метки и логическое значение, чтобы задать исходное состояние окошка с отметкой. Программно можно получать и устанавливать состояние окошка с отметкой с помощью методов getState и setState. Ниже приведен пример с тремя объектами Checkbox, задаваемое в этом примере исходное состояние соответствует отметке в первом объекте.

import java.awt.*;

import j ava.applet. *;

public class CheckboxDemo extends Applet {

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

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

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

Стивен Прата

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