Как разместить квадрат по середине окна - Java
Формулировка задачи:
import javax.swing.*;
public class GUI extends JFrame {
public static final int WIDTH = 500;
public static final int HEIGHT= 400;
public GUI(String s) {
setTitle(s);
setSize(WIDTH, HEIGHT);
MyPanel panel = new MyPanel();
add(panel);
}
}import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class MyPanel extends JPanel {
public static final double x1 = 100;
public static final double WIDTH = (GUI.WIDTH - x1) - x1;
public static final double y1 = 100;
public static final double HEIGHT = (GUI.HEIGHT - y1)-y1;
public MyPanel() {
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double(x1,y1,WIDTH,HEIGHT);
g2.setColor(Color.GREEN);
g2.fill(rect);
}
}import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class MyPanel extends JPanel {
public static final int WIDTH2 = 200;
public static final int HEIGHT2 = 200;
public MyPanel() {
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double((GUI.WIDTH - WIDTH2) / 2, (GUI.HEIGHT - HEIGHT2) / 2, WIDTH2, HEIGHT2);
g2.setColor(Color.GREEN);
g2.fill(rect);
}
}Решение задачи: «Как разместить квадрат по середине окна»
textual
Листинг программы
class MyPanel extends JPanel {
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
int leftMargin = (getWidth() - WIDTH) / 2;
int topMargin = (getHeight() - HEIGHT) / 2;
g.fillRect(leftMargin, topMargin, WIDTH, HEIGHT);
}
}