Національний технічний університет України
«Київський політехнічний інститут ім. Ігоря Сікорського»
Кафедра цифрових технологій в енергетиці
ЗВІТ
з виконання лабораторної роботи №6
з дисципліни «Програмування на мові Java»
«ПОБУДОВА ГРАФІЧНИХ ІНТЕРФЕЙСІВ ЗА ДОПОМОГОЮ ІНСТРУМЕНТІВ AWT»
Варіант 13
Завдання 2
package org.example;
import java.awt.*;
import java.awt.event.*;
/**
* Клас, що реалізує додаток для зміни шрифту.
*/
public class Task2 extends Frame {
private Panel panel;
Choice fontChoice;
Choice styleChoice;
TextArea textArea;
/**
* Конструктор класу. Ініціалізує вікно та його компоненти.
*/
public Task2() {
super("Характеристики шрифту");
setSize(600, 600);
setLayout(new BorderLayout());
panel = new Panel();
panel.setLayout(new GridLayout(2, 2));
Label labelFont = new Label("Шрифт:");
fontChoice = new Choice();
fontChoice.add("Times New Roman");
fontChoice.add("Arial");
fontChoice.add("Verdana");
Label labelStyle = new Label("Стиль:");
styleChoice = new Choice();
styleChoice.add("Простий");
styleChoice.add("Жирний");
styleChoice.add("Курсив");
styleChoice.add("Жирний курсив");
panel.add(labelFont);
panel.add(fontChoice);
panel.add(labelStyle);
panel.add(styleChoice);
textArea = new TextArea("", 10, 20);
textArea.setEditable(true);
add(panel, BorderLayout.NORTH);
add(textArea, BorderLayout.CENTER);
fontChoice.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateText();
}
});
styleChoice.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateText();
}
});
setVisible(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.exit(0);
}
});
}
/**
* Метод для оновлення текстового поля з урахуванням нових характеристик шрифту.
*/
void updateText() {
String font = fontChoice.getSelectedItem();
int style = Font.PLAIN;
switch (styleChoice.getSelectedIndex()) {
case 1:
style = Font.BOLD;
break;
case 2:
style = Font.ITALIC;
break;
case 3:
style = Font.BOLD | Font.ITALIC;
break;
}
Font newFont = new Font(font, style, 12);
textArea.setFont(newFont);
}
/**
* Метод для запуску програми.
* @param args Параметри командного рядка (не використовуються).
*/
public static void main(String[] args) {
new Task2();
}
}
/
package org.example;
import org.example.Task2;
import org.junit.jupiter.api.Test;
import java.awt.*;
import static org.junit.jupiter.api.Assertions.*;
class Task2Test {
@Test
public void testFontChoice() {
Task2 task2 = new Task2();
task2.fontChoice.select("Arial");
assertEquals("Arial", task2.fontChoice.getSelectedItem());
task2.fontChoice.select("Times New Roman");
assertEquals("Times New Roman", task2.fontChoice.getSelectedItem());
}
@Test
public void testStyleChoice() {
Task2 task2 = new Task2();
task2.styleChoice.select("Жирний");
task2.updateText();
assertEquals(Font.BOLD, task2.textArea.getFont().getStyle());
task2.styleChoice.select("Курсив");
task2.updateText();
assertEquals(Font.ITALIC, task2.textArea.getFont().getStyle());
task2.styleChoice.select("Жирний курсив");
task2.updateText();
assertEquals(Font.BOLD | Font.ITALIC, task2.textArea.getFont().getStyle());
task2.styleChoice.select("Простий");
task2.updateText();
assertEquals(Font.PLAIN, task2.textArea.getFont().getStyle());
}
@Test
public void testUpdateText() {
Task2 task2 = new Task2();
task2.fontChoice.select("Arial");
task2.styleChoice.select("Жирний");
task2.updateText();
assertEquals(Font.BOLD, task2.textArea.getFont().getStyle());
task2.fontChoice.select("Times New Roman");
task2.styleChoice.select("Курсив");
task2.updateText();
assertEquals(Font.ITALIC, task2.textArea.getFont().getStyle());
task2.fontChoice.select("Verdana");
task2.styleChoice.select("Жирний курсив");
task2.updateText();
assertEquals(Font.BOLD | Font.ITALIC, task2.textArea.getFont().getStyle());
}
}
/
Завдання 14
package org.example;
import java.awt.*;
import java.awt.event.*;
/**
* Клас, що реалізує додаток для зміни кольору та розміру шрифту.
*/
public class Task14 {
private Frame frame;
private Panel panel;
private Label labelColor;
private Label labelSize;
private Button buttonBlack;
private Button buttonRed;
private Button buttonGreen;
private Button buttonBlue;
private Button button12pt;
private Button button14pt;
private Button button16pt;
private TextArea textArea;
private Color color = Color.BLACK;
private int size = 12;
/**
* Конструктор класу. Ініціалізує вікно та його компоненти..
*/
public Task14() {
frame = new Frame("Введення тексту");
frame.setSize(400, 400);
frame.setLayout(new BorderLayout());
panel = new Panel();
panel.setLayout(new GridLayout(3, 5));
labelColor = new Label("Колір: ");
labelSize = new Label("Розмір: ");
buttonBlack = new Button("Чорний");
buttonRed = new Button("Червоний");
buttonGreen = new Button("Зелений");
buttonBlue = new Button("Синій");
button12pt = new Button("12pt");
button14pt = new Button("14pt");
button16pt = new Button("16pt");
panel.add(labelColor);
panel.add(buttonBlack);
panel.add(buttonRed);
panel.add(buttonGreen);
panel.add(buttonBlue);
panel.add(labelSize);
panel.add(button12pt);
panel.add(button14pt);
panel.add(button16pt);
textArea = new TextArea();
textArea.setFont(new Font("Arial", Font.PLAIN, size));
frame.add(panel, BorderLayout.NORTH);
frame.add(textArea, BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
/**
* Налаштовує обробники подій для кнопок кольору та розміру.
*/
buttonBlack.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
color = Color.BLACK;
textArea.setForeground(color);
}
});
buttonRed.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
color = Color.RED;
textArea.setForeground(color);
}
});
buttonGreen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
color = Color.GREEN;
textArea.setForeground(color);
}
});
buttonBlue.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
color = Color.BLUE;
textArea.setForeground(color);
}
});
button12pt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
size = 12;
textArea.setFont(new Font("Arial", Font.PLAIN, size));
}
});
button14pt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
size = 14;
textArea.setFont(new Font("Arial", Font.PLAIN, size));
}
});
button16pt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
size = 16;
textArea.setFont(new Font("Arial", Font.PLAIN, size));
}
});
frame.setVisible(true);
}
/**
* Головний метод для створення та відображення об'єкту Task14.
*
* @param args Аргументи командного рядка (не використовуються).
*/
public static void main(String[] args) {
new Task14();
}
public int getSize() {
return size;
}
public Color getColor() {
return color;
}
public Button getButtonBlack() {
return buttonBlack;
}
public Button getButtonRed() {
return buttonRed;
}
public Button getButtonGreen() {
return buttonGreen;
}
public Button getButtonBlue() {
return buttonBlue;
}
public Button getButton12pt() {
return button12pt;
}
public Button getButton14pt() {
return button14pt;
}
public Button getButton16pt() {
return button16pt;
}
}
/
package org.example;
import org.example.Task14;
import org.junit.jupiter.api.Test;
import java.awt.*;
import java.awt.event.ActionEvent;
import static org.junit.jupiter.api.Assertions.*;
class Task14Test {
@Test
public void testColorChange() {
Task14 task14 = new Task14();
task14.getButtonBlack().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(Color.BLACK, task14.getColor());
task14.getButtonRed().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(Color.RED, task14.getColor());
task14.getButtonGreen().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(Color.GREEN, task14.getColor());
task14.getButtonBlue().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(Color.BLUE, task14.getColor());
}
@Test
public void testSizeChange() {
Task14 task14 = new Task14();
task14.getButton12pt().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(12, task14.getSize());
task14.getButton14pt().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(14, task14.getSize());
task14.getButton16pt().getActionListeners()[0].actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
assertEquals(16, task14.getSize());
}
}
/
Завдання 21
package org.example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Клас, що реалізує додаток для зміни кольору та розміру шрифту.
*/
public class Task21 extends Frame {
private String text = "Hello World!";
private Color textColor = Color.BLACK;
private int textSize = 12;
private int xCoordinate = 50;
private int yCoordinate = 50;
Canvas canvas;
TextField textInputField;
Choice colorChoice;
Choice sizeChoice;
private Button drawButton;
private TextField xCoordinateField;
private TextField yCoordinateField;
/**
* Конструктор класу. Ініціалізує вікно та його компоненти.
*/
public Task21() {
setTitle("Зміна напису у графічному вікні");
setSize(1200, 800);
setLayout(new BorderLayout());
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
g.setColor(textColor);
g.setFont(new Font("Arial", Font.PLAIN, textSize));
g.drawString(text, xCoordinate, yCoordinate);
}
};
add(canvas, BorderLayout.CENTER);
Panel controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
Label textLabel = new Label("Текст:");
textInputField = new TextField(50);
textInputField.setText(text);
controlPanel.add(textLabel);
controlPanel.add(textInputField);
Label colorLabel = new Label("Колір:");
colorChoice = new Choice();
colorChoice.add("Чорний");
colorChoice.add("Червоний");
colorChoice.add("Зелений");
colorChoice.add("Синій");
colorChoice.select(0);
controlPanel.add(colorLabel);
controlPanel.add(colorChoice);
Label sizeLabel = new Label("Розмір:");
sizeChoice = new Choice();
sizeChoice.add("10pt");
sizeChoice.add("12pt");
sizeChoice.add("14pt");
sizeChoice.add("16pt");
sizeChoice.select(1);
controlPanel.add(sizeLabel);
controlPanel.add(sizeChoice);
Label xCoordLabel = new Label("Координата X:");
xCoordinateField = new TextField(5);
xCoordinateField.setEditable(false);
xCoordinateField.setText(Integer.toString(xCoordinate));
controlPanel.add(xCoordLabel);
controlPanel.add(xCoordinateField);
Label yCoordLabel = new Label("Координата Y:");
yCoordinateField = new TextField(5);
yCoordinateField.setEditable(false);
yCoordinateField.setText(Integer.toString(yCoordinate));
controlPanel.add(yCoordLabel);
controlPanel.add(yCoordinateField);
Button drawButton = new Button("Вивести рядок");
drawButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text = textInputField.getText();
textColor = getColorFromString(colorChoice.getSelectedItem());
textSize = Integer.parseInt(sizeChoice.getSelectedItem().replaceAll("pt", ""));
canvas.repaint();
}
});
controlPanel.add(drawButton);
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
xCoordinate = e.getX();
yCoordinate = e.getY();
xCoordinateField.setText(Integer.toString(xCoordinate));
yCoordinateField.setText(Integer.toString(yCoordinate));
canvas.repaint();
}
});
add(controlPanel, BorderLayout.SOUTH);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.exit(0);
}
});
}
/**
* Перетворює назву кольору в об'єкт Color.
*
* @param colorName Назва кольору.
* @return Об'єкт Color, що відповідає colorName.
*/
Color getColorFromString(String colorName) {
switch (colorName) {
case "Чорний":
return Color.BLACK;
case "Червоний":
return Color.RED;
case "Зелений":
return Color.GREEN;
case "Синій":
return Color.BLUE;
default:
return Color.BLACK;
}
}
/**
* Метод для запуску програми.
* @param args Параметри командного рядка (не використовуються).
*/
public static void main(String[] args) {
Task21 task21 = new Task21();
task21.setVisible(true);
}
public int getTextSize() {
return textSize;
}
public Color getTextColor() {
return textColor;
}
public int getXCoordinate() {
return xCoordinate;
}
public int getYCoordinate() {
return yCoordinate;
}
public Choice getColorChoice() {
return colorChoice;
}
public Choice getSizeChoice() {
return sizeChoice;
}
public TextField getXCoordinateField() {
return xCoordinateField;
}
public TextField getYCoordinateField() {
return yCoordinateField;
}
public TextField getTextInputField() {
return textInputField;
}
public Button getDrawButton() {
return drawButton;
}
public String getText() {
return text;
}
}
/
package org.example;
import org.junit.jupiter.api.Test;
import java.awt.*;
import java.awt.event.ActionListener;
import static org.junit.jupiter.api.Assertions.*;
class Task21Test {
@Test
void getColorFromString() {
Task21 task21 = new Task21();
assertEquals(Color.BLACK, task21.getColorFromString("Чорний"));
assertEquals(Color.RED, task21.getColorFromString("Червоний"));
assertEquals(Color.GREEN, task21.getColorFromString("Зелений"));
assertEquals(Color.BLUE, task21.getColorFromString("Синій"));
assertEquals(Color.BLACK, task21.getColorFromString("Невідомий колір"));
}
}
/
Завдання 28
package org.example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Клас, що реалізує додаток малювання трикутника по координатам.
*/
public class Task28 extends Frame {
public Choice x1Choice;
public Choice y1Choice;
public Choice x2Choice;
public Choice y2Choice;
public Choice x3Choice;
public Choice y3Choice;
/**
* Конструктор класу. Ініціалізує вікно та його компоненти.
*/
public Task28() {
setTitle("Малювання трикутника");
setSize(700, 700);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
topPanel.setLayout(new FlowLayout());
topPanel.add(new Label("X1:"));
x1Choice = createCoordinateChoice();
topPanel.add(x1Choice);
topPanel.add(new Label("Y1:"));
y1Choice = createCoordinateChoice();
topPanel.add(y1Choice);
topPanel.add(new Label("X2:"));
x2Choice = createCoordinateChoice();
topPanel.add(x2Choice);
topPanel.add(new Label("Y2:"));
y2Choice = createCoordinateChoice();
topPanel.add(y2Choice);
topPanel.add(new Label("X3:"));
x3Choice = createCoordinateChoice();
topPanel.add(x3Choice);
topPanel.add(new Label("Y3:"));
y3Choice = createCoordinateChoice();
topPanel.add(y3Choice);
Button drawButton = new Button("Вивести трикутник");
drawButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
drawTriangle();
}
});
topPanel.add(drawButton);
add(topPanel, BorderLayout.NORTH);
Canvas canvas = new Canvas();
add(canvas, BorderLayout.CENTER);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.exit(0);
}
});
}
/**
* Створює вибір координат для вершин трикутника.
*
* @return Вибір координат.
*/
public Choice createCoordinateChoice() {
Choice choice = new Choice();
for (int i = 0; i <= 700; i++) {
choice.add(Integer.toString(i));
}
return choice;
}
/**
* Відображає трикутник на полотні за обраними координатами вершин.
*/
public void drawTriangle() {
int x1 = Integer.parseInt(x1Choice.getSelectedItem());
int y1 = Integer.parseInt(y1Choice.getSelectedItem());
int x2 = Integer.parseInt(x2Choice.getSelectedItem());
int y2 = Integer.parseInt(y2Choice.getSelectedItem());
int x3 = Integer.parseInt(x3Choice.getSelectedItem());
int y3 = Integer.parseInt(y3Choice.getSelectedItem());
Canvas canvas = (Canvas) getComponent(1);
Graphics g = canvas.getGraphics();
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
g.setColor(Color.BLACK);
g.fillPolygon(new int[]{x1, x2, x3}, new int[]{y1, y2, y3}, 3);
}
/**
* Точка входу для застосунку Task28.
*
* @param args Аргументи командного рядка (не використовуються).
*/
public static void main(String[] args) {
Task28 app = new Task28();
app.setVisible(true);
}
}
/
package org.example;
import org.junit.jupiter.api.Test;
import java.awt.*;
import java.awt.image.BufferedImage;
import static org.junit.jupiter.api.Assertions.*;
class Task28Test {
@Test
void createCoordinateChoiceAddsValuesCorrectly() {
Task28 task28 = new Task28();
Choice choice = task28.createCoordinateChoice();
for (int i = 0; i <= 700; i++) {
assertEquals(Integer.toString(i), choice.getItem(i));
}
}
@Test
void drawTriangleUpdatesCanvasCorrectly() {
Task28 task28 = new Task28();
task28.setVisible(true);
task28.x1Choice.select("100");
task28.y1Choice.select("100");
task28.x2Choice.select("200");
task28.y2Choice.select("200");
task28.x3Choice.select("300");
task28.y3Choice.select("300");
BufferedImage image = new BufferedImage(700, 700, BufferedImage.TYPE_INT_RGB);
task28.drawTriangle();
assertEquals(Color.BLACK.getRGB(), getPixelColor(image, 150, 150));
assertEquals(Color.BLACK.getRGB(), getPixelColor(image, 250, 250));
assertEquals(Color.BLACK.getRGB(), getPixelColor(image, 350, 350));
}
private int getPixelColor(BufferedImage image, int x, int y) {
return image.getRGB(x, y);
}
}
/
/