Related
Is there a way to display an item in the middle of the chart?
Using the chart to output values from the database.
I'd like to place the next item in the center of each pie.
Is there a way? Below is the code.
public class DrawingPiePanel extends JPanel {
public DrawingPiePanel() {
}
private static final long serialVersionUID = 1L;
Admin ad = Login.ad;
String month = ad.year1 + "-01";
kiosk_dao dao = new kiosk_dao();
int Kor = dao.SelectSaleMonthRestaurant(month, "한식");
int Ch = dao.SelectSaleMonthRestaurant(month, "중식");
int Jp = dao.SelectSaleMonthRestaurant(month, "일식");
int We = dao.SelectSaleMonthRestaurant(month, "양식");
public void paint(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
int Total = Kor + Ch + Jp + We;
if (Total != 0) {
int arc1 = (int) 360.0 * Kor / Total;
int arc2 = (int) 360.0 * Ch / Total;
int arc3 = (int) 360.0 * Jp / Total;
int arc4 = 360 - (arc1 + arc2 + arc3);
double KorPer = (double) Kor / (double) Total * 100;
double ChPer = (double) Ch / (double) Total * 100;
double JpPer = (double) Jp / (double) Total * 100;
double WePer = (double) We / (double) Total * 100;
g.setColor(Color.YELLOW);
g.fillArc(50, 20, 200, 200, 0, arc1);
g.setColor(Color.RED);
g.fillArc(50, 20, 200, 200, arc1, arc2);
g.setColor(Color.BLUE);
g.fillArc(50, 20, 200, 200, arc1 + arc2, arc3);
g.setColor(Color.GREEN);
g.fillArc(50, 20, 200, 200, arc1 + arc2 + arc3, arc4);
g.setColor(Color.BLACK);
g.setFont(new Font("굴림체", Font.PLAIN, 12));
g.drawString(" 한식: 노랑" + String.format("%.2f", KorPer) + "%", 300, 150);
g.drawString(" 중식: 빨강" + String.format("%.2f", ChPer) + "%", 300, 170);
g.drawString(" 일식: 파랑" + String.format("%.2f", JpPer) + "%", 300, 190);
g.drawString(" 양식: 초록" + String.format("%.2f", WePer) + "%", 300, 210);
g.drawString(" 총매출액: " + Total + " 원", 300, 230);
}
}
}
I tried to use a Shape to draw the arcs and an Area to calculate the center of the filled arc.
It does a reasonable job, but not perfect:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.*;
public class DrawPie extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawArc(g2d, Color.YELLOW, 0, 70, "Y");
drawArc(g2d, Color.RED, 70, 80, "R");
drawArc(g2d, Color.BLUE, 150, 90, "B");
drawArc(g2d, Color.GREEN, 240, 120, "G");
g2d.dispose();
}
private void drawArc(Graphics2D g2d, Color color, int start, int extent, String text)
{
g2d.setColor( color );
Shape shape = new Arc2D.Double(50, 50, 200, 200, start, extent, Arc2D.PIE);
g2d.fill( shape );
Rectangle bounds = new Area(shape).getBounds();
System.out.println(bounds);
int centerX = bounds.x + (bounds.width / 2) - 5;
int centerY = bounds.y + (bounds.height / 2) + 7;
g2d.setColor( Color.BLACK );
g2d.drawString(text, centerX, centerY);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(300, 300);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() ->
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(new DrawPie()));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
The adjustments to the centerX/Y values was a shortcut for using the real FontMetrics of the Graphics class. The X value should be half the width of the text you draw and the Y value should be the height test you draw. You can try playing with the real FontMetrics to see if it makes a difference.
Note, this is an example of an "minimal, reproducible example". Only the code directly related to the question is included in the example. Anybody can copy/paste/compile and text. In the future all questions should include an MRE to demonstrate the problem.
Edit:
My second attempt which attempts to use Andrew's suggestion to determine a point on a line that is half the arc angle and half the radius.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.*;
public class DrawPie extends JPanel
{
private int inset = 25;
private int radius = 100;
private int diameter = radius * 2;
private int translation = inset + radius;
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawArc(g2d, Color.YELLOW, 0, 70, "Y");
drawArc(g2d, Color.RED, 70, 90, "R");
drawArc(g2d, Color.CYAN, 160, 80, "B");
drawArc(g2d, Color.GREEN, 240, 120, "G");
g2d.dispose();
}
private void drawArc(Graphics2D g2d, Color color, int start, int extent, String text)
{
g2d.setColor( color );
Shape shape = new Arc2D.Double(inset, inset, diameter, diameter, start, extent, Arc2D.PIE);
g2d.fill( shape );
double radians = Math.toRadians(90 + start + (extent / 2));
int centerX = (int)(Math.sin(radians) * radius / 2);
int centerY = (int)(Math.cos(radians) * radius / 2);
g2d.setColor( Color.BLACK );
g2d.drawString(text, centerX + translation, centerY + translation);
}
#Override
public Dimension getPreferredSize()
{
int size = (inset * 2) + diameter;
return new Dimension(300, 300);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() ->
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(new DrawPie()));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
Don't know why I needed to add "90" when converting the angle to radians?
For my programming class I'm working on a clock. The clock has to be set at an initial time, which I cannot figure out how to do. The clock I'm currently working with just uses the system time. I've tried setting a time using cal.set but then it just freezes on what I want to be the initial time and time doesn't progress. How can I edit this to allow me to have a set initial time, but have the clock still work?
package Clock;
package Clock;
import java.applet.Applet;
import java.awt.Color;
import java.lang.Object;
import javax.swing.JPanel;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Component extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
public static String name = "My Clock";
public static int size = 600;
public static boolean isRunning = false;
public static Graphics g;
public static Image screen;
public Numbers number;
public static JFrame frame;
public static void main(String [] args) {
Component component = new Component();
frame = new JFrame();
frame.add(component);
frame.setSize(size+6, size + 28);
frame.setTitle(name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
component.start();
}
public void start() {
requestFocus();
number = new Numbers();
isRunning = true;
Thread th = new Thread(this);
th.start();
}
public void run() {
screen = createVolatileImage(size, size);
while (isRunning) {
tick();
render(g);
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void tick() {
}
public double time;
public int anim;
public int anim2;
public int anim3;
public int anim4;
public int center = size/2;
public int radius = (size-40)/2;
public void render(Graphics g) {
// Drawing to image
screen = createImage(size, size);
g = screen.getGraphics();
//Drawing the background
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, size, size);
// Drawing the frame(outside circle)
g.setColor(Color.black);
g.fillOval(5, 5, size - 10, size - 10);
g.setColor(Color.white);
//g.setColor(new Color(new Random().nextInt(255). new Random().nextInt(255), new Random().nextInt(255)));
//g.drawOval(10, 10, size - 20, size - 20);
g.fillOval(20, 20, size - 40, size - 40);
number.render(g);
// Math and Drawing for Lines
for (int i = 0; i < 60; i++) {
radius = size - 40;
anim = center + (int) ((Math.sin(i % 60.0 / 60 * Math.PI * 2) * (radius / 2)));
anim2 = center - (int) ((Math.cos(i % 60.0 / 60 * Math.PI * 2) * (radius / 2)));
radius = size - 60;
anim3 = center + (int) ((Math.sin(i % 60.0 / 60 * Math.PI * 2) * (radius / 2)));
anim4 = center - (int) ((Math.cos(i % 60.0 / 60 * Math.PI * 2) * (radius / 2)));
g.drawLine(anim, anim2, anim3, anim4);
}
// Math for hour hand
radius = size - 140;
// time = System.currentTimeMillis() % 3600000 / 3600000 * Math.PI;
int t = (int) (System.currentTimeMillis() + 17300000) + 3600000+ 3600000 + 3600000 + 3600000 + 3600000 + 3600000 + 3600000 + 3600000;
anim = center
+ (int) ((Math.sin(t % 43200000.0
/ 43200000 * Math.PI * 2) * (radius / 2))) + 7;
anim2 = center
- (int) ((Math.cos(t % 43200000.0
/ 43200000 * Math.PI * 2) * (radius / 2))) + 7;
// Drawing the hour hand
g.setColor(Color.black);
g.fillOval(center - 8, center - 8, 16, 16);
g.drawLine(center, center, anim, anim2);
g.drawLine(center + 1, center, anim + 1, anim2);
g.drawLine(center, center + 1, anim, anim2 + 1);
g.drawLine(center - 1, center, anim - 1, anim2);
g.drawLine(center, center - 1, anim, anim2 - 1);
g.drawLine(center + 1, center + 1, anim, anim2);
g.drawLine(center + 1, center - 1, anim, anim2);
g.drawLine(center - 1, center + 1, anim, anim2);
g.drawLine(center - 1, center - 1, anim, anim2);
// Math for minute hand
radius = size - 90;
// time = System.currentTimeMillis() % 3600000 / 3600000 * Math.PI;
anim = center
+ (int) ((Math.sin(System.currentTimeMillis() % 3600000.0
/ 3600000 * Math.PI * 2) * radius / 2));
anim2 = center
- (int) ((Math.cos(System.currentTimeMillis() % 3600000.0
/ 3600000 * Math.PI * 2) * radius / 2));
// Drawing the minute hand
g.setColor(Color.black);
g.drawLine(center, center, anim, anim2);
g.drawLine(center + 1, center, anim + 1, anim2);
g.drawLine(center, center + 1, anim, anim2 + 1);
g.drawLine(center - 1, center, anim - 1, anim2);
g.drawLine(center, center - 1, anim, anim2 - 1);
//Math for second hand
DateFormat dateFormat = new SimpleDateFormat("ss");
Calendar cal = Calendar.getInstance();
String s = dateFormat.format(cal.getTime());
radius = size - 70;
// time = System.currentTimeMillis() % 60000 / 60000 * Math.PI;
anim = center
+ (int) ((Math.sin(Integer.parseInt(s) % 60.0 / 60 * Math.PI
* 2) * (radius / 2)));
anim2 = center
- (int) ((Math.cos(Integer.parseInt(s) % 60.0 / 60 * Math.PI
* 2) * (radius / 2)));
// Drawing the second hand
g.setColor(Color.red);
g.drawLine(center, center, anim, anim2);
g.drawLine(center + 1, center, anim + 1, anim2);
g.drawLine(center, center + 1, anim, anim2 + 1);
g.drawLine(center - 1, center, anim - 1, anim2);
g.drawLine(center, center - 1, anim, anim2 - 1);
// Center circle
g.fillOval(center - 5, center - 5, 10, 10);
g.setColor(Color.black);
g.fillOval(center - 2, center - 2, 4, 4);
// g.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
// g.fillRect(0, 0, getWidth(), getHeight());
// Drawing to screen
g = getGraphics();
g.drawImage(screen, 0, 0, size, size, this);
g.dispose();
}
}
and
package Clock;
import java.applet.Applet;
import java.awt.Color;
import java.lang.Object;
import javax.swing.JPanel;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Numbers extends JPanel {
private static final long serialVersionUID=1L;
public int size = Component.size;
public int center = size/2;
public void setFont(Font font) {
super.setFont(font);
repaint();
}
public String getDay() {
DateFormat dateFormat=new SimpleDateFormat("dd");
Calendar cal = Calendar.getInstance();
String s = dateFormat.format(cal.getTime());
int day = Integer.parseInt(s);
String d = day + "";
// sets ordinal indicator
switch(day) {
case 1:
case 21:
case 31:
d += "st";
break;
case 2:
case 22:
d += "nd";
break;
case 3:
case 23:
d += "rd";
break;
default:
d += "th";
}
return d;
}
public String getHour() {
DateFormat dateFormat = new SimpleDateFormat("HH");
Calendar cal = Calendar.getInstance();
String s = dateFormat.format(cal.getTime());
int hour = Integer.parseInt(s) -1;
String n = hour + "";
if(hour < 10) {
n=hour+"";
}
return n;
}
public String getMonth() {
DateFormat dateFormat = new SimpleDateFormat("MM");
Calendar cal = Calendar.getInstance();
String s = dateFormat.format(cal.getTime());
int month = Integer.parseInt(s);
// sets month name to number
String m = "";
switch (month)
{
case 1:
m= "January";
break;
case 2:
m= "February";
break;
case 3:
m= "March";
break;
case 4:
m= "April";
break;
case 5:
m= "May";
break;
case 6:
m= "June";
break;
case 7:
m= "July";
break;
case 8:
m= "August";
break;
case 9:
m= "September";
break;
case 10:
m= "October";
break;
case 11:
m= "November";
break;
case 12:
m= "December";
}
return m;
}
public void render(Graphics g) {
g.setColor(Color.black);
DateFormat dateFormat = new SimpleDateFormat(":mm:ss");
Calendar cal = Calendar.getInstance();
String s = dateFormat.format(cal.getTime());
int n = center - ((s.length() *13)/2);
//265
g.setFont(new Font("Arial", 1, 20));
s = (Integer.parseInt(getHour(), 10) % 12 + 1) + "" + dateFormat.format(cal.getTime());
n = center - (s.length() * 10 / 2);
g.setColor(Color.DARK_GRAY);
g.fillRoundRect(250, 348, 100, 30, 6, 6);
g.setColor(Color.LIGHT_GRAY);
g.fillRoundRect(252, 350, 96, 26, 6, 6);
g.setColor(Color.BLACK);
g.drawString("TIME", 275, 345);
g.drawString("DATE", 275, 225);
g.drawString("AM", 255, 150);
g.drawString("PM", 315, 150);
g.drawString(s, n, 370);
int p = Integer.parseInt(getHour(), 10);
if(p < 11 || p == 24) {
g.fillOval(265, 160, 10, 10);
g.drawOval(325, 160, 10, 10);
} else {
g.drawOval(265, 160, 10, 10);
g.fillOval(325, 160, 10, 10);
}
dateFormat = new SimpleDateFormat("yyyy");
cal = Calendar.getInstance();
s = getMonth() + " " + getDay() + ", " + dateFormat.format(cal.getTime());
n = center - (int) ((s.length() * 10.25) / 2);
g.setColor(Color.DARK_GRAY);
g.fillRoundRect(200, 228, 200, 30, 6, 6);
g.setColor(Color.LIGHT_GRAY);
g.fillRoundRect(202, 230, 196, 26, 6, 6);
g.setColor(Color.BLACK);
g.drawString(s, n, 250);
s = Component.name;
n=center - (int)((s.length()*10)/2);
g.drawString(s, n , 450);
g.setFont(new Font("Arial", 1, 30));
int radius = size - 100;
for(int i = 0; i < 12; i++) {
double anim = (int) ((Math.sin((i+1) % 12.0 / 12 * Math.PI * 2) * (radius / 2)));
double anim2 = (int) ((Math.cos((i+1) % 12.0 / 12 * Math.PI * 2) * (radius / 2)));
if(i >= 9){
anim -= 10;
}
g.drawString((i+1) + "", center + (int) anim - 6, center - (int) anim2 + 12);
}
}
}
Lot's of issues -- where to even begin?
You've named a class Component, a name that will easily cause conflicts with a key Java core GUI class, java.awt.Component. Rename it to something else.
This same class extends Applet but is not being used as an Applet. Rather it is being used as a component to be added to a JFrame -- this makes no sense, trying to add one top-level window into another, and would require some justification as to why you're doing it in such a strange fasion. Why not extend JPanel or JComponent something else that makes more sense?
You're using a Graphics field and drawing to it, something that risks NullPointerException. Instead Google and read the Swing drawing tutorials and follow their lead -- draw passively within the paintComponent method of a JPanel. There are other important details to understand which the tutorials will show and tell you.
You're drawing with a Graphics object obtained by calling getGraphics() on a component, something that will lead to unstable drawings and possible NullPointerExceptions. Again read the tutorials on how to do this correctly.
You're making Swing calls in a background thread, something that can lead to intermittent difficult to debug threading errors. Use a Swing Timer to make things easier on yourself. Google the tutorial for the gory details.
You appear to be creating a JPanel, Numbers, but aren't adding it to the GUI (that I can tell), but rather are trying to render it in a strange way -- why, I have no idea. Don't do this. Again do graphics as per the Swing drawing tutorials. Here's the links:
Lesson: Performing Custom Painting: introductory tutorial to Swing graphics
Painting in AWT and Swing: advanced tutorial on Swing graphics
..... more
So i'm trying to make a health + shield bar in my game. If you have ever played League of Legends or Heroes of the Storm, i'm trying to create a health and shield bar that works like that. if not, I have some images for you:
(stackoverflow will not let me post more than 2 links, so just imagine a full health bar :) )
The first example is just the normal health bar displaying health. I got this to work fine by multiplying the percentage health (health/maxHealth) and multiplying that number by the length of the health bar (51)
This second example shows how the health and shield should look when the player is at full health. This is working fine too.
My problem comes here, when the player is not at full health. as you can see, in the first picture, Kalista has around 550 health. Then as she gains the shield, her health bar goes to around 850 total and the 300 health shield is grey. Then once she's taken damage to around 300 health, the 300 health shield is no longer compressed like when it was in the 850 health. My HUD health bar works until this point. Even when the health bar is not at its full capacity, it tries to compress the shield and health into what just the health bar was.
Here's my current code:
package net.masterzach32.sidescroller.assets.gfx;
import java.awt.*;
import java.awt.image.BufferedImage;
import net.masterzach32.sidescroller.assets.Assets;
import net.masterzach32.sidescroller.entity.EntityPlayer;
import net.masterzach32.sidescroller.util.LogHelper;
public class HUD {
private EntityPlayer player;
private BufferedImage image;
private Font font;
double b0 = 31, b1 = 20, hx = 31, mx = 20;
public HUD(EntityPlayer p) {
player = p;
try {
image = Assets.getImageAsset("hud");
font = new Font("Arial", Font.PLAIN, 14);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void render(Graphics2D g) {
g.drawImage(image, 0, 15, null);
double h0 = player.getHealth() / player.getMaxHealth();
double h1 = h0 * hx;
double m0 = player.getShield() / player.getMaxShield();
double m1 = m0 * mx;
if((int) (h1 + m1) <= hx + mx) {
int f = (int) (mx - m1);
h1 += f;
}
LogHelper.logInfo("" + (int) (h1 + m1));
if(h1 >= b0) b0 = h1;
if(h1 < b0) b0 -= .7;
if(m1 >= b1) b1 = m1;
if(m1 < b1) b1 -= .7;
// health bar
g.setColor(new Color(200, 0, 0));
g.fillRect(17, 18, (int) b0, 13);
g.setColor(new Color(0, 170, 0));
g.fillRect(17, 18, (int) h1, 13);
// mana bar
g.setColor(new Color(200, 0, 0));
g.fillRect((int) (17 + b0), 18, (int) b1, 13);
g.setColor(Color.BLUE);
g.fillRect((int) (17 + h1), 18, (int) m1, 13);
g.setFont(font);
g.setColor(Color.WHITE);
if(player.getOrbCurrentCd() > 0) g.drawString("" + (player.getOrbCurrentCd() / 60 + 1), 0, 12);
else g.drawString("" + (player.getOrbCurrentCd() / 60), 0, 12);
g.drawString(player.getLevel() + " - " + (int) player.getExp() + "/" + (int) player.getMaxExp(), 1, 70);
g.setFont(font);
g.drawString((int) (player.getHealth()) + "/" + (int) (player.getMaxHealth()), 16, 29);
}
}
I have a programme where there are sticky notes. You click on them to pick them up and click again to place them somewhere. My problem is when there are two or more sticky notes on top of each other they both get picked up I only want the top one to be picked up. How can I fix this here is my code so far:
public class PhoneMsg {
public int x, y, id, hour, minute;
public boolean drag = false;
public String name, lastname, msg, msg2, msg3;
public Rectangle rx = new Rectangle(x + 290, y, 20, 20);
public Rectangle rdrag = new Rectangle(x, y, 310, 20);
public boolean remove;
private Image img;
public PhoneMsg(int x, int y, String name, String lastname, int hour, int minute, int id) {
this.x = x;
this.y = y;
this.name = name;
this.lastname = lastname;
this.hour = hour;
this.minute = minute;
this.id = id;
rdrag = new Rectangle(x, y, 310, 20);
rx = new Rectangle(x + 290, y, 20, 20);
genMsg();
}
public void tick() {
rx = new Rectangle(x + 290, y, 20, 20);
rdrag = new Rectangle(x, y, 310, 20);
if (rx.intersects(Comp.mx, Comp.my, 1, 1)) {
if (Comp.ml) {
remove = true;
for (int i = 0; i < play.ph.pp.toArray().length; i++) {
// play.ph.pp.get(i).canreadtxt = true;
}
}
}
// dragging
if (drag) {
x = Comp.mx - 140;
y = Comp.my - 10;
}
if (msg == null) {
genMsg();
}
}
public void render(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g2.setRenderingHints(rh);
// display
g.setColor(new Color(19, 165, 34));
g.fillRect(x, y, 310, 150);
g.setColor(new Color(27, 53, 16));
g.drawRect(x, y, 310, 150);
g.setColor(new Color(27, 53, 16));
g.drawRect(x, y, 310, 20);
// Exit part
g.setColor(new Color(27, 53, 16));
g.drawRect(rx.x, rx.y, rx.width, rx.height);
g.setColor(Color.red);
g.setFont(new Font("italic", Font.BOLD, 12));
g.drawString("X", rx.x + 7, rx.y + 15);
// name
g.setColor(Color.black);
g.setFont(new Font("italic", Font.BOLD, 12));
g.drawString("" + name + " " + lastname + "'s Recent Messages", x + 5, y + 15);
// details
String msg11 = String.format("%02d:%02d", hour, minute);
String msg21 = String.format("%02d:%02d", hour, minute);
String msg31 = String.format("%02d:%02d", hour, minute);
if(play.hud.wifi >= 1){
g.setColor(Color.CYAN);
g.setFont(new Font("italic", Font.BOLD, 12));
g.drawString(" " + msg, x + 2, y + 38);
g.setColor(Color.white);
g.setFont(new Font("italic", Font.BOLD, 12));
g.drawString(" " + msg2, x + 2, y + 58);
g.setColor(Color.cyan);
g.setFont(new Font("italic", Font.BOLD, 12));
g.drawString(" " + msg3, x + 2, y + 78);
}else if(play.hud.wifi <= 0){
g.setColor(Color.red);
g.setFont(new Font("italic", Font.PLAIN, 18));
g.drawString("Lost Connection", x +90, y +85);
g.setColor(Color.red);
g.setFont(new Font("italic", Font.PLAIN, 18));
g.drawString("_________________", x +70, y +88);
}
}
}
and this is the part in the mouse listener that lets u pick up the sticky notes:
// dragging msg's
for (int i1 = 0; i1 < play.ph.pm.toArray().length; i1++) {
if (play.ph.pm.get(i1).drag == false && play.holding == false) {
if (play.ph.pm.get(i1).rdrag.contains(Comp.mx, Comp.my)) {
play.ph.pm.get(i1).drag = true;
play.holding = true;
}
} else {
play.ph.pm.get(i1).drag = false;
play.holding = false;
}
}
If you break out of the for loop you can pick up the first sticky note the code gets to when they're overlapping.
if (play.ph.pm.get(i1).rdrag.contains(Comp.mx, Comp.my)) {
play.ph.pm.get(i1).drag = true;
play.holding = true;
break; // Found sticky note, exits loop
}
Or if this conflicts with your else statement, simply create a flag.
// dragging msg's
boolean gotCard = false;
for (int i1 = 0; i1 < play.ph.pm.toArray().length; i1++) {
if (play.ph.pm.get(i1).drag == false && play.holding == false && gotNote == false) { // Added gotNote check
if (play.ph.pm.get(i1).rdrag.contains(Comp.mx, Comp.my)) {
play.ph.pm.get(i1).drag = true;
play.holding = true;
gotNote = true; // Set flag to true
}
} else {
play.ph.pm.get(i1).drag = false;
play.holding = false;
}
}
However you should probably have a z-index implemented to be able to tell which sticky note is on top then sort your array by that z-index.
I am trying to find a way to determine a winner and I am not having much luck. The program is suppose to run three laps and which ever car finish all the laps first is the winner. I can get 3 "laps" in but it is not a very good way of doing it. I am hoping someone can show me a better way and also how I can can "count" those laps for the specific winning car. The number of cars is random from 2 - 4 and the "speed" is also random. Can someone help me please. Some code would be nice.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class RacingCar extends JFrame {
public RacingCar() {
int x = (int)(Math.random() * 3) + 2;
setLayout(new GridLayout(x, 1, 5,5));
for (int i = 0; i < x; i++){
add(new CarImage());
}
}
public static void main(String[] args) {
JFrame frame = new RacingCar();
frame.setTitle("Racing Car");
frame.setSize(1200, 350);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class CarImage extends JPanel {
protected int x = 0;
protected int y = 350;
protected int z = 1200;
protected int c = 0;
public CarImage() {
int j = (int)(Math.random() * 500) + 2;
Timer timer1 = new Timer(j, new ActionListener(){
public void actionPerformed(ActionEvent e) {
x += 10;
c ++;
repaint();
}
});
timer1.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//x = 0;
y = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, y);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 21);
polygon.addPoint(x + 20, y - 31);
polygon.addPoint(x + 30, y - 31);
polygon.addPoint(x + 40, y - 21);
if (x < z - 50) {
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 11, 10, 10);
g.fillOval(x + 30, y - 11, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 21, 50, 10);
g.setColor(Color.GRAY);
g.fillPolygon(polygon);
g.setColor(Color.RED);
}
else {
x = 0;
/*if (c < z - 86) {
g.drawString("Clint's Car", c, y - 51);
}
else {
c = 0;
}*/
}
}
}
}
What I did for the laps loop is this:
if (k < 341){
repaint();
k++;
{
this loop was inserted at the end of:
public void paintComponent(Graphics g) {
I really am stuck here. Thanks for all the help.
Give this code a try
New RacingCar.java
By the way I made your timer be faster in order to not wait 3 laps on really slow races! :P