Rotating a shape vertically around the x-axis - java

I have a 2d graph with an x and y axis and im trying to rotate a shape (series of points) around an axis. This rotation will need to include a scale function.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import javax.swing.*;
import java.lang.reflect.Array;
public class test extends JPanel implements ActionListener {
int[] p1x = {200, 200, 240, 240, 220, 220, 200};
int[] p1y = {200, 260, 260, 240, 240, 200, 200};
int[] p2x = {600, 600, 620, 620, 640, 640, 660, 660, 600};
int[] p2y = {400, 420, 420, 460, 460, 420, 420, 400, 400};
int[] p3x = {400, 400, 460, 460, 440, 440, 420, 420, 400};
int[] p3y = {400, 460, 460, 400, 400, 440, 440, 400, 400};
int delay = 1000;
int dx = 0;
int dy = 5;
int steps = 121;
Polygon t;
Timer tim = new Timer(delay, this);
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < Array.getLength(p2x); i++) {
//p2x[i] = (int) (p2x[i]*Math.cos(Math.toRadians(1))- p2y[i]*Math.sin(Math.toRadians(1)));
//p2y[i] = (int) (p2x[i]*Math.sin(Math.toRadians(1))+ p2y[i]*Math.cos(Math.toRadians(1)));;
Point2D original = new Point2D.Double(p2x[i], p2y[i]);
AffineTransform at = new AffineTransform();
//at.setToRotation(.02, 250, 250);
at.scale(1, -1);
Point2D rotated = at.transform(original, null);
p2x[i] = (int) rotated.getX();
p2y[i] = (int) rotated.getY();
}
repaint();
if (--steps == 0) {
tim.stop();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.white);
g.drawLine(this.getWidth() / 2, 0, this.getWidth() / 2, this.getWidth());
g.drawLine(0, this.getHeight() / 2, this.getHeight(), this.getHeight() / 2);
Polygon t = new Polygon(p2x, p2y, 9);
g.drawPolygon(t);
Letters u = new Letters(p3x, p3y, 9);
u.draw(g);
Letters l = new Letters(p1x, p1y, 7);
l.draw(g);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing line and a moving polygon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test sl = new test();
frame.getContentPane().add(sl);
frame.setSize(700, 700);
frame.setVisible(true);
sl.tim.start();
}
}

Absent a clear question, a simple animation using your coordinate arrays is shown below. In general you can transform the graphics context (g2d) or the polygonal Shape itself (p3); the example shows both. Resize the window to see the effect of each.
Note the last-specified-first-applied order of the transformations in at. First, a suitable point on p3 is translated to the origin, then p3 is scaled, and then p3 is translated to the center of the panel. The + 10 fudge factor applied to p3 is an artifact of having no symmetric rotation point. It may be easier to define your polygons relative to the origin, as shown in this example.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/3405799 */
public class AffineTest extends JPanel implements ActionListener {
private static final double DELTA_THETA = Math.PI / 45; // 4°
private static final double DELTA_SCALE = 0.1;
private int[] p1x = {200, 200, 240, 240, 220, 220, 200};
private int[] p1y = {200, 260, 260, 240, 240, 200, 200};
private int[] p2x = {600, 600, 620, 620, 640, 640, 660, 660, 600};
private int[] p2y = {400, 420, 420, 460, 460, 420, 420, 400, 400};
private int[] p3x = {400, 400, 460, 460, 440, 440, 420, 420, 400};
private int[] p3y = {400, 460, 460, 400, 400, 440, 440, 400, 400};
private Polygon p1 = new Polygon(p1x, p1y, p1x.length);
private Polygon p2 = new Polygon(p2x, p2y, p2x.length);
private Polygon p3 = new Polygon(p3x, p3y, p3x.length);
private AffineTransform at = new AffineTransform();
private double dt = DELTA_THETA;
private double theta;
private double ds = DELTA_SCALE;
private double scale = 1;
private Timer timer = new Timer(100, this);
public AffineTest() {
this.setPreferredSize(new Dimension(700, 700));
this.setBackground(Color.white);
p1.translate(-50, +100);
p2.translate(-100, -100);
}
#Override
public void actionPerformed(ActionEvent event) {
theta += dt;
scale += ds;
if (scale < .5 || scale > 4) {
ds = -ds;
}
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = this.getWidth();
int h = this.getHeight();
g2d.drawLine(w / 2, 0, w / 2, h);
g2d.drawLine(0, h / 2, w, h / 2);
g2d.rotate(theta, w / 2, h / 2);
g2d.drawPolygon(p1);
g2d.drawPolygon(p2);
at.setToIdentity();
at.translate(w / 2, h / 2);
at.scale(scale, scale);
at.translate(-p3x[5] + 10, -p3y[5]);
g2d.setPaint(Color.blue);
g2d.fill(at.createTransformedShape(p3));
}
public void start() {
timer.start();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Affine Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AffineTest sl = new AffineTest();
frame.add(sl);
frame.pack();
frame.setVisible(true);
sl.start();
}
}

Related

Shapes are not drawn in real time

So, if I try to move the shape, it actually moves, but there is no motion animation. In order for the moved shape to be drawn, the application window must be minimized or maximized.
Here is the PentaminoShape class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class PentominoShape extends JFrame implements MouseListener, MouseMotionListener {
JPanel shapePane;
Container contentPane;
private Polygon currPolygon;
private int x, y;
ArrayList<Polygon> polygons = new ArrayList<Polygon>();
JFrame frame;
public PentominoShape(JFrame frame){
this.frame = frame;
initShape();
}
private void initShape() {
Polygon fig1 = new Polygon(new int[]{10, 50, 50, 10}, new int[]{10, 10, 200, 200}, 4);
Polygon fig2 = new Polygon(new int[]{130, 210, 210, 170, 170, 130, 130, 90, 90, 130}, new int[]{80, 80, 120, 120, 200, 200, 160, 160, 120, 120}, 10);
Polygon fig3 = new Polygon(new int[]{290, 330, 330, 250, 250, 290}, new int[]{50, 50, 200, 200, 160, 160}, 6);
Polygon fig4 = new Polygon(new int[]{10, 90, 90, 50, 50, 10}, new int[]{280, 280, 400, 400, 360, 360}, 6);
Polygon fig5 = new Polygon(new int[]{170, 210, 210, 170, 170, 130, 130, 170}, new int[]{240, 240, 360, 360, 400, 400, 320, 320}, 8);
Polygon fig6 = new Polygon(new int[]{250, 370, 370, 330, 330, 290, 290, 250}, new int[]{280, 280, 320, 320, 400, 400, 320, 320}, 8);
Polygon fig7 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 10}, new int[]{480, 480, 520, 520, 480, 480, 560, 560}, 8);
Polygon fig8 = new Polygon(new int[]{170, 250, 250, 290, 290, 170}, new int[]{520, 520, 440, 440, 560, 560}, 6);
Polygon fig9 = new Polygon(new int[]{330, 370, 370, 410, 410, 450, 450, 410, 410, 330}, new int[]{520, 520, 480, 480, 440, 440, 520, 520, 560, 560}, 10);
Polygon fig10 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 90, 90, 50, 50, 10}, new int[]{680, 680, 640, 640, 680, 680, 720, 720, 760, 760, 720, 720}, 12);
Polygon fig11 = new Polygon(new int[]{170, 210, 210, 250, 250, 210, 210, 170}, new int[]{640, 640, 600, 600, 760, 760, 680, 680}, 8);
Polygon fig12 = new Polygon(new int[]{330, 410, 410, 370, 370, 290, 290, 330}, new int[]{640, 640, 680, 680, 760, 760, 720, 720}, 8);
polygons.add(fig1);
polygons.add(fig2);
polygons.add(fig3);
polygons.add(fig4);
polygons.add(fig5);
polygons.add(fig6);
polygons.add(fig7);
polygons.add(fig8);
polygons.add(fig9);
polygons.add(fig10);
polygons.add(fig11);
polygons.add(fig12);
Color[] c = new Color[12];
c[0] = new Color(25, 165, 25);
c[1] = new Color(255, 165, 25);
c[2] = new Color(255, 50, 50);
c[3] = new Color(150, 45, 90);
c[4] = new Color(25, 165, 150);
c[5] = new Color(25, 165, 255);
c[6] = new Color(255, 40, 190);
c[7] = new Color(180, 90, 60);
c[8] = new Color(90, 80, 70);
c[9] = new Color(70, 80, 90);
c[10] = new Color(150, 30, 20);
c[11] = new Color(80, 80, 80);
shapePane = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(c[0]); g2.fill(fig1);
g2.setColor(c[1]); g2.fill(fig2);
g2.setColor(c[2]); g2.fill(fig3);
g2.setColor(c[3]); g2.fill(fig4);
g2.setColor(c[4]); g2.fill(fig5);
g2.setColor(c[5]); g2.fill(fig6);
g2.setColor(c[6]); g2.fill(fig7);
g2.setColor(c[7]); g2.fill(fig8);
g2.setColor(c[8]); g2.fill(fig9);
g2.setColor(c[9]); g2.fill(fig10);
g2.setColor(c[10]); g2.fill(fig11);
g2.setColor(c[11]); g2.fill(fig12);
}
};
/*contentPane = this.getContentPane();
contentPane.add(shapePane);
this.pack();*/
frame.add(shapePane);
shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);
/*shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);*/
}
public void mousePressed(MouseEvent e) {
for(Polygon polygon: polygons) {
if (polygon.contains(e.getPoint())) {
System.out.println("Pressed");
currPolygon = polygon;
x = e.getX();
y = e.getY();
}
}
}
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint();
}
}catch (NullPointerException ex){
}
}
public void mouseReleased(MouseEvent e){
currPolygon = null;
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
}
And the main Pentamino class:
import javax.swing.*;
public class Pentomino extends JFrame {
JFrame frame;
PentominoShape shape;
PentominoPanel panel;
public Pentomino(){
initUI();
}
private void initUI(){
frame = new JFrame("Пентамино");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1500, 900);
setResizable(false);
shape = new PentominoShape(frame);
panel = new PentominoPanel(frame);
/*frame.add(shape);
frame.add(panel);*/
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
Pentomino game = new Pentomino();
}
}
I'm new to Java and I don't understand how to solve this problem. Tried searching the internet for a similar problem but couldn't find anything.
Your bug is here:
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint(); // ***** here ****
}
}catch (NullPointerException ex){
}
}
You're calling repaint() on the enclosing class, a JFrame, one that is never displayed, and this will have not have the effect desired.
In fact, ask yourself, why this...
public class PentominoShape extends JFrame // ...
Why is PentominoShape extending JFrame at all, when it isn't behaving as a JFrame, when it shouldn't be behaving as a JFrame?
Instead, call repaint on the JPanel that holds the shapes, the shapePane JPanel, and yes, get rid of catching the NullPointerException. That should never be in your code:
public void mouseDragged(MouseEvent e) {
if (currPolygon == null) {
return;
}
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
shapePane.repaint(); // now we're repainting the correct JPanel!
}
}
Side note: I'd clean things up a bit including
Not having any class extend JFrame if possible
Create my own polygon type of class:
public class PentominoShape2 {
private Polygon polygon;
private Color color;
public PentominoShape2(Polygon polygon, Color color) {
this.polygon = polygon;
this.color = color;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
g2.fill(polygon);
}
public Polygon getPolygon() {
return polygon;
}
public Color getColor() {
return color;
}
public boolean contains(Point p) {
return polygon.contains(p);
}
}
and then in the drawing JPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (PentominoShape2 poly : polys) {
poly.draw(g);
}
}
same for the mouse listener

How to tilt an elipse in Java?

I have a task: draw a human figure (then it should start moving).
I draw it with primitive figures. When it came to drawing arms and legs, I realized that I needed to use Elipse2d instead of Oval and I need to position it at an angle relative to the body.
I found out that I need AffineTransform, but my attempts to apply it ended with nothing. "Arms" remain parallel to the coordinate axis.
Here is my code:
public class Main extends JFrame {
public static void main(String[] args) {
new Main("Human");
}
public Main(String title) {
super(title);
setBounds(300, 75, 1000,710);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Color skin = new Color((int) 255, (int) 235, (int) 205);
g2.setColor(skin);
//body
g2.fillOval(85, 160, 120, 220);
//face
Ellipse2D face = new Ellipse2D.Double(100, 50, 90, 120);
g2.fill(face);
//arms
Ellipse2D armR = new Ellipse2D.Double(85, 180, 30, 240);
g2.fill(armR);
/* this part isn't working:
AffineTransform tx = new AffineTransform();
tx.getRotateInstance(Math.PI / 4)
.createTransformedShape(armR);
g2.setTransform(tx); */
Ellipse2D armL = new Ellipse2D.Double(175, 180, 30, 240);
g2.fill(armL);
/* this part isn't working:
AffineTransform tx = new AffineTransform();
tx.getRotateInstance(Math.PI / 4)
.createTransformedShape(armL);
g2.setTransform(tx); */
//legs
Ellipse2D legL = new Ellipse2D.Double(100, 365, 40, 280);
g2.fill(legL);
Ellipse2D legR = new Ellipse2D.Double(150, 365, 40, 280);
g2.fill(legR);
Please help me with code where the tilt will work :))

JSlider does not appear?

I have a JSlider but it does not appear when I run the code. I also created a button, but that one shows. Also, do you know how to change the location of the two to the bottom left and right? Thanks!
Here is my code
public class Board extends JPanel implements ActionListener,
KeyListener
{
private CurlingStone[] stones;
private int stonenumber;
private Timer timer;
private int delay = 15;
private Button button;
private JSlider slider;
public Board()
{
stones = new CurlingStone[8];
for(int i = 0; i < 8; i++)
{
if(i%2 == 0)
stones[i] = new CurlingStone(Color.yellow);
else
stones[i] = new CurlingStone(Color.red);
}
stonenumber = 0;
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
this button appears
button = new Button("Launch");
add(button);
button.addActionListener(this);
but the slider does not, so over here I'm not sure what's wrong
slider = new JSlider(1, 10, 1);
slider.setMinorTickSpacing(1);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
add(slider);
timer = new Timer(delay, this);
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0, 0, 400, 725);
g.setColor(Color.gray);
g.fillRect(0, 0, 400, 50);
g.setColor(Color.blue);
g.fillOval(95, 95, 210, 210);
g.setColor(Color.white);
g.fillOval(125, 125, 150, 150);
g.setColor(Color.red);
g.fillOval(155, 155, 90, 90);
g.setColor(Color.white);
g.fillOval(185, 185, 30, 30);
for(int i = 0; i <= stonenumber; i++)
{
stones[i].draw((Graphics2D) g);
}
if(stones[stonenumber].stoneX == 185 &&
stones[stonenumber].stoneY == 600)
{
g.setColor(Color.green);
((Graphics2D)g).setStroke(new BasicStroke(4));
g.drawLine(200, 600, 200 + stones[stonenumber].dirX*10, 530);
}
this.requestFocus();
g.dispose();
}

JPane inside JFrame

I'm trying to make simple app in Java but I have problem with inserting JPane (pasy) inside JFrame(frame). For now my output is two windows, one with resisor and second with combo boxes. Can you please explain me what am I doing wrong? I also tried frame.getContentPane().add(pasy); but it didn't work.
import java.awt.* ;
import java.awt.Color;
import java.awt.event.* ;
import java.awt.Frame ;
import java.awt.Graphics;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Map;
public class rezystorGUI extends JFrame implements ActionListener {
String kod="",kolor="",pasek1="BLACK",pasek2="WHITE",pasek3="VIOLET",pasek4="WHITE",pasek5="BLACK";
JComboBox p1, p2, p3, p4, p5;
JTextField wynik;
ResistorColorCode rcc;
WpiszWartosc wwart;
/** * Constructor for objects of class REZYSTORGUI */
rezystorGUI(){
setTitle("Odczytywanie paskow rezystora");
setSize(375,300);
setVisible(true);
addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
});
rcc = new ResistorColorCode();
makeGUI() ;
}
/** method */
void makeGUI() {
JFrame frame = new JFrame();
frame.setSize(375,300);
JPanel pasy = new JPanel();
pasy.setLayout(new GridLayout(3,3));
pasy.setSize(200,200);
String[]pasek = {"BLACK","BROWN","RED","ORANGE","YELLOW","GREEN","BLUE","VIOLET","GRAY","WHITE"};
String[]multi = {"BLACK","BROWN","RED","ORANGE","YELLOW","GREEN","BLUE","VIOLET"};
String[]tol = {"BROWN","RED","GREEN","BLUE","VIOLET","GRAY","GOLD","SILVER"};
pasy.add(p1 = new JComboBox<String>(pasek));
p1.addActionListener(this);
pasy.add(p2 = new JComboBox<String>(pasek));
p2.addActionListener(this);
pasy.add(p3 = new JComboBox<String>(pasek));
p3.addActionListener(this);
pasy.add(p4 = new JComboBox<String>(multi));
p4.addActionListener(this);
pasy.add(p5 = new JComboBox<String>(tol));
p5.addActionListener(this);
wynik= new JTextField(30);
pasy.add(wynik);
frame.add(pasy);
frame.pack();
frame.setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Map<String, Color> colors = new HashMap<String, Color>();
colors.put("BLUE", Color.BLUE);
colors.put("RED", Color.RED);
colors.put("GREEN", Color.GREEN);
colors.put("WHITE", Color.WHITE);
colors.put("YELLOW", Color.YELLOW);
colors.put("BLACK", Color.BLACK);
colors.put("ORANGE", Color.ORANGE);
colors.put("GRAY", Color.GRAY);
colors.put("VIOLET", new Color(127,0,255));
colors.put("BROWN", new Color(150,75,0));
colors.put("GOLD", new Color(255,215,0));
colors.put("SILVER", new Color(192,192,192));
colors.put("LIGHT-BLUE", new Color(153,204,255));
int x=100;
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 60, 10);
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 10, 50);
g.setColor(colors.get("LIGHT-BLUE"));
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get(pasek1));
x=x+20;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+10;
g.fillRect(x, 50, 95, 100);
g.setColor(colors.get(pasek2));
x=x+5;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek3));
x=x+30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek4));
x=x+30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+30;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get(pasek5));
x=x+10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+10;
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get("GRAY"));
x=x+20;
g.fillRect(x, 95, 60, 10);
x=x+50;
g.setColor(colors.get("GRAY"));
g.fillRect(x, 95, 10, 50);
}
public void actionPerformed(ActionEvent e){
Object eventSource = e.getSource();
if (eventSource == p1){
pasek1 = (String)p1.getSelectedItem();
kod+=pasek1;
repaint();
}
if (eventSource == p2){
pasek2 = (String)p2.getSelectedItem();
kod+="-";
kod+=pasek2;
repaint();
}
if (eventSource == p3){
pasek3 = (String)p3.getSelectedItem();
kod+="-";
kod+=pasek3;
repaint();
}
if (eventSource == p4){
pasek4 = (String)p4.getSelectedItem();
kod+="-";
kod+=pasek4;
repaint();
}
if (eventSource == p5){
pasek5 = (String)p5.getSelectedItem();
String tempkod;
tempkod=kod;
kod+="-";
kod+=pasek5;
repaint();
rcc.inputColorCode(kod);
kod=tempkod;
wynik.setText(rcc.convertToValues()+" Ohm(s)\n"+rcc.tolerancja+" tolerancji");
}
}
public static void main(String[] args)
{
new rezystorGUI() ;
}
}
Your output is two JFrames because you're creating two JFrames. One is the class which extends JFrame:
public class rezystorGUI extends JFrame
and the other is the frame variable:
void makeGUI() {
JFrame frame = new JFrame();
Solution: don't do this, simple as that. Myself, I avoid extending JFrame, since for one it helps prevent me from doing bad things, like painting directly in the JFrame (like you're doing!).
Instead have your class extend JPanel, draw within its paintComponent method, just as the Swing painting tutorials recommend that you do, add all your components to it, and then when you need to display it in a stand alone GUI, create a JFrame, add your class to its contentPane, pack, and display the JFrame.
e.g.,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;
public class Resistor extends JPanel {
private String kod = "";
private String kolor = "";
private String pasek1 = "BLACK";
private String pasek2 = "WHITE";
private String pasek3 = "VIOLET";
private String pasek4 = "WHITE";
private String pasek5 = "BLACK";
private String[] paseks = {pasek1, pasek2, pasek3, pasek4, pasek5};
private JLabel imageLabel = new JLabel();
private List<JComboBox<String>> combos = new ArrayList<>();
private JTextField textField = new JTextField(10);
public Resistor() {
imageLabel.setIcon(createIcon());
String[] pasek = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET",
"GRAY", "WHITE" };
String[] multi = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET" };
String[] tol = { "BROWN", "RED", "GREEN", "BLUE", "VIOLET", "GRAY", "GOLD", "SILVER" };
String[][] comboModels = {pasek, pasek, pasek, multi, tol};
JPanel comboPanel = new JPanel(new GridLayout(2, 3));
for (int i = 0; i < comboModels.length; i++) {
JComboBox<String> combo = new JComboBox<>(comboModels[i]);
combo.addActionListener(new ComboListener());
comboPanel.add(combo);
combos.add(combo);
}
comboPanel.add(textField);
setLayout(new BorderLayout());
add(imageLabel, BorderLayout.CENTER);
add(comboPanel, BorderLayout.PAGE_END);
}
private Icon createIcon() {
String[] pasek = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET",
"GRAY", "WHITE" };
String[] multi = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET" };
String[] tol = { "BROWN", "RED", "GREEN", "BLUE", "VIOLET", "GRAY", "GOLD", "SILVER" };
Map<String, Color> colors = new HashMap<String, Color>();
colors.put("BLUE", Color.BLUE);
colors.put("RED", Color.RED);
colors.put("GREEN", Color.GREEN);
colors.put("WHITE", Color.WHITE);
colors.put("YELLOW", Color.YELLOW);
colors.put("BLACK", Color.BLACK);
colors.put("ORANGE", Color.ORANGE);
colors.put("GRAY", Color.GRAY);
colors.put("VIOLET", new Color(127, 0, 255));
colors.put("BROWN", new Color(150, 75, 0));
colors.put("GOLD", new Color(255, 215, 0));
colors.put("SILVER", new Color(192, 192, 192));
colors.put("LIGHT-BLUE", new Color(153, 204, 255));
int w = 375;
int h = 200;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
int x = 100;
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 60, 10);
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 10, 50);
g.setColor(colors.get("LIGHT-BLUE"));
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get(pasek1));
x = x + 20;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 10;
g.fillRect(x, 50, 95, 100);
g.setColor(colors.get(pasek2));
x = x + 5;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek3));
x = x + 30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek4));
x = x + 30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 30;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get(pasek5));
x = x + 10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 10;
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get("GRAY"));
x = x + 20;
g.fillRect(x, 95, 60, 10);
x = x + 50;
g.setColor(colors.get("GRAY"));
g.fillRect(x, 95, 10, 50);
g.dispose();
return new ImageIcon(img);
}
private class ComboListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO finish!
}
}
private static void createAndShowGui() {
Resistor mainPanel = new Resistor();
JFrame frame = new JFrame("Resistor");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I also recommend that you spend some time on the non-GUI "model" side of things, for instance, that create a ColorCode class, or better, an enum, one that holds a Color field, a String text field, an int multiplier field (that holds multiples of 10), and perhaps a double tolerance field. Doing this would simplify much of your code and make debugging easier.

How to execute an action when x and y location enters another location? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make a little racing game for fun. So far I have two rectangles that successfully move and I have a map setup for them to race through.
My map is also made up of rectangles. Now previously I made a mistake by not giving my two racers a specific objectified name. So they're just two locations that move. Now what i'm trying to do is, to make the rectangle walls actually be walls so they don't just go through them. I've heard I can cover up my mistakes if I make the walls like arrays(not sure how) so they don't go through them. Is this correct? Is there any other way to do this?
Here is how it looks like so far:
Thank you and here is my code.
First class is the info for frames and black rectangle.
Second class is the info for the blue rectangles and the walls.
First Class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, g = 0;
private Color color;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1300, 750);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 725) // stops us from going through the ground
{
vely = 0;
y = 725;
}
if (x > 1250) // stops us from going through the wall
{
velx = 0;
x = 1250;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 2; // removing velx = 0 allows us to go vertically and horizontlly at the same time
velx = 0;
}
if (code == KeyEvent.VK_UP) {
vely = -2; // same goes for here
velx = 0;
}
if (code == KeyEvent.VK_LEFT) {
vely = 0;
velx = -2;
}
{
if (code == KeyEvent.VK_RIGHT) {
vely = 0;
velx = 2;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
public static void main (String arge[]){
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Second Class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Incoming extends MyGame {
private Color color;
int x = 0, y = 0;
int velx = 0, vely = 0;
public Incoming() {
color = Color.BLUE;
Rectangle rect = new Rectangle();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
g.setColor(Color.blue);
g.drawRect(0, 100, 80, 30);
g.drawRect(80, 100, 80, 30);
g.drawRect(160, 100, 80, 30);
g.drawRect(240, 100, 80, 30);
g.drawRect(320, 100, 80, 30);
g.drawRect(400, 100, 80, 30);
g.drawRect(480, 100, 80, 30);
g.drawRect(560, 100, 80, 30);
g.drawRect(640, 100, 80, 30);
g.drawRect(720, 100, 80, 30);
g.drawRect(800, 100, 80, 30);
g.drawRect(880, 100, 80, 30);
g.drawRect(960, 100, 80, 30);
g.drawRect(1040, 100, 80, 30);
g.drawRect(1040, 250, 80, 30);
g.drawRect(1120, 250, 80, 30);
g.drawRect(1200, 250, 80, 30);
g.drawRect(960, 250, 80, 30);
g.drawRect(880, 250, 80, 30);
g.drawRect(800, 250, 80, 30);
g.drawRect(720, 250, 80, 30);
g.drawRect(640, 250, 80, 30);
g.drawRect(560, 250, 80, 30);
g.drawRect(480, 250, 80, 30);
g.drawRect(400, 250, 80, 30);
g.drawRect(320, 250, 80, 30);
g.drawRect(240, 250, 80, 30);
g.drawRect(160, 250, 80, 30);
g.drawRect(1040, 400, 80, 30);
g.drawRect(960, 400, 80, 30);
g.drawRect(880, 400, 80, 30);
g.drawRect(800, 400, 80, 30);
g.drawRect(720, 400, 80, 30);
g.drawRect(640, 400, 80, 30);
g.drawRect(560, 400, 80, 30);
g.drawRect(480, 400, 80, 30);
g.drawRect(400, 400, 80, 30);
g.drawRect(320, 400, 80, 30);
g.drawRect(240, 400, 80, 30);
g.drawRect(160, 400, 80, 30);
g.drawRect(80, 400, 80, 30);
g.drawRect(0, 400, 80, 30);
g.drawRect(1040, 550, 80, 30);
g.drawRect(1120, 550, 80, 30);
g.drawRect(1200, 550, 80, 30);
g.drawRect(960, 550, 80, 30);
g.drawRect(880, 550, 80, 30);
g.drawRect(800, 550, 80, 30);
g.drawRect(720, 550, 80, 30);
g.drawRect(640, 550, 80, 30);
g.drawRect(560, 550, 80, 30);
g.drawRect(480, 550, 80, 30);
g.drawRect(400, 550, 80, 30);
g.drawRect(320, 550, 80, 30);
g.drawRect(240, 550, 80, 30);
g.drawRect(160, 550, 80, 30);
g.drawRect(1040, 550, 80, 30);
g.drawRect(960, 550, 80, 30);
g.drawRect(880, 550, 80, 30);
g.drawRect(800, 550, 80, 30);
g.drawRect(720, 550, 80, 30);
g.drawRect(640, 550, 80, 30);
g.drawRect(560, 550, 80, 30);
g.drawRect(480, 550, 80, 30);
g.drawRect(400, 550, 80, 30);
g.drawRect(320, 550, 80, 30);
g.drawRect(240, 550, 80, 30);
g.drawRect(160, 550, 80, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 725) // stops us from going through the ground
{
vely = 0;
y = 725;
}
if (x > 1250) // stops us from going through the wall
{
velx = 0;
x = 1250;
}
if (y < 0.1)
{
y = 50;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_S) {
vely = 2; // removing velx = 0 allows us to go vertically and horizontlly at the same time
velx = 0;
}
if (code == KeyEvent.VK_W) {
vely = -2; // same goes for here
velx = 0;
}
if (code == KeyEvent.VK_A) {
vely = 0;
velx = -2;
}
{
if (code == KeyEvent.VK_D) {
vely = 0;
velx = 2;
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
}
}
How would I list rectangles?
See the DrawOnCompnent example from Custom Painting Approaches. It shows you how to paint from an ArrayList.

Categories

Resources