Не рисуется линия в Swing
Я пытаюсь сделать графический редактор (что-то типа исполнителя Чертежника из курсов информатики). Хочу нарисовать одну чёрную линию и сетку из линий, но отображается только сетка из линий. Что не так?
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.lang.Math;
@SuppressWarnings("ALL")
public class Window extends JFrame {
private Canvas canvas = new Canvas();
class Canvas extends JPanel {
ArrayList<Line> lines = new ArrayList();
ArrayList<Line> grid = new ArrayList();
class Line {
private int x1, x2, y1, y2;
private Color color;
public Line(int x1, int y1, int x2, int y2, Color color) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.color = color;
}
public void draw(Graphics canvas) {
canvas.setColor(color);
canvas.drawLine(x1, y1, x2, y2);
repaint();
}
}
public Canvas() {
super();
setBackground(Color.WHITE);
}
public void paintComponent(Graphics canvas) {
super.paintComponent(canvas);
canvas.setColor(Color.WHITE);
canvas.clearRect(0, 0, 600, 600);
for(Line line:grid) {
line.draw(canvas);
}
for(Line line:lines) {
line.draw(canvas);
}
}
public void addGrid() {
for (int x = 1; x < 20; x++) {
grid.add(new Line(x * 30, 0, x * 30, 600, Color.GRAY));
}
for (int y = 1; y < 20; y++) {
grid.add(new Line(0, y * 30, 600, y * 30, Color.GRAY));
}
}
public void addLine(int x1, int y1, int x2, int y2) {
lines.add(new Line(x1, y1, x2, y2, Color.BLACK));
}
}
Window() {
// Создаём окно с заголовком
super();
setTitle("JPaint");
setBounds(0, 0, 615, 639);
canvas.setBounds(0, 0, 600, 600);
add(canvas);
setLayout(null);
// Пытаемся сделать графический интерфейс похожим на интерфейс используемой ОС
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Задаём кнопке закрытия принадлежащее ей действие
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Блокируем кнопку "Развернуть на весь экран"
setResizable(false);
// Показываем окно
setVisible(true);
canvas.addGrid();
canvas.addLine((int) Math.random() * 600, (int) Math.random() * 600, (int) Math.random() * 600,
(int) Math.random() * 600);
canvas.repaint();
}
}
Ответы (1 шт):
Автор решения: Alexey R.
→ Ссылка
Выражение (int) Math.random() * 600 всегда даст ноль, потому что Math.random() возвращает значение меньше единицы. Каст этого значения к инту даёт ноль (отбрасывается всё после точки).
В итоге, Вы рисуете линию начинающуюся в нуле и заканчивающуюся в нуле.
Решения два:
- Вместо
(int) Math.random() * 600делать(int)(Math.random() * 600) - Вместо
(int) Math.random() * 600
Random random = new Random();
random.nextInt(600);