I'm Making a program that displays a building, some clouds, and trees with Java Graphics. I would like to use a Timer to scroll the clouds across the screen. I'm not sure how to use the timer to continually loop the clouds after it reaches the end of the JFrame
timer is on 126-147
cloud method is on 184 - 239
I have tried to put all the Timer code within the Cloud drawing method but I can't figure out how to use the variable that is tied to the timer to make the clouds move inside the method for the clouds.
Currently, I just have most of the timer stuff outside of the method, and then using 3 different cloud methods, which is redundant.
I'm very new to java so sorry if I have basic mistakes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Elevator extends JFrame implements ActionListener {
private final int DISPLAY_WIDTH = 800;
private final int DISPLAY_HEIGHT = 600;
private JPanel guiPanel, buttonPanel;
private DisplayPanel display;
private JLabel Title;
private JButton Floor;
private JComboBox Select;
int locX, locY;
final int LIMIT = 10;
final int NUM_ROWS = 10;
final int WINDOWWIDTH = 12;
final int WINDOWHEIGHT = 25;
final int WINDOWSPACING = 10;
final int FLOORSPACING = 30;
final int FLOOROFFSET = -10;
final int ELEVATOR_COLUMN = 5;
private static final int NUM_ITERATIONS = 10; //number of floors for combo box selection
private int lvlChoice; //variable holding elevator level choice for item event
private int buildX, buildY, buildW, buildH; //building height dem
Color drkGrn = new Color ( 49, 216, 91); //building ground color
Color flWind = new Color (163, 156, 77); //default floor window color
Color bldCol = new Color (176, 201, 212); // building color
Color crntFl = new Color (255, 247, 0); //current floor color for elevator
Color blu1 = new Color ( 157, 215, 255 ); //cloud colors
Color blu2 = new Color (93, 172, 227);
Color blu3 = new Color ( 62, 167, 240);
Color blu4 = new Color (136, 156, 169);
Color blu5 = new Color (209, 230, 245);
Color plmLeaf = new Color ( 6, 145, 84);
Color trunk =new Color ( 170, 85, 0);
//graphics variables
final int tWidth = 10;
final int tHeiht =120;
public static void main(String[] args) {
Elevator frame = new Elevator();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.initializeVariables();
frame.setUpGUI();
frame.pack();
frame.setVisible(true);
}
public void initializeVariables() {
locX = 300;
locY = 150;
buildX = locX-20;
buildY = locY-10;
buildH =375;
buildW =250;
lvlChoice = 1;
}
public void setUpGUI() {
Container window = getContentPane(); //you attach Jcomponents to this pannel
display = new DisplayPanel();
guiPanel = new JPanel(new FlowLayout());
buttonPanel = new JPanel(new FlowLayout());
//TODO add title panel
/* Title = new JLabel("Elevator");
Title.setFont(new Font(" San Serif", Font.PLAIN, 20));
titlePanel.add(Title);*/
Floor =new JButton("Floor");
Floor.addActionListener(this);
Select = new JComboBox();
for (int i = 0; i < NUM_ITERATIONS; i++) {
Select.addItem(String.valueOf(i + 1)); //this takes the int value and the parses it to a string
}
buttonPanel.add(Select);
buttonPanel.add(Floor);
window.add(buttonPanel, BorderLayout.NORTH);
window.add(guiPanel, BorderLayout.SOUTH);
window.add(display, BorderLayout.CENTER);
}
//cloude1 timer, moviment
Timer tm1 = new Timer(60, this);
int x1 = 800, velX1 = 3; //position of x on cloud and velociity of cloudes
//cloude1 timer, moviment
Timer tm2 = new Timer(50, this);
int x2 = 700, velX2 = 2; //position of x on cloud and velociity of cloudes
//cloude1 timer, moviment
Timer tm3 = new Timer(75, this);
int x3 = 777, velX3 = 2; //position of x on cloud and velociity of cloudes
#Override
public void actionPerformed(ActionEvent e) {
lvlChoice = Integer.parseInt((String) Select.getSelectedItem());
display.repaint();
//make only one of these simplfiy the "x1" to x
x1 = x1 - velX1; //every 2 milliseconds and 2 to the position of x whitch starts at 0
x2 = x2 - velX2; //every 2 milliseconds and 2 to the position of x whitch starts at 0
x3 = x3 - velX3; //every 2 milliseconds and 2 to the position of x whitch starts at 0
}
class DisplayPanel extends JPanel {
DisplayPanel() {
setPreferredSize(new Dimension(DISPLAY_WIDTH, DISPLAY_HEIGHT));
this.setBackground(Color.WHITE);
}
//executes all paint methods
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
backDrop(g2d);
cloud1(g2d, 100, 45);
cloud3(g2d, 50, 30);
buildingLoop(g2d);
cloud2(g2d, 240, 40);
tree(g2d, 140, 400);
tree(g2d, 500, 400);
tree(g2d, 650, 470);
tree(g2d, 600, 420);
tree(g2d, 190, 390);
tree(g2d, 45, 425);
tree(g2d, 75, 450);
}
//static background objects (ground, trees, ect..)
public void backDrop(Graphics2D g2d) {
g2d.setColor(drkGrn);
g2d.fillRect(0,500,getWidth(), getHeight());
}
//new method custom for cloudes
public void cloud1(Graphics2D g2d, int y, int CLDSIZE) {
//cloud 1
//y starts at 100 to be put in method argument
g2d.setColor(blu4);
g2d.fillOval(x1, y, CLDSIZE, CLDSIZE);
g2d.setColor(blu1);
g2d.fillOval(x1 + 15, y-10, CLDSIZE, CLDSIZE);
g2d.setColor(blu3);
g2d.fillOval(x1 + 30, y+10, CLDSIZE, CLDSIZE);
g2d.setColor(blu2);
g2d.fillOval(x1 + 45, y-10, CLDSIZE, CLDSIZE);
g2d.setColor(blu5);
g2d.fillOval(x1 + 57, y, CLDSIZE, CLDSIZE);
tm1.start(); //start the timer
}
public void cloud2(Graphics2D g2d, int y, int CLDSIZE) {
//cloud 2
g2d.setColor(blu5);
g2d.fillOval(x2, y, CLDSIZE,CLDSIZE);
g2d.setColor(blu4);
g2d.fillOval(x2+15, y-20, CLDSIZE,CLDSIZE);
g2d.setColor(blu2);
g2d.fillOval(x2+30, y+10, CLDSIZE,CLDSIZE);
g2d.setColor(blu3);
g2d.fillOval(x2+45, y-20, CLDSIZE,CLDSIZE);
g2d.setColor(blu1);
g2d.fillOval(x2+57, y, CLDSIZE,CLDSIZE);
tm2.start(); //start the timer
}
public void cloud3(Graphics2D g2d, int y, int CLDSIZE) {
//cloud 3
//y starts at 30
g2d.setColor(blu3);
g2d.fillOval(x3, y, CLDSIZE,CLDSIZE);
g2d.setColor(blu2);
g2d.fillOval(x3+15, y-10, CLDSIZE,CLDSIZE);
g2d.setColor(blu4);
g2d.fillOval(x3+30, y+10, CLDSIZE,CLDSIZE);
g2d.setColor(blu5);
g2d.fillOval(x3+45, y-10, CLDSIZE,CLDSIZE);
g2d.setColor(blu1);
g2d.fillOval(x3+57, y, CLDSIZE,CLDSIZE);
tm3.start(); //start the timer
}
public void tree(Graphics2D g2d, int xPoint, int yPoint){
int leafSize =25;
g2d.setColor(trunk);
g2d.fillRect(xPoint+25,yPoint,tWidth, tHeiht);
g2d.setColor(plmLeaf);
g2d.fillOval(xPoint,yPoint, leafSize, leafSize);
g2d.fillOval(xPoint+5,yPoint-10, leafSize, leafSize);
g2d.fillOval(xPoint+5,yPoint+10, leafSize, leafSize);
g2d.fillOval(xPoint+10,yPoint, leafSize, leafSize);
g2d.fillOval(xPoint+10,yPoint+10, leafSize, leafSize);
g2d.fillOval(xPoint+30,yPoint-10, leafSize, leafSize);
g2d.fillOval(xPoint+30,yPoint+10, leafSize, leafSize);
g2d.fillOval(xPoint+35,yPoint, leafSize, leafSize);
g2d.fillOval(xPoint+35,yPoint+10, leafSize, leafSize);
}
//building the building and windows for the building
public void buildingLoop(Graphics2D g2d) {
g2d.setColor(bldCol);
g2d.fillRect(buildX, buildY, buildW, buildH);
g2d.setColor(flWind);
for (int j = 1; j <=NUM_ROWS; j++) { //draws row
for (int i = 0; i <= LIMIT; i++) { //draws window's
if (i == ELEVATOR_COLUMN && j == NUM_ROWS - lvlChoice + 1) {
g2d.setColor(crntFl);
}
g2d.fillRect (i* (WINDOWWIDTH + WINDOWSPACING) + buildX + WINDOWSPACING, buildY + j * FLOORSPACING - FLOOROFFSET, WINDOWWIDTH , WINDOWHEIGHT);
g2d.setColor(flWind);
}
}
}
}
}
I have tried to put all the Timer code within the Cloud drawing method but I can't figure out how to use the variable that is tied to the timer and get that value passed from the actual parameter that is entered from the method.
Currently, I just have most of the timer stuff outside of the method, and then using 3 different cloud methods, which is redundant.
Here is how I'd write it:
If you have any questions you're welcome to ask :)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Elevator extends JFrame implements ActionListener
{
private final int DISPLAY_WIDTH = 800;
private final int DISPLAY_HEIGHT = 600;
private JPanel guiPanel, buttonPanel;
private DisplayPanel display;
private JLabel Title;
private JButton Floor;
private JComboBox Select;
int locX, locY;
final int LIMIT = 10;
final int NUM_ROWS = 10;
final int WINDOWWIDTH = 12;
final int WINDOWHEIGHT = 25;
final int WINDOWSPACING = 10;
final int FLOORSPACING = 30;
final int FLOOROFFSET = -10;
final int ELEVATOR_COLUMN = 5;
private static final int NUM_ITERATIONS = 10; // number of floors for combo box selection
private int lvlChoice; // variable holding elevator level choice for item event
private int buildX, buildY, buildW, buildH; // building height dem
Color drkGrn = new Color(49, 216, 91); // building ground color
Color flWind = new Color(163, 156, 77); // default floor window color
Color bldCol = new Color(176, 201, 212); // building color
Color crntFl = new Color(255, 247, 0); // current floor color for elevator
// an array with all your clouds
private Cloud[] clouds;
private Tree[] trees;
public static void main(String[] args)
{
Elevator frame = new Elevator();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// added the cloud initialization in there
frame.initializeVariables();
frame.setUpGUI();
frame.pack();
frame.setVisible(true);
// starts ticking each 30 ms
frame.tick();
}
private void tick()
{
// while loop for ever and ever
while (true)
{
// ticks all the clouds
for (int i = 0; i < clouds.length; i++)
{
clouds[i].tick();
}
// updates the JFrame graphics
display.repaint();
// pauses the ticking for 30 ms
try
{
Thread.sleep(30);
} catch (InterruptedException e)
{
}
}
}
public void initializeVariables()
{
locX = 300;
locY = 150;
buildX = locX - 20;
buildY = locY - 10;
buildH = 375;
buildW = 250;
lvlChoice = 1;
// puts 3 clouds in our array
clouds = new Cloud[] { new Cloud(800, 100, 45, 3, true), new Cloud(700, 50, 30, 2, false),
new Cloud(777, 240, 40, 2, false), };
trees = new Tree[] { new Tree(140, 400), new Tree(500, 400), new Tree(650, 470), new Tree(600, 420),
new Tree(190, 390), new Tree(45, 425), new Tree(75, 450) };
}
public void setUpGUI()
{
Container window = getContentPane(); // you attach Jcomponents to this pannel
display = new DisplayPanel();
guiPanel = new JPanel(new FlowLayout());
buttonPanel = new JPanel(new FlowLayout());
// TODO add title panel
/* Title = new JLabel("Elevator");
Title.setFont(new Font(" San Serif", Font.PLAIN, 20));
titlePanel.add(Title);*/
Floor = new JButton("Floor");
Floor.addActionListener(this);
Select = new JComboBox<>();
for (int i = 0; i < NUM_ITERATIONS; i++)
{
Select.addItem(String.valueOf(i + 1)); // this takes the int value and the parses it to a string
}
buttonPanel.add(Select);
buttonPanel.add(Floor);
window.add(buttonPanel, BorderLayout.NORTH);
window.add(guiPanel, BorderLayout.SOUTH);
window.add(display, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e)
{
lvlChoice = Integer.parseInt((String) Select.getSelectedItem());
display.repaint();
// moves each cloud by the respective velocity
for (int i = 0; i < clouds.length; i++)
clouds[i].x -= clouds[i].velX;
}
class DisplayPanel extends JPanel
{
private static final long serialVersionUID = 1L;
DisplayPanel()
{
setPreferredSize(new Dimension(DISPLAY_WIDTH, DISPLAY_HEIGHT));
this.setBackground(Color.WHITE);
}
// executes all paint methods
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
backDrop(g2d);
for (Cloud c : clouds)
{
if (!c.Foreground) c.draw(g2d);
}
buildingLoop(g2d);
for (Cloud c : clouds)
{
if (c.Foreground) c.draw(g2d);
}
for (Tree t : trees)
{
t.draw(g2d);
}
}
// static background objects (ground, trees, ect..)
public void backDrop(Graphics2D g2d)
{
g2d.setColor(drkGrn);
g2d.fillRect(0, 500, getWidth(), getHeight());
}
// building the building and windows for the building
public void buildingLoop(Graphics2D g2d)
{
g2d.setColor(bldCol);
g2d.fillRect(buildX, buildY, buildW, buildH);
g2d.setColor(flWind);
for (int j = 1; j <= NUM_ROWS; j++)
{ // draws row
for (int i = 0; i <= LIMIT; i++)
{ // draws window's
if (i == ELEVATOR_COLUMN && j == NUM_ROWS - lvlChoice + 1)
{
g2d.setColor(crntFl);
}
g2d.fillRect(i * (WINDOWWIDTH + WINDOWSPACING) + buildX + WINDOWSPACING,
buildY + j * FLOORSPACING - FLOOROFFSET, WINDOWWIDTH, WINDOWHEIGHT);
g2d.setColor(flWind);
}
}
}
}
}
class Cloud
{
int x = 800, y, velX = 3; // position of x on cloud and velociity of cloudes
final Color blu1 = new Color(157, 215, 255); // cloud colors
final Color blu2 = new Color(93, 172, 227);
final Color blu3 = new Color(62, 167, 240);
final Color blu4 = new Color(136, 156, 169);
final Color blu5 = new Color(209, 230, 245);
int Size;
boolean Foreground;
public Cloud(int x, int y, int Size, int velX, boolean Foreground)
{
this.x = x;
this.y = y;
this.Size = Size;
this.velX = velX;
this.Foreground = Foreground;
}
public void tick()
{
x -= velX;
if (x < -100) x = 1000;
}
public void draw(Graphics2D g2d)
{
// cloud 1
// y starts at 100 to be put in method argument
g2d.setColor(blu4);
g2d.fillOval(x, y, Size, Size);
g2d.setColor(blu1);
g2d.fillOval(x + 15, y - 10, Size, Size);
g2d.setColor(blu3);
g2d.fillOval(x + 30, y + 10, Size, Size);
g2d.setColor(blu2);
g2d.fillOval(x + 45, y - 10, Size, Size);
g2d.setColor(blu5);
g2d.fillOval(x + 57, y, Size, Size);
}
}
class Tree
{
int xPoint, yPoint;
public Tree(int xPoint, int yPoint)
{
this.xPoint = xPoint;
this.yPoint = yPoint;
}
public void draw(Graphics2D g2d)
{
int leafSize = 25;
// graphics variables
final int tWidth = 10;
final int tHeiht = 120;
final Color plmLeaf = new Color(6, 145, 84);
final Color trunk = new Color(170, 85, 0);
g2d.setColor(trunk);
g2d.fillRect(xPoint + 25, yPoint, tWidth, tHeiht);
g2d.setColor(plmLeaf);
g2d.fillOval(xPoint, yPoint, leafSize, leafSize);
g2d.fillOval(xPoint + 5, yPoint - 10, leafSize, leafSize);
g2d.fillOval(xPoint + 5, yPoint + 10, leafSize, leafSize);
g2d.fillOval(xPoint + 10, yPoint, leafSize, leafSize);
g2d.fillOval(xPoint + 10, yPoint + 10, leafSize, leafSize);
g2d.fillOval(xPoint + 30, yPoint - 10, leafSize, leafSize);
g2d.fillOval(xPoint + 30, yPoint + 10, leafSize, leafSize);
g2d.fillOval(xPoint + 35, yPoint, leafSize, leafSize);
g2d.fillOval(xPoint + 35, yPoint + 10, leafSize, leafSize);
}
}
Related
I'm new to gui java and I've been trying to recreate the game called" jump it" (http://www.crazygames.com/game/jump-it) and I'm currently on the process of making the randomized rectangles for my character to jump on. However I ran my code and I had no errors, but the rectangles that I made isn't showing up. I attached my code underneath, it's kinda long sorry about that.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;
import java.util.TimerTask;
class GuiGame{
public static void main(String args[]) {
JFrame f = new JFrame("RUN - Christine & Esther"); //title of frame
Container cont = f.getContentPane(); // get container - top of the frame
cont.setLayout(new BorderLayout());
BtnActPanel bp = new BtnActPanel(); // create an object of our game panel
cont.add(bp, BorderLayout.CENTER );
f.setVisible(true);
f.setSize(975,613); //size of frame
}
}
class Rectangle{
static Random r = new Random();
static int upperX = 100;
static int lowerX = 20;
static int upperY = 550;
static int lowerY = 450;
static int minWidth = 200;
static int maxWidth = 600;
static int minHeight = 40;
static int maxHeight = 140;
static int x = 0, y = 0, w = 0, h = 0, check = 0;
public Rectangle(){
check++;
int x = 650 + 50*check;
int y = r.nextInt(upperY-lowerY + 1) + lowerY; // from 450 to 550
int w = r.nextInt(maxWidth-minWidth + 1) + minWidth; // from 200 to 600
int h = r.nextInt(maxHeight - minHeight + 1) + minHeight; // from 40 to 140
}
public int getx(){
return x;
}
public int gety(){
return y;
}
public int getw(){
return w;
}
public int geth(){
return h;
}
}
class BtnActPanel extends JPanel implements ActionListener{
//variables
private JButton b1, b2, b3;
private JPanel background;
private JPanel game;
private Timer t, timer;
private int x = 0, check1 = 0, index = 0, x1 = 650, count2 = 0,
y2 = (int)(Math.random()*100)+40, y1 = (int)(Math.random()*100)+450,
x2 = (int)(Math.random()*600)+200, xaxis = 0, yaxis = 0, w = 0, h = 0, count = 0;
private ImageIcon []arrImage;
private boolean check2;
private static ImageIcon icon, exitButton, startButton, questionButton, b, instruct, c ;
public BtnActPanel(){
c = new ImageIcon("character.png"); // constructor
t = new Timer (100,this);
arrImage = new ImageIcon[2];
arrImage[0] = new ImageIcon("character.png");
arrImage[1] = new ImageIcon("character2.png");
startButton = new ImageIcon("startButton.png");//start button image
questionButton = new ImageIcon("QuestionButton.png"); //question button image
exitButton = new ImageIcon("exitButton.png"); //exit button image
icon = new ImageIcon("Title.jpg");//title image
b1 = new JButton(questionButton); // creates first button
//only shows button image with borders
b1.setOpaque(false);
b1.setContentAreaFilled(false);
b1.setBorderPainted(false);
b1.setFocusPainted(false);
b2 = new JButton(startButton);// creates second button
//only shows button image with borders
b2.setOpaque(false);
b2.setContentAreaFilled(false);
b2.setBorderPainted(false);
b2.setFocusPainted(false);
b3 = new JButton(exitButton);// creates third button
//only shows button image with borders
b3.setOpaque(false);
b3.setContentAreaFilled(false);
b3.setBorderPainted(false);
b3.setFocusPainted(false);
//adds buttons to code
this.add(b1);
this.add(b2);
this.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}// end of constructor
public void actionPerformed(ActionEvent e) { //checks which button the user presses and performs actions based off choice
if(e.getSource() == b1){
check1 = 2;
this.remove(b1);
this.remove(b3);
repaint();
instruct = new ImageIcon("Instructions.jpg");
}
else if (e.getSource() == b2){
t.start();
check1 = 1;
this.remove(b1);
this.remove(b2);
this.remove(b3);
repaint();
b = new ImageIcon("toskyline.png");
}
else if (e.getSource() == b3){
JOptionPane.showMessageDialog(null, "This is an exit button, hope you enjoyed the game! :)", "Exit message",JOptionPane.WARNING_MESSAGE ); //shows exit message
System.exit(0);//exits program
}
else if (e.getSource() == t){
if (index == 0){
index = 1;
c = arrImage[1];
}
else{
index = 0;
c = arrImage[0];
}
if(count%50 == 0 && count >= 50){
Rectangle obstacle = new Rectangle();
int xaxis = obstacle.getx();
int yaxis = obstacle.gety();
int w = obstacle.getw();
int h = obstacle.geth();
xaxis = xaxis - 10;
count2 = 1;
}
x = x - 10;
x1 = x1 - 10;
repaint();
}
}
public void paintComponent(Graphics g){//this method draws and paints images and icons based on the user decisions
super.paintComponent(g);
if(check1 == 0)[enter image description here][1]
g.drawImage(icon.getImage(),0,0,null);
if(check1 == 1){
g.drawImage(b.getImage(),0,0,null);
g.setColor(Color.black);
g.fillRect(x,495, 500, 35);
g.fillRect(x1, y1, x2, y2);
count++;
System.out.println(count);
if(count2 == 1){
g.fillRect(xaxis, yaxis, w, h);
count2 = 0;
}
g.drawImage(c.getImage(), 100, 460, null);
}
if(check1 == 2)
g.drawImage(instruct.getImage(),0,0,null);
b1.setBounds(320, 350, 100, 100);
b2.setBounds(420, 350, 100, 100);
b3.setBounds(520, 350, 100, 100);
}
}//end of class
Using your ranges I made a demo.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Demo extends JPanel implements ActionListener {
final static int height = 800;
final static int width = 800;
final static String title = "title";
JFrame frame = new JFrame("default title");
Timer timer;
static Random r = new Random();
static int upperX = 100;
static int lowerX = 20;
static int upperY = 550;
static int lowerY = 450;
static int minWidth = 200;
static int maxWidth = 600;
static int minHeight = 40;
static int maxHeight = 140;
List<MyRectangle> rectangles = new ArrayList<>();
public static void main(String[] args) {
SwingUtilities
.invokeLater(() -> new Demo().start());
}
public Demo() {
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setPreferredSize(
new Dimension(width, height));
setBackground(Color.WHITE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void start() {
timer = new Timer(0, this);
timer.setDelay(1000);
timer.start();
}
public void actionPerformed(ActionEvent ae) {
rectangles.add(createRectangle());
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (MyRectangle r : rectangles) {
g2d.setColor(Color.black);
g2d.drawRect(r.x, r.y, r.width, r.height);
g2d.setColor(r.color);
g2d.fillRect(r.x+1, r.y+1, r.width-1,r.height-1);
}
g2d.dispose();
}
Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.GRAY};
int color = 0;
public MyRectangle createRectangle() {
int y = r.nextInt(upperY - lowerY + 1) + lowerY; // from 450 to 550
int w = r.nextInt(maxWidth - minWidth + 1)
+ minWidth; // from 200 to 600
int h = r.nextInt(maxHeight - minHeight + 1)
+ minHeight; // from 40 to 140
int x = r.nextInt(upperX - lowerX + 1) + lowerX;
Color c = colors[color++ % colors.length];
return new MyRectangle(c, x, y, w, h);
}
class MyRectangle extends Rectangle {
Color color;
MyRectangle(Color c, int x, int y, int w, int h) {
super(x, y, w, h);
this.color = c;
}
}
}
This extends the JDK class Rectangle and adds a color field to the subclass. It displays a new rectangle very second.
I recently made a drawing of a car and tried changing the .fillPolygon to .fillRect but it didnt work to change the car to look like a truck. How would I change my code below to make the drawing of the car into a drawing of a truck?I did this on Eclipse.
Car.java
import java.awt.*;
public class Car {
//Coordinates if car is drawn at position 0,0
private int [] x = {0, 0, 20, 25, 70, 80, 105, 110};
private int[] y = {35, 15, 15, 0, 0, 15, 15, 35};
private int [] xCurrent = new int [x.length];
private int [] yCurrent = new int [y.length];
private int xOffset = 0, yOffset =0;
private Color carColor;
//-----------------------------------------------------------------
// Sets up the graphical car with the specified offsets.
//-----------------------------------------------------------------
public Car(int xOff, int yOff, Color color)
{
xOffset = xOff;
yOffset = yOff;
carColor = color;
for (int i=0; i < x.length; i++)
{
xCurrent[i] = x[i] + xOffset;
yCurrent[i] = y[i] + yOffset;
}
}
//
public int getXOffset() {return xOffset;}
public int getYOffset() {return yOffset;}
//-----------------------------------------------------------------
// Draws the car at a particular x and y offset.
//-----------------------------------------------------------------
public void draw(Graphics page)
{
page.setColor(carColor);
page.fillPolygon(xCurrent, yCurrent, x.length);
page.setColor(Color.black);
page.fillOval(13+xOffset, 28+yOffset, 14, 14); // rear wheel
page.fillOval(83+xOffset, 28+yOffset, 14, 14); // front wheel
page.drawLine(15+xOffset, 18+yOffset, 15+xOffset, 3+yOffset);
}
}
CarPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CarPanel extends JPanel {
private Car car1, car2, car3;
private final int DELAY =20;
private int x, y;
private final int SPEED =2;
public CarPanel ()
{
car1 =new Car(200, 150, Color.BLUE);
car2 = new Car(50, 50, Color.RED);
car3 = new Car(0, 220, Color.GREEN);
x =0;
y= 220;
setPreferredSize(new Dimension(450,300));
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
x = car3.getXOffset() + SPEED;
y = car3.getYOffset();
if (x > getWidth()) x = 0;
car3 = new Car(x, y, Color.GREEN);
x = car2.getXOffset() + SPEED + 5;
if (x > getWidth()) x = 0;
y = car2.getYOffset();
car2 = new Car(x, y, Color.RED);
repaint();
}
};
new Timer(DELAY, taskPerformer).start();
}
//-----------------------------------------------------------------
// Draws the car.
//-----------------------------------------------------------------
public void paint(Graphics page)
{
super.paint(page);
car1.draw(page);
car2.draw(page);
car3.draw(page);
}
}
GUITester.java
import javax.swing.JFrame;
public class GUITester {
//-----------------------------------------------------------------
// Sets up a frame containing a tabbed pane. The panel on each
// tab demonstrates a different layout manager.
//-----------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("GUI Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add any panel into here
//ArrayReviews panel = new ArrayReviews();
//ArrayBetter panel = new ArrayBetter();
CarPanel panel = new CarPanel();
//NumericKeypadPanel panel = new NumericKeypadPanel();
//StarPanel panel = new StarPanel();
//SnowPanel panel = new SnowPanel();
//Draw1StarPanel panel = new Draw1StarPanel();
//Rain panel = new Rain();
//Cards panel = new Cards();
//SelectionSortPanel panel = new SelectionSortPanel();
//PersonPanel panel = new PersonPanel();
//SinPanel panel = new SinPanel();
//KochSnowFlake panel = new KochSnowFlake();
//CalculatorPanelSimple panel = new CalculatorPanelSimple();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Yuk! You are declaring x[] y[] arrays, and then constructing xOffset[] yOffset[] arrays to translate you car/truck to different positions. You can let the GPU do the work for you:
void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g; // Every Graphics is actually a Graphics2D.
translate(xOffset, yOffset); // Move the graphic origin
g2d.fillPolygon(x, y, x.length); // Draw with original coordinates
translate(-xOffset, yOffset); // Restore graphic origin, for other drawing
}
It doesn't turn your car into a truck, but your code doesn't show your attempt, so it is hard to say where you went wrong.
But, if this simplifies your code, perhaps that will help.
As #MadProgrammer points out, the Shape API might also be useful.
static Shape CAR_SHAPE;
static {
// Initialize CAR_SHAPE
}
void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
translate(xOffset, yOffset);
g2d.draw(CAR_SHAPE);
translate(-xOffset, yOffset);
}
See Trail: 2D Graphics
In my code i generate randoms integer between 0 and 60 and i draw lines based on these.
I just want my lines fit the ordinate vertical line without touching my randoms integer... I guess it's kind of a mathematics problem but i'm really stuck here!
Here's my code first:
Windows.java:
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
print.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
Panel.java:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,200,0);
Color blue = new Color (0,0,200);
Color yellow = new Color (200,200,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
g.drawString("10", 0, this.getHeight()-85);
g.drawString("20", 0, this.getHeight()-125);
g.drawString("30", 0, this.getHeight()-165);
g.drawString("40", 0, this.getHeight()-205);
g.drawString("50", 0, this.getHeight()-245);
g2.drawString("Maximum: ", 20, this.getHeight()-20);
g2.drawString(Integer.toString(max), 80, this.getHeight()-20);
g2.drawString("Minimum: ", 140, this.getHeight()-20);
g2.drawString(Integer.toString(min), 200, this.getHeight()-20);
g2.drawString("Average: ", 260, this.getHeight()-20);
g2.drawString(Integer.toString(moyenne), 320, this.getHeight()-20);
g2.setColor(red);
g2.drawLine(500, this.getHeight()-25, 540, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Maximum", 560, this.getHeight()-20);
g2.setColor(blue);
g2.drawLine(640, this.getHeight()-25, 680, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Minimum", 700, this.getHeight()-20);
g2.setColor(green);
g2.drawLine(780, this.getHeight()-25, 820, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Average", 840, this.getHeight()-20);
if(!randL.isEmpty()){
g2.setColor(red);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(new Color(0,0,0));
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(Math.random() * (60));
lastT += 80;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
}
k++;
if(randL.size()>=12)
{
randL.removeAll(randL);
tL.removeAll(tL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
And here it what i gives me :
Sorry it's a real mess!
Any thoughts ?
Thanks.
You need to stop working with absolute/magical values, and start using the actual values of the component (width/height).
The basic problem is a simple calculation which takes the current value divides it by the maximum value and multiples it by the available width of the allowable area
int length = (value / max) * width;
value / max generates a percentage value of 0-1, which you then use to calculate the percentage of the available width of the area it will want to use.
The following example places a constraint (or margin) on the available viewable area, meaning all the lines need to be painted within that area and not use the entire viewable area of the component
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawLine {
public static void main(String[] args) {
new DrawLine();
}
public DrawLine() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int margin = 20;
int width = getWidth() - (margin * 2);
int height = getHeight() - (margin * 2);
int x = margin;
for (int index = 0; index < 4; index++) {
int y = margin + (int)(((index / 3d) * height));
int length = (int)(((index + 1) / 4d) * width);
g2d.drawLine(x, y, x + length, y);
}
g2d.dispose();
}
}
}
I have read multiple topics about why repaint does not call the paintComponent, yet I have not been able to combine those answers with my code to get it working. I have to do an assignment for school where in a GUI I give the X and Y coordinate for N trucks to be drawn, first one on X and Y and the rest randomly.
public class TruckMaker extends JPanel {
public int y1;
public int x1;
public static Double circle, circle2, circle3;
public static java.awt.geom.Rectangle2D.Double rectangle, rectangle2;
Random random = new Random();
public TruckMaker() {
circle = new Ellipse2D.Double();
circle2 = new Ellipse2D.Double();
circle3 = new Ellipse2D.Double();
rectangle = new Rectangle2D.Double();
rectangle2 = new Rectangle2D.Double();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(circle);
g2.fill(rectangle);
g2.fill(rectangle2);
g2.fill(circle2);
g2.fill(circle3);
System.out.println("Paint component is being called");
}
public void getTrucks(int x, int y, int n) {
boolean firstTimer = true;
while (n > 0) {
if (firstTimer) {
x1 = x;
y1 = y;
rectangle = new Rectangle2D.Double(x1, y1, 50, 50);
circle = new Ellipse2D.Double(x1 + 25, (y1 + 65), 25, 25);
rectangle2 = new Rectangle2D.Double(x1 + 65, y1 - 25, 150, 75);
circle2 = new Ellipse2D.Double(x1 + 140, (y1 + 65), 25, 25);
circle3 = new Ellipse2D.Double(x1 + 175, (y1 + 65), 25, 25);
n--;
firstTimer = false;
} else {
x1 = (random.nextInt(750) + 1);
y1 = y;
rectangle = new Rectangle2D.Double(x1, y1, 50, 50);
circle = new Ellipse2D.Double(x1 + 25, (y1 + 65), 25, 25);
rectangle2 = new Rectangle2D.Double(x1 + 65, y1 - 25, 150, 75);
circle2 = new Ellipse2D.Double(x1 + 140, (y1 + 65), 25, 25);
circle3 = new Ellipse2D.Double(x1 + 175, (y1 + 65), 25, 25);
n--;
}
}
repaint();
}
}
and here is where I call the TruckMaker
public class TruckMain {
private TruckMaker truck;
private TruckMain truckmain;
private final static int FRAME_WIDTH = 750;
private final static int FRAME_HEIGHT = 750;
public final static JButton startButton = new JButton("Start");
private final static BorderLayout border = new BorderLayout();
public final static JLabel x = new JLabel("x: ");
public final static JLabel y = new JLabel("y: ");
public final static JLabel n = new JLabel("n: ");
private static JPanel controlPanel = new JPanel();
private static JTextField textField1 = new JTextField(5);
private static JTextField textField2 = new JTextField(5);
private static JTextField textField3 = new JTextField(5);
public static void main(String[] args){
TruckMaker truck = new TruckMaker();
TruckMain truckMain = new TruckMain();
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.add(truck);
frame.setLayout(border);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
controlPanel.add(x);
controlPanel.add(textField1);
controlPanel.add(y);
controlPanel.add(textField2);
controlPanel.add(n);
controlPanel.add(textField3);
controlPanel.add(startButton);
startButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
int x1 = Integer.parseInt(textField1.getText());
int y1 = Integer.parseInt(textField2.getText());
int n1 = Integer.parseInt(textField3.getText());
truck.getTrucks(x1,y1,n1);
}
});
frame.add(controlPanel,BorderLayout.SOUTH);
}
}
You repaint method seems to work fine; the problem is in your main method and how you construct your frame. It seems like your TruckMaker component is not visible at all, so repaint has nothing to do. Maybe this is just a mistake in your posted code, since I can not even see your controls panel, but instead of adding the components directly to frame, you have to add them to the frame's contentPane:
frame.getContentPane().add(truck, BorderLayout.CENTER);
frame.getContentPane().add(controlPanel,BorderLayout.SOUTH);
After this fix, both the control panel and the TruckMaker component are visible and the paintComponent method is being called.
There's also an (unrelated) issue with the types of circle, circle2, etc. I guess this should be
public static Ellipse2D.Double circle, circle2, circle3;
I want to create a program that can use mouse to move picture around the program here is my code. My code is set position of shape with tempX and tempY that I set it to get position of mouse while draging when drag mouse a picture will move along mouse.
* I can't make this picture repaint while draging mouse anything I miss?
* Add chagnePositionVectors()
public class SiaemsiMouse extends JPanel implements MouseListener,MouseMotionListener {
int tempX = 330;
int tempY = 95;
// position of Siaemsi box
int posX[] = {tempX-30,tempX-30,tempX-30};
int posY[] = {tempY+305,tempY+80,tempY+55};
// position of Siaemsi stick
int posXS1[] = {tempX,tempX,tempX-3,tempX+8,tempX+20,tempX+17};
int posXS2[] = {tempX+20,tempX+20,tempX+17,tempX+28,tempX+40,tempX+37};
int posXS3[] = {tempX+40,tempX+40,tempX+37,tempX+48,tempX+60,tempX+57};
int posXS4[] = {tempX+60,tempX+60,tempX+57,tempX+68,tempX+80,tempX+77};
int posXS5[] = {tempX+80,tempX+80,tempX+77,tempX+88,tempX+100,tempX+97};
int posXS6[] = {tempX+100,tempX+100,tempX+97,tempX+108,tempX+120,tempX+117};
int posXS7[] = {tempX+120,tempX+120,tempX+117,tempX+128,tempX+140,tempX+137};
// All of y for stick are equals
int posYS1[] = {tempY,tempY,tempY-10,tempY-15,tempY-10,tempY};
public SiaemsiMouse(){
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) {
SiaemsiMouse siaemsimouse = new SiaemsiMouse();
JFrame frame = new JFrame();
frame.add(siaemsimouse);
frame.setSize(800,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
Graphics2D g2 = (Graphics2D) graphics;
Random random = new Random();
// Draw Siaemsi
Ellipse2D.Double floor = new Ellipse2D.Double(posX[0],posY[0],200,50);
Rectangle2D.Double body = new Rectangle2D.Double(posX[1],posY[1],200,250);
Ellipse2D.Double top = new Ellipse2D.Double(posX[2],posY[2],200,50);
g2.setPaint(Color.RED);
g2.fill(floor);
g2.fill(body);
g2.setPaint(Color.BLACK);
g2.fill(top);
// Draw siaemsi's stick
Rectangle2D.Double stick1 = new Rectangle2D.Double(posXS1[0],posYS1[0],18,100);
GeneralPath path1 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS1.length);
path1.moveTo(posXS1[1],posYS1[1]);
for (int i = 2; i < posXS1.length; i++) {
path1.lineTo(posXS1[i],posYS1[i]);
}
path1.closePath();
Rectangle2D.Double stick2 = new Rectangle2D.Double(posXS2[0],posYS1[0],18,100);
GeneralPath path2 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS2.length);
path2.moveTo(posXS2[1],posYS1[1]);
for (int i = 2; i < posXS2.length; i++) {
path2.lineTo(posXS2[i],posYS1[i]);
}
path2.closePath();
Rectangle2D.Double stick3 = new Rectangle2D.Double(posXS3[0],posYS1[0],18,100);
GeneralPath path3 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS3.length);
path3.moveTo(posXS3[1],posYS1[1]);
for (int i = 2; i < posXS3.length; i++) {
path3.lineTo(posXS3[i],posYS1[i]);
}
path3.closePath();
Rectangle2D.Double stick4 = new Rectangle2D.Double(posXS4[0],posYS1[0],18,100);
GeneralPath path4 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS4.length);
path4.moveTo(posXS4[1],posYS1[1]);
for (int i = 2; i < posXS4.length; i++) {
path4.lineTo(posXS4[i],posYS1[i]);
}
path4.closePath();
Rectangle2D.Double stick5 = new Rectangle2D.Double(posXS5[0],posYS1[0],18,100);
GeneralPath path5 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS5.length);
path5.moveTo(posXS5[1],posYS1[1]);
for (int i = 2; i < posXS5.length; i++) {
path5.lineTo(posXS5[i],posYS1[i]);
}
path5.closePath();
Rectangle2D.Double stick6 = new Rectangle2D.Double(posXS6[0],posYS1[0],18,100);
GeneralPath path6 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS6.length);
path6.moveTo(posXS6[1],posYS1[1]);
for (int i = 2; i < posXS6.length; i++) {
path6.lineTo(posXS6[i],posYS1[i]);
}
path6.closePath();
Rectangle2D.Double stick7 = new Rectangle2D.Double(posXS7[0],posYS1[0],18,100);
GeneralPath path7 = new GeneralPath(GeneralPath.WIND_EVEN_ODD,posXS7.length);
path7.moveTo(posXS7[1],posYS1[1]);
for (int i = 2; i < posXS7.length; i++) {
path7.lineTo(posXS7[i],posYS1[i]);
}
path7.closePath();
g2.setPaint(new Color(153,153,0));
g2.fill(stick1);
g2.fill(path1);
g2.setPaint(Color.BLACK);
g2.draw(stick1);
g2.draw(path1);
g2.setPaint(new Color(153, 76, 0));
g2.fill(stick2);
g2.fill(path2);
g2.setPaint(Color.BLACK);
g2.draw(stick2);
g2.draw(path2);
g2.setPaint(new Color(255, 255, 0));
g2.fill(stick3);
g2.fill(path3);
g2.setPaint(Color.BLACK);
g2.draw(stick3);
g2.draw(path3);
g2.setPaint(new Color(0, 255, 128));
g2.fill(stick4);
g2.fill(path4);
g2.setPaint(Color.BLACK);
g2.draw(stick4);
g2.draw(path4);
g2.setPaint(new Color(102, 0, 56));
g2.fill(stick5);
g2.fill(path5);
g2.setPaint(Color.BLACK);
g2.draw(stick5);
g2.draw(path5);
g2.setPaint(new Color(255, 0, 127));
g2.fill(stick6);
g2.fill(path6);
g2.setPaint(Color.BLACK);
g2.draw(stick6);
g2.draw(path6);
g2.setPaint(new Color(224, 224, 56));
g2.fill(stick7);
g2.fill(path7);
g2.setPaint(Color.BLACK);
g2.draw(stick7);
g2.draw(path7);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
changePositionVectors(e.getX(),e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
public void changePositionVectors(int xPos, int yPos){
tempX = xPos;
tempY = yPos;
repaint();
}
}
Try this, here based on #HovercraftFullOfEels's comment I have separated moving from the paintComponent()...
EDIT 1:
Added floor, body and top objects. Throws null pointer exception on O/P screen but works
EDIT 2:
Still shows NPE, Fixed: Image(a cake) was not moving as posX,posY,... arrays were not updated
class SiaemsiMouse extends JPanel implements MouseListener, MouseMotionListener {
private int tempX = 330;
private int tempY = 95;
// position of Siaemsi box
private int posX[] = {tempX - 30, tempX - 30, tempX - 30};
private int posY[] = {tempY + 305, tempY + 80, tempY + 55};
// position of Siaemsi stick
private int posXS1[] = {tempX, tempX, tempX - 3, tempX + 8, tempX + 20, tempX + 17};
private int posXS2[] = {tempX + 20, tempX + 20, tempX + 17, tempX + 28, tempX + 40, tempX + 37};
private int posXS3[] = {tempX + 40, tempX + 40, tempX + 37, tempX + 48, tempX + 60, tempX + 57};
private int posXS4[] = {tempX + 60, tempX + 60, tempX + 57, tempX + 68, tempX + 80, tempX + 77};
private int posXS5[] = {tempX + 80, tempX + 80, tempX + 77, tempX + 88, tempX + 100, tempX + 97};
private int posXS6[] = {tempX + 100, tempX + 100, tempX + 97, tempX + 108, tempX + 120, tempX + 117};
private int posXS7[] = {tempX + 120, tempX + 120, tempX + 117, tempX + 128, tempX + 140, tempX + 137};
// All of y for stick are equals
private int posYS1[] = {tempY, tempY, tempY - 10, tempY - 15, tempY - 10, tempY};
public SiaemsiMouse() {
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) throws InterruptedException {
SiaemsiMouse siaemsimouse = new SiaemsiMouse();
JFrame frame = new JFrame();
frame.add(siaemsimouse);
frame.setSize(800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//added objects here
private Rectangle2D.Double stick1, stick2, stick3, stick4, stick5, stick6, stick7;
private GeneralPath path1, path2, path3, path4, path5, path6, path7;
//added more objects
private Ellipse2D.Double floor;
private Rectangle2D.Double body;
private Ellipse2D.Double top;
#Override
public void paintComponent(Graphics graphics) {
Graphics2D g2 = (Graphics2D) graphics;
super.paintComponent(graphics); //If you use paintComponents() the previous image persists
//Random random = new Random(); //No use for Random??
// Draw Siaemsi
g2.setPaint(Color.RED);
g2.fill(floor);
g2.fill(body);
g2.setPaint(Color.BLACK);
g2.fill(top);
g2.setPaint(new Color(153, 153, 0));
g2.fill(stick1);
g2.fill(path1);
g2.setPaint(Color.BLACK);
g2.draw(stick1);
g2.draw(path1);
g2.setPaint(new Color(153, 76, 0));
g2.fill(stick2);
g2.fill(path2);
g2.setPaint(Color.BLACK);
g2.draw(stick2);
g2.draw(path2);
g2.setPaint(new Color(255, 255, 0));
g2.fill(stick3);
g2.fill(path3);
g2.setPaint(Color.BLACK);
g2.draw(stick3);
g2.draw(path3);
g2.setPaint(new Color(0, 255, 128));
g2.fill(stick4);
g2.fill(path4);
g2.setPaint(Color.BLACK);
g2.draw(stick4);
g2.draw(path4);
g2.setPaint(new Color(102, 0, 56));
g2.fill(stick5);
g2.fill(path5);
g2.setPaint(Color.BLACK);
g2.draw(stick5);
g2.draw(path5);
g2.setPaint(new Color(255, 0, 127));
g2.fill(stick6);
g2.fill(path6);
g2.setPaint(Color.BLACK);
g2.draw(stick6);
g2.draw(path6);
g2.setPaint(new Color(224, 224, 56));
g2.fill(stick7);
g2.fill(path7);
g2.setPaint(Color.BLACK);
g2.draw(stick7);
g2.draw(path7);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
changePositionVectors(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
#SuppressWarnings("empty-statement")
public void changePositionVectors(int xPos, int yPos) {
tempX = xPos;
tempY = yPos;
//calc pos...
posX = new int[]{tempX - 30, tempX - 30, tempX - 30};
posY = new int[]{tempY + 305, tempY + 80, tempY + 55};
// position of Siaemsi stick
posXS1 = new int[]{tempX, tempX, tempX - 3, tempX + 8, tempX + 20, tempX + 17};
posXS2 = new int[]{tempX + 20, tempX + 20, tempX + 17, tempX + 28, tempX + 40, tempX + 37};
posXS3 = new int[]{tempX + 40, tempX + 40, tempX + 37, tempX + 48, tempX + 60, tempX + 57};
posXS4 = new int[]{tempX + 60, tempX + 60, tempX + 57, tempX + 68, tempX + 80, tempX + 77};
posXS5 = new int[]{tempX + 80, tempX + 80, tempX + 77, tempX + 88, tempX + 100, tempX + 97};
posXS6 = new int[]{tempX + 100, tempX + 100, tempX + 97, tempX + 108, tempX + 120, tempX + 117};
posXS7 = new int[]{tempX + 120, tempX + 120, tempX + 117, tempX + 128, tempX + 140, tempX + 137};
// All of y for stick are equals
posYS1 = new int[]{tempY, tempY, tempY - 10, tempY - 15, tempY - 10, tempY};
floor = new Ellipse2D.Double(posX[0], posY[0], 200, 50);
body = new Rectangle2D.Double(posX[1], posY[1], 200, 250);
top = new Ellipse2D.Double(posX[2], posY[2], 200, 50);
// Draw siaemsi's stick
stick1 = new Rectangle2D.Double(posXS1[0], posYS1[0], 18, 100);
path1 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS1.length);
path1.moveTo(posXS1[1], posYS1[1]);
for (int i = 2; i < posXS1.length; i++) {
path1.lineTo(posXS1[i], posYS1[i]);
}
path1.closePath();
stick2 = new Rectangle2D.Double(posXS2[0], posYS1[0], 18, 100);
path2 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS2.length);
path2.moveTo(posXS2[1], posYS1[1]);
for (int i = 2; i < posXS2.length; i++) {
path2.lineTo(posXS2[i], posYS1[i]);
}
path2.closePath();
stick3 = new Rectangle2D.Double(posXS3[0], posYS1[0], 18, 100);
path3 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS3.length);
path3.moveTo(posXS3[1], posYS1[1]);
for (int i = 2; i < posXS3.length; i++) {
path3.lineTo(posXS3[i], posYS1[i]);
}
path3.closePath();
stick4 = new Rectangle2D.Double(posXS4[0], posYS1[0], 18, 100);
path4 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS4.length);
path4.moveTo(posXS4[1], posYS1[1]);
for (int i = 2; i < posXS4.length; i++) {
path4.lineTo(posXS4[i], posYS1[i]);
}
path4.closePath();
stick5 = new Rectangle2D.Double(posXS5[0], posYS1[0], 18, 100);
path5 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS5.length);
path5.moveTo(posXS5[1], posYS1[1]);
for (int i = 2; i < posXS5.length; i++) {
path5.lineTo(posXS5[i], posYS1[i]);
}
path5.closePath();
stick6 = new Rectangle2D.Double(posXS6[0], posYS1[0], 18, 100);
path6 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS6.length);
path6.moveTo(posXS6[1], posYS1[1]);
for (int i = 2; i < posXS6.length; i++) {
path6.lineTo(posXS6[i], posYS1[i]);
}
path6.closePath();
stick7 = new Rectangle2D.Double(posXS7[0], posYS1[0], 18, 100);
path7 = new GeneralPath(GeneralPath.WIND_EVEN_ODD, posXS7.length);
path7.moveTo(posXS7[1], posYS1[1]);
for (int i = 2; i < posXS7.length; i++) {
path7.lineTo(posXS7[i], posYS1[i]);
}
path7.closePath();
repaint();
}
}
I see what I think is your problem.
You are assuming that if you change tempX and tempY that all variables that are derived from them will change as well,
but this is not so. Any variables created with tempX or tempY will not magically know to change once they have been created.
You need to change any variables that need to be changed yourself, and the easiest way to do this is to create a method that takes your tempX and tempY values and re-calculates all the other fields that need to be recalculated.
Consider creating and moving your Shape and path objects outside of paintComponent, perhaps in the Mouse adapter code and simply painting the Shape in paintComponent.
i.e.,
public void changePositionVectors(int xPos, int yPos) {
// set the fields that need to be set with x and y
repaint();
}
Edit
Regarding your new code:
public void changePositionVectors(int xPos, int yPos){
tempX = xPos;
tempY = yPos;
repaint();
}
This fixes nothing since all this does is set's tempX and tempY, and again, changing these values will not magically change any value that was originally created with these fields. Again, your changePositionVectors method must contain more code that in fact sets the values of all the vectors needed for drawing your GUI.
Edit I would take a completely different tack from what you and boxed are doing. I would:
Draw everything to a BufferedImage
Place that BufferedImage into an ImageIcon
Place that ImageIcon into a JLabel
Place that JLabel into a JLayeredPane
Add a MouseListener and MouseMotionListener to the JLabel.
Done.
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleDrawing {
private static final int PREF_W = 780;
private static final int PREF_H = 570;
private static final int GAP = 1;
private static final int BI_WIDTH = 200 + 2 * GAP;
private static final int BI_HEIGHT = 300 + 2 * GAP;
private static final int ELLIPSE_WIDTH = BI_WIDTH - 2 * GAP;
private static final int ELLIPSE_HEIGHT = 50;
private static final Color CAN_COLOR = Color.red;
private JLayeredPane layeredPane = new JLayeredPane() {
public Dimension getPreferredSize() {
return SimpleDrawing.this.getPreferredSize();
};
};
private JLabel imageLabel;
private Point imageLabelPoint = new Point();
public SimpleDrawing() {
layeredPane.setOpaque(true);
layeredPane.setBackground(Color.white);
imageLabel = drawImageLabel();
imageLabel.setLocation(imageLabelPoint);
imageLabel.setSize(imageLabel.getPreferredSize());
layeredPane.add(imageLabel, JLayeredPane.DEFAULT_LAYER);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
imageLabel.addMouseListener(myMouseAdapter);
imageLabel.addMouseMotionListener(myMouseAdapter);
}
private JLabel drawImageLabel() {
BufferedImage img = new BufferedImage(BI_WIDTH, BI_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(CAN_COLOR);
int x = GAP;
int y = BI_HEIGHT - ELLIPSE_HEIGHT - GAP;
int width = ELLIPSE_WIDTH;
int height = ELLIPSE_HEIGHT;
g2.fillOval(x, y, width, height);
y = GAP + ELLIPSE_HEIGHT / 2;
width = ELLIPSE_WIDTH;
height = BI_HEIGHT - ELLIPSE_HEIGHT / 2 - GAP - y;
g2.fillRect(x, y, width, height);
g2.setColor(Color.black);
y = GAP;
height = ELLIPSE_HEIGHT;
g2.fillOval(x, y, width, height);
g2.dispose();
ImageIcon icon = new ImageIcon(img);
return new JLabel(icon);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public JLayeredPane getLayeredPane() {
return layeredPane;
}
private class MyMouseAdapter extends MouseAdapter {
private boolean dragging = false;
private Point srcLoc;
private Point msePressLoc;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
dragging = true;
srcLoc = ((Component) e.getSource()).getLocation();
msePressLoc = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
dragging = false;
moveTo(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (!dragging) {
return;
}
moveTo(e);
}
private void moveTo(MouseEvent e) {
Point loc = e.getLocationOnScreen();
Component comp = (Component) e.getSource();
int x = loc.x - msePressLoc.x + srcLoc.x;
int y = loc.y - msePressLoc.y + srcLoc.y;
comp.setLocation(x, y);
layeredPane.repaint();
}
}
private static void createAndShowGui() {
SimpleDrawing simpleDrawing = new SimpleDrawing();
JFrame frame = new JFrame("Simple Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(simpleDrawing.getLayeredPane());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}