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();
}
});
}
}
Related
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);
}
}
I'm trying to make is so that multiple squares appear on the level screen. For some reason the only square it renders will be the last one in the order I type it in. Been at it for 2 hours and is extremely annoying. Any help would be awesome and greatly appreciated.
public class Level1 extends JFrame implements ActionListener, KeyListener {
LevelRender render;
static Square square;
static Player player;
static Square squares;
public static Timer timer;
boolean fail, Over, Reset = false, create = false;
static int enemyCount = 5;
static int eX = 200, eY, z;
ArrayList <Enemys> squareList = new ArrayList();
public static Level1 level;
ImageIcon Level1 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Level1.png");
public Level1(Player player){
timer = new Timer(50,this);
render = new LevelRender();
setVisible(true);
setSize(1000,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(render);
addKeyListener(this);
this.player = player;
timer.start();
player.x = 0;
player.y = 387;
}
public void render(Graphics2D g){
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if(!fail){
Level1.paintIcon(MainMenu.level1, g, -4, -25);
player.GameCount = 1;
player.render(g);
square = new Square(50,397);
squares = new Square(200,397);
square.render(g);
squares.render(g);
reset();
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", 1, 30));
g.drawString(String.valueOf("Health:"), 40, 80);
//lots of other string
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", 1, 15));
g.drawString(String.valueOf("Level:"), 900, 20);
g.drawString(String.valueOf("1"), 950, 20);
}
if(fail){
g.setColor(Color.black);
g.fillRect(0, 0, 1200, 500);
g.setColor(Color.red);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("You Have Failed"), 200, 150);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("Press ENTER to Continue"), 120, 220);
}
if(enemyCount == 0){
g.setColor(Color.black);
g.fillRect(0, 0, 1200, 500);
g.setColor(Color.green);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("You Won"), 200, 150);
g.setFont(new Font("Arial", 1, 50));
g.drawString(String.valueOf("Press ENTER to Continue"), 120, 220);
}
}
public void createEnemys(){
for(int i = 0; i < 5; i++){
eX += 50;
//squares = new Enemys(player, eX, 397);
squareList.add(squares);
create = true;
}
}
public void update(){
player.update();
if(!create){
createEnemys();
}
if(Player.health <= 0){
fail = true;
Over = true;
Player.health = 10;
}
if(enemyCount == 0){
fail = false;
Over = true;
}
System.out.println(Enemys.health + " , " + enemyCount + " , " + squareList.get(3).x );
}
public void reset(){
if(Reset){
enemyCount = 5;
Reset = false;
create = false;
}
}
#Override
public void actionPerformed(ActionEvent e) {
update();
render.repaint();
}
}
...................
public class Enemys {
public static int health, damage,x,y;
static boolean hit;
static int count;
public Enemys(int x, int y){
this.x = x;
this.y = y;
}
public void hit(){
if(Player.x == x)
{
Player.health -= damage;
}
}
public void update(){
hit();
}
public void hello(){
System.out.println("Hello");
}
public void render(Graphics g){}
}
.......................
public class Square extends Enemys {
static int count;
static boolean hit;
public Square(int x, int y){
super(x,y);
damage = 1;
health = 30;
}
public void render(Graphics g){
g.setColor(Color.red);
g.fillRect(x, y, 50, 50);
g.setColor(Color.green);
g.fillRect(x, y - 20, (50*(health / 30)), 7);
}
public void update(){
x += 1;
}
}
........................
public class LevelRender extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
MainMenu.level1.render((Graphics2D)g);
}
}
...................
I am working on a 2D game as a learning project and I have hit a bump. I cannot figure out how to move a Polygon object using the KeyListener within a JPanel (which is added to a JFrame). I've tried the frog.translate(int x, int y) method, which does not update the location. I've also tried changing the array coordinates manually. A sample of my code is below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Board extends JPanel implements KeyListener {
private Frog frog;
public Board() {
setBackground(Color.GREEN);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
frog = new Frog();
// Frog graphics
g2.setColor(Color.BLACK);
g2.drawPolygon(frog);
g2.setColor(new Color(0,150,15));
g2.fillPolygon(frog);
}
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
int c = ke.getKeyCode();
if(c == KeyEvent.VK_LEFT){
frog.moveFrogLeft(25);
//frog.translate(-25,0);
}
if(c == KeyEvent.VK_RIGHT){
frog.moveFrogRight(25);
//frog.translate(25,0);
}
if(c == KeyEvent.VK_UP){
frog.moveFrogUp(25);
//frog.translate(0,-25);
}
if(c == KeyEvent.VK_DOWN){
frog.moveFrogDown(25);
//frog.translate(0,25);
}
repaint();
}
#Override
public void keyReleased(KeyEvent ke) {
}
}
///////////////////////
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Frog extends Polygon {
private Integer[] xcoord;
private Integer[] ycoord;
public Frog(){
xcoord = new Integer[] {5,10,10,15,15,20,
20,30,30,35,35,40,40,
45,45,40,40,30,30,40,
40,45,45,40,40,35,35,
30,30,20,20,15,15,10,
10,5,5,10,10,20,20,
10,10,5,5};
ycoord = new Integer[] {10,10,5,5,20,20,
10,10,20,20,5,5,10,10,
15,15,25,25,30,30,35,35,
40,40,45,45,35,35,40,40,
35,35,45,45,40,40,35,35,
30,30,25,25,15,15,10};
for(int i = 0; i < xcoord.length; i++){
this.addPoint(xcoord[i],ycoord[i]);
}
}
public void moveFrogLeft(int x) {
if(xcoord[0] - x < 0){
//do nothing
} else {
for(int i = 0; i < xcoord.length; i++){
xcoord[i] = xcoord[i] - x;
}
}
}
public void moveFrogRight(int x){
if(xcoord[0] + x > 600){
//do nothing
} else {
for(int i = 0; i < xcoord.length; i++){
xcoord[i] = xcoord[i] + x;
}
}
}
public void moveFrogUp(int y){
if(ycoord[0] - y < 0){
//do nothing
} else {
for(int i = 0; i < ycoord.length; i++){
ycoord[i] = ycoord[i] - y;
}
}
}
public void moveFrogDown(int y){
if(ycoord[0] + y > 600){
//do nothing
} else {
for(int i = 0; i < ycoord.length; i++){
ycoord[i] = ycoord[i] + y;
}
}
}
}
This code has a simple issue:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
frog = new Frog();// <-- !!!!!
// Frog graphics
g2.setColor(Color.BLACK);
g2.drawPolygon(frog);
g2.setColor(new Color(0,150,15));
g2.fillPolygon(frog);
}
The marked line overwrites the frog with a new instance, every time the frog is painted, thus reseting it to the original point. Apart from the obvious issue that this is the reason for the unexpected behaviour, never do any unnecessary calculations in the paintComponent(...)-method. Any precomputation, Object-generation, etc. should be done outside of paintComponent!!!
First of all, I would strongly discourage you from using KeyListener, it's troublesome at the best, a better choice would be to make use of the Key Bindings API which was desgiend to fix the short commings of the KeyListener API.
Second, you shouldn't be modifying the points of the polygon, the 2D Graphics API is actually capable of some really neat tricks which makes it much easier and faster to change the location (and rotation and scale) of what you are drawing.
Take a look closer look at 2D Graphics for more details.
Instead of changing the points of the polygon, which isn't taking into consideration the viewable bounds, you could simply use an AffineTransform...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point location = frog.getLocation();
AffineTransform at = AffineTransform.getTranslateInstance(location.x, location.y);
g2d.transform(at);
g2d.setColor(new Color(0, 150, 15));
g2d.fill(frog);
g2d.setColor(Color.BLACK);
g2d.draw(frog);
g2d.dispose();
}
This just simply changes the origin point of the Graphics context to the location where you want to paint the polygon (yes, there's another reason why I'm using AffineTransform
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 Board());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected enum VerticalDirection {
NONE, UP, DOWN;
}
protected enum HorizontalDirection {
NONE, LEFT, RIGHT;
}
public static class Board extends JPanel {
protected static final int Y_DELTA = 4;
protected static final int X_DELTA = 4;
private Frog frog;
private VerticalDirection verticalDirection = VerticalDirection.NONE;
private HorizontalDirection horizontalDirection = HorizontalDirection.NONE;
public Board() {
setBackground(Color.GREEN);
frog = new Frog();
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point location = frog.getLocation();
switch (verticalDirection) {
case UP:
location.y -= Y_DELTA;
break;
case DOWN:
location.y += Y_DELTA;
break;
}
switch (horizontalDirection) {
case LEFT:
location.x -= X_DELTA;
break;
case RIGHT:
location.x += X_DELTA;
break;
}
Rectangle bounds = frog.getBounds();
int width = bounds.x + bounds.width;
int height = bounds.y + bounds.height;
if (location.y < 0) {
location.y = 0;
} else if (location.y + height > getHeight()) {
location.y = getHeight() - height;
}
if (location.x < 0) {
location.x = 0;
} else if (location.x + width > getWidth()) {
location.x = getWidth() - width;
}
frog.setLocation(location);
repaint();
}
});
timer.start();
addPressedKeyBinding("up", KeyEvent.VK_UP, new VerticalMovementAction(VerticalDirection.UP));
addPressedKeyBinding("down", KeyEvent.VK_DOWN, new VerticalMovementAction(VerticalDirection.DOWN));
addPressedKeyBinding("left", KeyEvent.VK_LEFT, new HorizontalMovementAction(HorizontalDirection.LEFT));
addPressedKeyBinding("right", KeyEvent.VK_RIGHT, new HorizontalMovementAction(HorizontalDirection.RIGHT));
addReleasedKeyBinding("up", KeyEvent.VK_UP, new VerticalMovementAction(VerticalDirection.NONE));
addReleasedKeyBinding("down", KeyEvent.VK_DOWN, new VerticalMovementAction(VerticalDirection.NONE));
addReleasedKeyBinding("left", KeyEvent.VK_LEFT, new HorizontalMovementAction(HorizontalDirection.NONE));
addReleasedKeyBinding("right", KeyEvent.VK_RIGHT, new HorizontalMovementAction(HorizontalDirection.NONE));
}
protected void addPressedKeyBinding(String name, int virtuaKey, Action action) {
addKeyBinding(name + ".pressed", KeyStroke.getKeyStroke(virtuaKey, 0, false), action);
}
protected void addReleasedKeyBinding(String name, int virtuaKey, Action action) {
addKeyBinding(name + ".released", KeyStroke.getKeyStroke(virtuaKey, 0, true), action);
}
protected void addKeyBinding(String name, KeyStroke ks, Action action) {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(ks, name);
am.put(name, action);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point location = frog.getLocation();
AffineTransform at = AffineTransform.getTranslateInstance(location.x, location.y);
g2d.transform(at);
g2d.setColor(new Color(0, 150, 15));
g2d.fill(frog);
g2d.setColor(Color.BLACK);
g2d.draw(frog);
g2d.dispose();
}
protected class VerticalMovementAction extends AbstractAction {
private VerticalDirection direction;
public VerticalMovementAction(VerticalDirection direction) {
this.direction = direction;
}
#Override
public void actionPerformed(ActionEvent e) {
verticalDirection = direction;
}
}
protected class HorizontalMovementAction extends AbstractAction {
private HorizontalDirection direction;
public HorizontalMovementAction(HorizontalDirection direction) {
this.direction = direction;
}
#Override
public void actionPerformed(ActionEvent e) {
horizontalDirection = direction;
}
}
}
public static class Frog extends Polygon {
private Integer[] xcoord;
private Integer[] ycoord;
private Point location;
public Frog() {
location = new Point(0, 0);
xcoord = new Integer[]{5, 10, 10, 15, 15, 20,
20, 30, 30, 35, 35, 40, 40,
45, 45, 40, 40, 30, 30, 40,
40, 45, 45, 40, 40, 35, 35,
30, 30, 20, 20, 15, 15, 10,
10, 5, 5, 10, 10, 20, 20,
10, 10, 5, 5};
ycoord = new Integer[]{10, 10, 5, 5, 20, 20,
10, 10, 20, 20, 5, 5, 10, 10,
15, 15, 25, 25, 30, 30, 35, 35,
40, 40, 45, 45, 35, 35, 40, 40,
35, 35, 45, 45, 40, 40, 35, 35,
30, 30, 25, 25, 15, 15, 10};
for (int i = 0; i < xcoord.length; i++) {
this.addPoint(xcoord[i], ycoord[i]);
}
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
}
}
Now, you're probably wondering why I would use AffineTransform instead of Graphcis2D#translate, the main reason is, it's easy to apply other transformations, like rotation...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point location = frog.getLocation();
Rectangle bounds = frog.getBounds();
int width = bounds.x + bounds.width;
int height = bounds.y + bounds.height;
AffineTransform at = AffineTransform.getTranslateInstance(location.x, location.y);
at.rotate(Math.toRadians(angle), width / 2, height / 2);
g2d.transform(at);
g2d.setColor(new Color(0, 150, 15));
g2d.fill(frog);
g2d.setColor(Color.BLACK);
g2d.draw(frog);
g2d.dispose();
}
All this does is apply a compound transformation, moving the Graphics context's origin and rotation matrix
And for a complete example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 Board());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected enum VerticalDirection {
NONE, UP, DOWN;
}
protected enum HorizontalDirection {
NONE, LEFT, RIGHT;
}
public static class Board extends JPanel {
protected static final int Y_DELTA = 4;
protected static final int X_DELTA = 4;
private Frog frog;
private VerticalDirection verticalDirection = VerticalDirection.NONE;
private HorizontalDirection horizontalDirection = HorizontalDirection.NONE;
private double angle = 0; // Up...
public Board() {
setBackground(Color.GREEN);
frog = new Frog();
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point location = frog.getLocation();
switch (verticalDirection) {
case UP:
angle = 0;
location.y -= Y_DELTA;
break;
case DOWN:
angle = 180;
location.y += Y_DELTA;
break;
}
switch (horizontalDirection) {
case LEFT:
location.x -= X_DELTA;
angle = 270;
break;
case RIGHT:
location.x += X_DELTA;
angle = 90;
break;
}
Rectangle bounds = frog.getBounds();
int width = bounds.x + bounds.width;
int height = bounds.y + bounds.height;
if (location.y < 0) {
location.y = 0;
} else if (location.y + height > getHeight()) {
location.y = getHeight() - height;
}
if (location.x < 0) {
location.x = 0;
} else if (location.x + width > getWidth()) {
location.x = getWidth() - width;
}
frog.setLocation(location);
repaint();
}
});
timer.start();
addPressedKeyBinding("up", KeyEvent.VK_UP, new VerticalMovementAction(VerticalDirection.UP));
addPressedKeyBinding("down", KeyEvent.VK_DOWN, new VerticalMovementAction(VerticalDirection.DOWN));
addPressedKeyBinding("left", KeyEvent.VK_LEFT, new HorizontalMovementAction(HorizontalDirection.LEFT));
addPressedKeyBinding("right", KeyEvent.VK_RIGHT, new HorizontalMovementAction(HorizontalDirection.RIGHT));
addReleasedKeyBinding("up", KeyEvent.VK_UP, new VerticalMovementAction(VerticalDirection.NONE));
addReleasedKeyBinding("down", KeyEvent.VK_DOWN, new VerticalMovementAction(VerticalDirection.NONE));
addReleasedKeyBinding("left", KeyEvent.VK_LEFT, new HorizontalMovementAction(HorizontalDirection.NONE));
addReleasedKeyBinding("right", KeyEvent.VK_RIGHT, new HorizontalMovementAction(HorizontalDirection.NONE));
}
protected void addPressedKeyBinding(String name, int virtuaKey, Action action) {
addKeyBinding(name + ".pressed", KeyStroke.getKeyStroke(virtuaKey, 0, false), action);
}
protected void addReleasedKeyBinding(String name, int virtuaKey, Action action) {
addKeyBinding(name + ".released", KeyStroke.getKeyStroke(virtuaKey, 0, true), action);
}
protected void addKeyBinding(String name, KeyStroke ks, Action action) {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(ks, name);
am.put(name, action);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point location = frog.getLocation();
Rectangle bounds = frog.getBounds();
int width = bounds.x + bounds.width;
int height = bounds.y + bounds.height;
AffineTransform at = AffineTransform.getTranslateInstance(location.x, location.y);
at.rotate(Math.toRadians(angle), width / 2, height / 2);
g2d.transform(at);
g2d.setColor(new Color(0, 150, 15));
g2d.fill(frog);
g2d.setColor(Color.BLACK);
g2d.draw(frog);
g2d.dispose();
}
protected class VerticalMovementAction extends AbstractAction {
private VerticalDirection direction;
public VerticalMovementAction(VerticalDirection direction) {
this.direction = direction;
}
#Override
public void actionPerformed(ActionEvent e) {
verticalDirection = direction;
}
}
protected class HorizontalMovementAction extends AbstractAction {
private HorizontalDirection direction;
public HorizontalMovementAction(HorizontalDirection direction) {
this.direction = direction;
}
#Override
public void actionPerformed(ActionEvent e) {
horizontalDirection = direction;
}
}
}
public static class Frog extends Polygon {
private Integer[] xcoord;
private Integer[] ycoord;
private Point location;
public Frog() {
location = new Point(0, 0);
xcoord = new Integer[]{5, 10, 10, 15, 15, 20,
20, 30, 30, 35, 35, 40, 40,
45, 45, 40, 40, 30, 30, 40,
40, 45, 45, 40, 40, 35, 35,
30, 30, 20, 20, 15, 15, 10,
10, 5, 5, 10, 10, 20, 20,
10, 10, 5, 5};
ycoord = new Integer[]{10, 10, 5, 5, 20, 20,
10, 10, 20, 20, 5, 5, 10, 10,
15, 15, 25, 25, 30, 30, 35, 35,
40, 40, 45, 45, 35, 35, 40, 40,
35, 35, 45, 45, 40, 40, 35, 35,
30, 30, 25, 25, 15, 15, 10};
// I rest the coordinates back to 0x0 because it's easier to
// deal with when applying a rotation...
for (int index = 0; index < xcoord.length; index++) {
xcoord[index] -= 5;
}
for (int index = 0; index < ycoord.length; index++) {
ycoord[index] -= 5;
}
for (int i = 0; i < xcoord.length; i++) {
this.addPoint(xcoord[i], ycoord[i]);
}
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
}
}
Look ma, no maths!
Don't create a Frog in your paintComponent() method! That is throwing away the existing frog and creating a new one with default position.
You should create all of your Frog instances when you initialize your panel, or possibly in response to a b button click to "create a new frog".
When you click in a box, it should create a circle in that box from the designated coordinate. Unless if its already there then its removed. How do I get currentx and currenty coordinates into the fill oval?
public class Grid extends Applet{
boolean click;
public void init()
{
click = false;
addMouseListener(new MyMouseListener());
}
public void paint(Graphics g)
{
super.paint(g);
g.drawRect(100, 100, 400, 400);
//each box
g.drawRect(100, 100, 100, 100);
g.drawRect(200, 100, 100, 100);
g.drawRect(300, 100, 100, 100);
g.drawRect(400, 100, 100, 100);
//2y
g.drawRect(100, 200, 100, 100);
g.drawRect(200, 200, 100, 100);
g.drawRect(300, 200, 100, 100);
g.drawRect(400, 200, 100, 100);
//3y1x
g.drawRect(100, 300, 100, 100);
g.drawRect(200, 300, 100, 100);
g.drawRect(300, 300, 100, 100);
g.drawRect(400, 300, 100, 100);
//4y1x
g.drawRect(100, 400, 100, 100);
g.drawRect(200, 400, 100, 100);
g.drawRect(300, 400, 100, 100);
g.drawRect(400, 400, 100, 100);
if (click)
{
g.fillOval(currentx, currenty, 100, 100); // problem HERE
}
}
private class MyMouseListener implements MouseListener
{
public void mouseClicked(MouseEvent e)
{
int nowx = e.getX();
int nowy = e.getY();
nowx = nowx / 100;
String stringx = Integer.toString(nowx);
stringx = stringx+"00";
int currentx = Integer.parseInt(stringx);
nowy = nowy /100;
String stringy = Integer.toString(nowy);
stringy = stringy+"00";
int currenty = Integer.parseInt(stringy);
click = true;
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}
Your main problem is, painting in Swing/AWT is destructive, that is, each time your paint method is called, you are expected to repaint the current state of the component.
In that case, what you really need is some way to model the state of the game so when paint is called, you can repaint it in some meaningful way. This a basic concept of a Model-View-Controller paradigm, where you separate the responsibility of the program into separate layers.
The problem then becomes, how do you translate from the view to model?
The basic idea is take the current x/y coordinates of the mouse and divide it by the cell size. You also need to ensure that the results are within the expected ranges, as you could get a result which is beyond the columns/rows of grids
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 static class TestPane extends JPanel {
protected static final int CELL_COUNT = 3;
private int[][] board;
private int[] cell;
private boolean isX = true;
public TestPane() {
board = new int[CELL_COUNT][CELL_COUNT];
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int[] cell = getCellAt(e.getPoint());
if (board[cell[0]][cell[1]] == 0) {
board[cell[0]][cell[1]] = isX ? 1 : 2;
isX = !isX;
repaint();
}
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
cell = getCellAt(e.getPoint());
repaint();
}
});
}
protected int[] getCellAt(Point p) {
Point offset = getOffset();
int cellSize = getCellSize();
int x = p.x - offset.x;
int y = p.y - offset.y;
int gridx = Math.min(Math.max(0, x / cellSize), CELL_COUNT - 1);
int gridy = Math.min(Math.max(0, y / cellSize), CELL_COUNT - 1);
return new int[]{gridx, gridy};
}
protected Point getOffset() {
int cellSize = getCellSize();
int x = (getWidth() - (cellSize * CELL_COUNT)) / 2;
int y = (getHeight() - (cellSize * CELL_COUNT)) / 2;
return new Point(x, y);
}
protected int getCellSize() {
return Math.min(getWidth() / CELL_COUNT, getHeight() / CELL_COUNT) - 10;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point offset = getOffset();
int cellSize = getCellSize();
if (cell != null) {
g2d.setColor(new Color(0, 0, 255, 128));
g2d.fillRect(
offset.x + (cellSize * cell[0]),
offset.y + (cellSize * cell[1]),
cellSize,
cellSize);
}
g2d.setColor(Color.BLACK);
FontMetrics fm = g2d.getFontMetrics();
for (int col = 0; col < CELL_COUNT; col++) {
for (int row = 0; row < CELL_COUNT; row++) {
int value = board[col][row];
int x = offset.x + (cellSize * col);
int y = offset.y + (cellSize * row);
String text = "";
switch (value) {
case 1:
text = "X";
break;
case 2:
text = "O";
break;
}
x = x + ((cellSize - fm.stringWidth(text)) / 2);
y = y + ((cellSize - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(text, x, y);
}
}
int x = offset.x;
int y = offset.y;
for (int col = 1; col < CELL_COUNT; col++) {
x = offset.x + (col * cellSize);
g2d.drawLine(x, y, x, y + (cellSize * CELL_COUNT));
}
x = offset.x;
for (int row = 1; row < CELL_COUNT; row++) {
y = offset.x + (row * cellSize);
g2d.drawLine(x, y, x + (cellSize * CELL_COUNT), y);
}
g2d.dispose();
}
}
}
First off, if you want to truncate a number to the nearest 100, e.g. 142 becomes 100, all you have to do is:
num = (num/100)*100;
this is because when you divide 2 integers it automatically truncates it, and you can just multiply it back to get the number. And what I think you want in this case is to create some field variables and some accessor methods. At the top of your MouseListener class, you will need to add:
private int mouseX=0;
private int mouseY=0;
then to be able to access these variables from outside of the mouselistener class you will need to add accessor methods:
public int getMouseX(){
return mouseX;
}
in your Grid Class, you can add the field:
private MyMouseListener listener;
and then initialize it in your init by doing:
listener = new MyMouseListener();
addMouseListener(listener);
then you can do the same for mouseY, and finally from your paint method you can then call:
int mouseX = listener.getMouseX();
int mouseY = listener.getMouseY();
and from there it is as simple as doing if statements or switch statements to find which box you clicked in!
I'm trying to make a simulation on our school's enrollment system. But I'm stuck on a problem that i can't figure out why, the box that i rendered are blinking. I need it not to. can you help me? thanks.
import java.awt.Color;
import java.awt.*;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates and open the template
* in the editor.
*/
/**
*
* #author paolo
*/
public class simulator extends JPanel {
Thread tr;
Image i;
Graphics gbfr;
Dimension size;
int num = 0, check, wid, hyt, oq;
Random rand = new Random();
Dimension locs[];
list waiting, queue;
boolean allowMove = false;
simulator(int w, int h) {
oq = 0;
wid = w;
hyt = h;
tr = new tr1();
locs = new Dimension[30];
waiting = new list(50);
queue = new list(30);
int tw, u;
for (u = 0, tw = 64; u < 10; u++, tw += 55) {
locs[u] = new Dimension(tw, 275);
locs[19 - u] = new Dimension(tw, 325);
locs[u + 20] = new Dimension(tw, 375);
}
}
public void paint(Graphics g) {
i = createImage(getWidth(), getHeight());
gbfr = i.getGraphics();
gbfr.setColor(getBackground());
gbfr.fillRect(0, 0, getWidth(), getHeight());
gbfr.setColor(getForeground());
paintComponent(gbfr);
g.drawImage(i, 0, 0, this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
drawSettings(g);
drawStudents(g);
}
protected void drawSettings(Graphics g) {
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
}
protected void drawStudents(Graphics g) {
waiting.drawStudents(g);
}
public class tr1 extends Thread implements Runnable {
public void run() {
for (check = 0;; check++) {
num++;
try {
if (num % 100 == 0 && waiting.max != waiting.countL) {
waiting.add();
}
repaint();
Thread.sleep(1);
} catch (InterruptedException e) {
}
//repaint();
}
}
}
public class list {
int max, countL;
students temp, head;
list() {
head = new students();
countL = 0;
head.setNext(null);
max = 0;
}
list(int m) {
countL = 0;
head = new students(1);
list();
max = m;
head.setNext(null);
}
void add() {
students t;
t = head;
if (countL == 0) {
countL++;
t.setNext(new students());
} else {
temp = head.getNext();
while (temp != null) {
temp = temp.getNext();
}
countL++;
head.setNext(new students());
//updateCount();
}
}
void delete(int c) {
students t = head, t1;
int aa = 1;
if (countL == 1) {
if (c == 1) {
t.setNext(null);
}
} else {
if (c == 1) {
t.setNext(t.getNext());
} else {
for (t = t.getNext(); aa < c; aa++, t = t.getNext()) {
}
t.setNext(t.getNext().getNext());
}
}
}
void updateCount() {
students t = new students();
t = head;
t = t.getNext();
System.out.println(countL + "__");
for (int q = 1; q < countL; q++) {
System.out.println(t);
t.setCount(q);
t = t.getNext();
}
}
void drawStudents(Graphics g) {
students t = head;
if (countL != 0) {
t = t.getNext();
while (t != null) {
g.setColor(t.getClr());
g.fillRect(t.xpos, t.ypos, 10, 10);
t = t.getNext();
}
}
}
}
public class students {
int xpos, ypos, year, level, servtime, waittime, pos, destx, desty, count;
Color clr;
boolean active, onq;
students next;
students() {
//System.out.print("Recieved");
xpos = rand.nextInt((wid - 580) + 1) + 580;
onq = false;
ypos = rand.nextInt((hyt - 280) + 1) + 280;
waittime = rand.nextInt((100 - 50) + 1) + 50;
servtime = rand.nextInt((200 - 100) + 1) + 100;
count = 0;
level = 0;
next = null;
year = rand.nextInt((4 - 1) + 1) + 1;
clr = new Color(12, 12, 12);
if (year == 1) {
clr = Color.GREEN;
} else if (year == 2) {
clr = Color.YELLOW;
} else if (year == 3) {
clr = Color.RED;
} else {
clr = Color.BLUE;
}
pos = 0;
active = false;
}
students(int i) {
count = 0;
}
void setxpos(int x) {
xpos = x;
}
void setypos(int y) {
ypos = y;
}
void setpos(int p) {
pos = p;
}
void setCount(int q) {
count = q;
}
students getNext() {
return next;
}
Color getClr() {
return clr;
}
void setNext(students n) {
next = n;
}
int getpos() {
return pos;
}
boolean isActive() {
return active;
}
void activate() {
active = true;
}
}
}
Don't override the simulator JPanel's paint(Graphics g) method
Don't call paintComponent directly. You mess with all of Swing's graphics by doing these two things.
Draw your stable background image to a BufferedImage, and then draw the image in your JPanel's paintComponent(Graphics g) method.
Note that your code does not reproduce your problem for me. I don't see any blinking. Should there be some animation going on that we're not seeing?
e.g.,
// class names should begin with an upper-case letter
public class Simulator extends JPanel {
// ....
private BufferedImage settings = null;
Simulator(int w, int h) {
// ....
settings = createSettings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(wid, hyt);
}
// public void paint(Graphics g) {
// i = createImage(getWidth(), getHeight());
// gbfr = i.getGraphics();
// gbfr.setColor(getBackground());
// gbfr.fillRect(0, 0, getWidth(), getHeight());
//
// gbfr.setColor(getForeground());
// paintComponent(gbfr);
//
// g.drawImage(i, 0, 0, this);
// }
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
if (settings != null) {
g.drawImage(settings, 0, 0, this);
}
// !! drawSettings(g);
drawStudents(g);
}
private BufferedImage createSettings() {
int width = 700;
int height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
g.dispose();
return img;
}
// ...
}