Rectangle object using two-dimensional array - java

If i have a two-dimensional array, is it possible to print out the result as a rectangle?
Here is what i have come up with;
int[][] anArrayRectangle = {{0,0},{-2,0},{1,-2},
{0,1},{2,1},{2,0}};
Each point represents one out of six points which together create a rectangle in the unit circle.
The question is if it is possible to display the rectangle in lines, not exclusively using the print method. Perhaps in an applet?
All tips are welcome.

Maybe you could use drawPolygon
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Rectangle extends JPanel {
private int xPos[] = {100, 150, 200, 200, 150, 100};
private int yPos[] = {100, 100, 100, 150, 150, 150};
public void paint(Graphics g) {
super.paint(g);
int length = xPos.length;
g.drawPolygon(xPos, yPos, length);
}
private static JFrame frame = null;
public static void main(String[] args) {
frame = new JFrame("Graphics");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
Rectangle obj = new Rectangle();
frame.add(obj);
}
}

Related

AffineTransform: how to scale only one shape Triangle

I have this code:
import javax.swing.*;
import java.awt.*;
public class Test {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
class MyCanvas extends JComponent {
public void paint(Graphics g) {
g.drawRect (10, 10, 100, 100);
Polygon triangle = new Polygon(new int[] {100, 150, 200}, new int[] {200, 100, 200}, 3);
g.drawPolygon(triangle);
}
}
It draws this:
I want to scale only Triangle, so it becomes thrice is big:
I understand that I need to use AffiniteTransform, but I don't understand how.
I only know that I need the scaling instance:
AffineTransform at = AffineTransform.getScaleInstance(3, 3);
All answers I've seen were very confusing or just used g2d.setTransform(at) which doesn't seem to be what I need, seeing as the square is supposed to stay the same size.
EDIT: And how do I scale a Triagle, while keeping its leftmost coordinate at the same location? (leftmost (x,y) stays the same)
New code:
public class Test {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
class MyCanvas extends JComponent {
public void paint(Graphics g) {
g.drawRect (10, 10, 100, 100);
Polygon triangle = new Polygon(new int[] {100, 150, 200}, new int[] {200, 100, 200}, 3);
AffineTransform at = AffineTransform.getScaleInstance(1.5, 1.5);
((Graphics2D) g).setTransform(at);
g.drawPolygon(triangle);
((Graphics2D) g).setTransform(AffineTransform.getScaleInstance(1,1));
validate();
}
}
gives this:
The triangle shifts as it gets scaled.
Is it possible to keep the triangle at the same spot - that is to keep its leftmost bottom corner at the same spot?

How to make Color change when mouse clicked in java?

I'm trying to make my own Java GUI project. I want to make the line's colors change when mouse pressed, but this doesn't work. I used 'for'loop and array for Colors but this doesn't run. So I'd like to ask you help me to solve it! Also, I wonder why loop needs for drawing lines on panel.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GraphicEx extends JFrame {
private MyPanel panel = new MyPanel();
public GraphicEx(){
setTitle("Java Mondrian");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
setSize(400,220);
setVisible(true);
}
class MyPanel extends JPanel{
private Vector <Point> vStart = new Vector <Point>();
private Vector <Point> vEnd = new Vector <Point>();
Color [] c = {Color.BLUE, Color.RED, Color.YELLOW, Color.BLACK};
private int a;
MyPanel(){
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
Point startP = e.getPoint();
vStart.add(startP);
for(int i=0; i<c.length; i++) {
if (i== (c.length-1)){
i=0;
}
a = i;
}
}
I made this for Color Change, But this not work.
#Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
Point endP = e.getPoint();
vEnd.add(endP);
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//component Color & Size
g.setColor(Color.BLACK);
g.drawRect(10,10,50,50);
g.setColor(Color.BLUE);
g.fillRect(60, 60, 100, 100);
g.setColor(Color.RED);
g.fillRect(50,50,20,20);
g.setColor(Color.YELLOW);
g.fillRect(130,50,50,50);
g.setColor(Color.RED);
g.drawRect(170,10,50,50);
g.setColor(Color.BLACK);
g.fillRect(210,50,80,50);
g.setColor(Color.YELLOW);
g.drawRect(260,30,40,170);
g.setColor(Color.RED);
g.fillRect(240,130,170,40);
g.setColor(new Color(0,0,0));
g.setFont(new Font("Arial",Font.ITALIC, 30));
g.drawString("Mondrian.2020", 100, 174);
g.setColor(new Color(0,210,200));
g.setFont(new Font("Arial",Font.BOLD,20));
g.drawString("Draw your own Picture", 70, 100);
g.setColor(new Color(0,0,0));
g.drawLine(20,20,350,20);
g.drawLine(35,0,35,180);
g.drawLine(20,160,350,160);
g.drawLine(330, 0, 330, 190);
int [] x = {80, 40, 80, 120};
int [] y = {40, 120, 200, 120};
g.drawPolygon(x,y,4);
g.setColor(Color.BLUE);
g.fillArc(290, 10, 50, 50, 90, 360);
for(int i=0; i<vStart.size();i++) {
Point s = vStart.elementAt(i);
Point e = vEnd.elementAt(i);
g.setColor(c[a]);
g.drawLine((int)s.getX(), (int)s.getY(), (int)e.getX(), (int)e.getY());
}
}
}
I cannot understand this part too! why I should use loop to draw lines?
public static void main(String[] args) {
new GraphicEx();
}
}
As there's only a limited supply of colors, and each line should have it's own, the modulo operator seems fitting:
//Make sure both vectors have that index!
for(int i=0; i< Math.min(vStart.size(), vEnd.size()); i++) {
Point s = vStart.elementAt(i);
Point e = vEnd.elementAt(i);
g.setColor(c[i % c.length]); //Use a calculated color using modulo length
g.drawLine((int)s.getX(), (int)s.getY(), (int)e.getX(), (int)e.getY());
}
Also it's not good to access elements that are not there (yet). Painting could happen at any time - so there might be start items with no end items.
If this works, you could get rid of the whole calculation of a as well.

Why cant I draw a rectangle with fillPolygon()

I am learning Java graphics. I am trying to draw simple figures. However I noticed that the following code won't draw properly:
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xpoints = new int[] { 20, 50, 80 };
int[] ypoints = new int[] { 40, 10, 40 };
g.fillPolygon(xpoints, ypoints, 3);
int[] recXp = new int[] { 20, 80, 20, 80 };
int[] recYp = new int[] { 50, 60, 50, 60 };
g.fillPolygon(recXp, recYp, 4);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw panel = new Draw();
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
}
}
In order to achieve what I want I have to use
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xpoints = new int[] { 20, 50, 80 };
int[] ypoints = new int[] { 40, 10, 40 };
g.fillPolygon(xpoints, ypoints, 3);
g.fillRect(20, 50, 60, 10);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw panel = new Draw();
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
}
}
Why is this happening? Am I missing something? Sorry if this is a trivial question, I am just trying to understand Java better.
int[] recXp = new int[] { 20, 80, 20, 80 };
int[] recYp = new int[] { 50, 60, 50, 60 };
You only have two sets of points.
You need 4 different sets of point. One for each corner of the Rectangle.
Something like:
top/left (20, 50)
top/right (x is different from above, y is the same)
bottom/right (x is same as above, y is different.
bottom/left (x is same as first, y is save as above)

TextArea with Canvas Binding to Rect

I have the problem of this textarea not showing up when I run it. Is there any way to make it show up. BTW its getting called through the gameloop on a class that extends canvas.
public void render(Graphics g){
Graphics2D g2d = (Graphics2D) g;
if(!initialized)
init();
try {
test.requestFocus();
test.paintAll(g);
test.setText("hi");
test.setBounds(getBounds());
test.printAll(g);
} catch (Exception e) {
e.printStackTrace();
}
g2d.draw(getBounds());
g.drawRect(0, 0, 100, 100);
}
private void init(){
frame.setVisible(false);
initialized = true;
test = new TextArea();
test.setEditable(true);
test.setBounds(getBounds());
test.setBackground(test.getBackground());
test.setForeground(test.getForeground());
frame.add(test);
frame.repaint();
frame.setVisible(true);
System.out.println(test.isVisible());
}
private Rectangle getBounds(){
return new Rectangle(100, 100, 100, 100);
}
I have tried using JTextArea but it takes up the full screen and won't bind to a rect. Thanks for help in advance!
You don't need to manually paint existing Components you add to your program. Here is a simple example how to display a TextArea over a frame/canvas you paint yourself: Check the comments for further details.
package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Test extends JFrame {
private static Test frame;
private static double t;
private static int x;
private static int y;
private static TextArea test;
public static void main(String[] args) {
frame = new Test();
frame.setVisible(true);
// set layout to null so that you can freely position your components
// without them "filling up the whole screen"
frame.setLayout(null);
frame.setSize(500, 500);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
// game loop
new Timer(10, (e) -> {
t += 10.0 / 1000;
x = (int) (100 + 50 * Math.sin(t));
y = (int) (100 + 50 * Math.cos(t));
// calling repaint will cause Test.paint() to be called first,
// then Test's children will be painted (= the TextArea)
frame.repaint();
}).start();
// initialize the textarea only once
test = new TextArea();
test.setEditable(true);
test.setBounds(new Rectangle(100, 100, 100, 100));
test.setText("hi");
frame.add(test);
}
#Override
public void paint(Graphics g) {
// put only painting logic in your paint/render.
// don't set the bounds of components here,
// as this will trigger a repaint.
g.setColor(Color.black);
g.fillRect(0, 0, 400, 400);
g.setColor(Color.yellow);
g.fillOval(x, y, 20, 20);
}
}

Trying to draw on a JPanel without success

I'm trying to learn drawing with swing. I'm trying to create a circle and position it on a specific position in a JPanel. This is what I've come up with but it does not show any figure:
import java.awt.*;
import javax.swing.*;
public class Circles extends JPanel {
private static final long serialVersionUID = 1L;
public Circles(){
setBackground(Color.white);
setPreferredSize(new Dimension(300, 300));
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.black);
g.drawRect(10, 10, 50, 50);
}
}
This is the class that starts the program.
import java.awt.*;
import javax.swing.*;
public class StartCircles extends JFrame{
private static final long serialVersionUID = 1L;
private Circles circle;
public StartCircles(){
Container c = getContentPane();
circle = new Circles();
c.setBackground(Color.white);
c.setLayout(new FlowLayout());
setSize(300, 300);
c.add(circle);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
StartCircles c1 = new StartCircles();
}
}
What am I doing wrong? How do I position the figure where I want?
Try this SSCCE - noting the comments in the source.
import java.awt.*;
import javax.swing.*;
public class StartCircles extends JFrame{
private static final long serialVersionUID = 1L;
private Circles circle;
public StartCircles(){
Container c = getContentPane();
circle = new Circles();
c.setBackground(Color.white);
c.setLayout(new FlowLayout());
//setSize(300, 300);
c.add(circle);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack(); // size the GUI to the components within it
}
public static void main(String[] args){
StartCircles c1 = new StartCircles();
}
}
class Circles extends JPanel {
private static final long serialVersionUID = 1L;
public Circles(){
setBackground(Color.white);
setPreferredSize(new Dimension(300, 300));
}
public void paintComponent(Graphics g){
//super.paintComponents(g); // WRONG METHOD!
super.paintComponent(g);
g.setColor(Color.black);
g.drawRect(10, 10, 50, 50);
}
}
Your code running perfectly, but you are drawing Rectangle here.
so if you want to draw circle, you have to use
one of below methods
g.fillOval(10, 10, 50, 50);
g.drawOval(10, 10, 50, 50);
g.drawRect(10, 10, 50, 50); is sure to get you a rectangle. You need to look at the documentation for how to draw a circle.
You need to draw it using drawOval(). It takes 4 parameters:
x - the x coordinate of the upper left corner of the oval to be drawn.
y - the y coordinate of the upper left corner of the oval to be drawn.
width - the width of the oval to be drawn.
height - the height of the oval to be drawn.
So, replace your drawRect() with drawOval()

Categories

Resources