Flashing JTextField and JButton - java

//ADDING BET FIELDS
setLayout(null);
horseChoice = new JTextField();
horseChoice.setBounds(200, 585, 300, 20);
add(horseChoice);
setLayout(null);
horseBet = new JTextField();
horseBet.setBounds(200, 625, 300, 20);
add(horseBet);
//ADDING BET BUTTON
setLayout(null);
bet = new JButton("Place Bet");
bet.setBounds(250, 675, 200, 50);
add(bet);
I am trying to create two textfields where the users can type in what they want and a button to save their input to a variable. But when I run my program, the text fields and button flash and then become invisible. Then if the user clicks on them they flash again. How do I stop this from happening?
The rest of the class:
// the "main" function
public void run(){
init();
font = new Font ("Arial", Font.BOLD, 14);
titleFont = new Font ("Comic Sans MS", Font.BOLD, 20);
textColor = new Color(100, 100, 100);
resultColor = new Color(255, 165, 0, 180);
//ADDING HORSES
horse1 = new Horses_1();
horse2 = new Horses_2();
horse3 = new Horses_3();
horse4 = new Horses_4();
//GAMELOOP
while (running){
start = System.nanoTime();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
try{
Thread.sleep(wait);
}
catch(Exception e){
e.printStackTrace();
}
//TIMER
if(horse1.h1x < 1350){
horse1Time++;
}
if(horse2.h2x < 1350){
horse2Time++;
}
if(horse3.h3x < 1350){
horse3Time++;
}
if(horse4.h4x < 1350){
horse4Time++;
}
//STOP RACING TIMERS
if(horse1Result == true && horse1.h1x >= 1350){
horse1TimeStr = horse1Time + ", Dominic";
horse1Result = false;
}
if(horse2Result == true && horse2.h2x >= 1350){
horse2TimeStr = horse2Time + ", Charlie";
horse2Result = false;
}
if(horse3Result == true && horse3.h3x >= 1350){
horse3TimeStr = horse3Time + ", Admiral";
horse3Result = false;
}
if(horse4Result == true && horse4.h4x >= 1350){
horse4TimeStr = horse4Time + ", Bacardi";
horse4Result = false;
}
//RANDOM HORSE CHOICE & MOVE PLACES
if(horse1.h1x >= 1350){
final int[] CHOICES = { 2,3,4 };
}
else if(horse2.h2x >= 1350){
final int[] CHOICES = { 1,3,4 };
}
else if(horse3.h3x >= 1350){
final int[] CHOICES = { 1,2,4 };
}
else if(horse4.h4x >= 1350){
final int[] CHOICES = { 1,2,3 };
}
else{
final int[] CHOICES = { 1,2,3,4 };
}
randomHorse = CHOICES[rand.nextInt(CHOICES.length)];
randomMove = rand.nextInt(35) + 1;
//PLACES
Update();
Draw();
drawToScreen();
}
}
// updates the game
private void Update() {
//UPDATE RACE COUNTER
if(horse1.h1x == 100 && horse2.h2x == 100 && horse3.h3x == 100 && horse4.h4x == 100){
races++;
}
//HORSE UPDATE
horse1.Update();
horse2.Update();
horse3.Update();
horse4.Update();
//RESULT SETTING
if(result == true && horse1Result == false && horse2Result == false && horse3Result == false && horse4Result == false){
String[] horses =
{ horse1TimeStr, horse2TimeStr, horse3TimeStr, horse4TimeStr };
Arrays.sort(horses);
firstHorse = horses[0];
secondHorse = horses[1];
thirdHorse = horses[2];
fourthHorse = horses[3];
firstHorse = firstHorse.replaceAll("[0-9,,]","");
secondHorse = secondHorse.replaceAll("[0-9,,]","");
thirdHorse = thirdHorse.replaceAll("[0-9,,]","");
fourthHorse = fourthHorse.replaceAll("[0-9,,]","");
result = false;
}
}
// draws the game onto an off-screen buffered image
private void Draw() {
//BACKGROUND COLOUR
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
if(button == true){
//ADDING BET FIELDS
setLayout(null);
horseChoice = new JTextField();
horseChoice.setBounds(200, 585, 300, 20);
add(horseChoice);
setLayout(null);
horseBet = new JTextField();
horseBet.setBounds(200, 625, 300, 20);
add(horseBet);
//ADDING BET BUTTON
setLayout(null);
bet = new JButton("Place Bet");
bet.setBounds(250, 675, 200, 50);
add(bet);
button = false;
}
horse1.Draw(g);
horse2.Draw(g);
horse3.Draw(g);
horse4.Draw(g);
//HORSE 1 - TRACK
g.setColor(new Color (255, 0, 0));
g.drawLine(100, 125, WIDTH - 100, 125);
//HORSE 2 - TRACK
g.setColor(new Color (0, 255, 0));
g.drawLine(100, 225, WIDTH - 100, 225);
//HORSE 3 - TRACK
g.setColor(new Color (0, 0, 255));
g.drawLine(100, 325, WIDTH - 100, 325);
//HORSE 4 - TRACK
g.setColor(new Color (255, 255, 0));
g.drawLine(100, 425, WIDTH - 100, 425);
//FINISH LINE
g.setColor(new Color (255, 255, 0));
g.drawLine(WIDTH - 100, 475, WIDTH - 100, 375);
g.setColor(new Color (0, 0, 255));
g.drawLine(WIDTH - 100, 275, WIDTH - 100, 375);
g.setColor(new Color (0, 255, 0));
g.drawLine(WIDTH - 100, 175, WIDTH - 100, 275);
g.setColor(new Color (255, 0, 0));
g.drawLine(WIDTH - 100, 75, WIDTH - 100, 175);
//HUD
g.setColor(new Color (180, 180, 180));
g.drawLine(50, 550, WIDTH - 50, 550);
g.drawLine(550, 550, 550, 700);
g.drawLine(900, 550, 900, 700);
g.setColor(resultColor);
g.setFont(titleFont);
g.drawString("Results", 700, 540);
g.drawString("Details", 1000, 540);
g.drawString("Betting", 360, 540);
//Results
g.setColor(textColor);
g.setFont(font);
g.drawString("Winner : ", 600, 600);
g.drawString("Second : ", 600, 630);
g.drawString("Third : ", 600, 660);
g.drawString("Fourth : ", 600, 690);
//DETAILS
g.drawString("Race Number :", 950, 600);
g.drawString("Horse Choice :", 950, 630);
g.drawString("Bet :", 950, 660);
g.setColor(resultColor);
g.drawString("" + races, 1250, 600);
//BETS
g.setColor(textColor);
g.drawString("Horse Choice :", 75, 600);
g.drawString("Bet :", 75, 640);
if(horse1Result == false && horse2Result == false && horse3Result == false && horse4Result == false){
g.setColor(resultColor);
g.drawString(" " + firstHorse, 780, 600);
g.drawString(" " + secondHorse, 780, 630);
g.drawString(" " + thirdHorse, 780, 660);
g.drawString(" " + fourthHorse, 780, 690);
}
g.setColor(textColor);
g.setFont(font);
//HORSE 1 TEXT
String h1 = "Dominic -";
g.drawString(h1, 10, 130);
//HORSE 2 TEXT
String h2 = "Charlie -";
g.drawString(h2, 10, 230);
//HORSE 3 TEXT
String h3 = "Admiral -";
g.drawString(h3, 10, 330);
//HORSE 4 TEXT
String h4 = "Bacardi -";
g.drawString(h4, 10, 430);
}

Looks like while(running) and Thread.sleep is giving your problems. For Swing apps use a javax.swing.Timer. Here is the basic construct
Timer(int delay, ActionListener listener)
where delay is the time to be delayed ("slept") between intervals and the listener is used just like a listener for a button, except you don't need to press a button for the event to fire, the Timer fires the event every delayed milliseconds. You can do something like this
Timer timer = new Timer(delay, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// the stuff in your while loop here
}
});
timer.starts();
Here's an example of a Timer being used. Take a look at the docs for more methods you can use with the timer.
Side Note
It's not recommended to use a null layout. Take a look at Laying out Components within a Container for details on how to use Layout Managers, as you should be using instead of a null layout.

Related

How can I avoid keyPressed method to make my draw permenant in Processing 3?

I'm trying to create a HangMan game since it's an assignment. In the game() method, I want to call some methods from dead class if player's input is wrong. These methods creates HangMan. When I input a wrong letter and press Enter (increasing numWrong) related method is called but only flashes and disappears. I know it because of keyPressed method but how can I draw HangMan on screen and make it permanent till end of the game.
String[] words = {"dictionary","game","player","result"};
char[] strChar, guessed, wrong;
float x, y;
String str, display, display2, typing="", guess="", win = "", lost = "", wrongAnswers;
int rnd, c, numRight=0, winner=0, numWrong=0;
void setup() {
size(800, 800);
surface.setLocation(960, 0);
x = width;
y = height;
rnd = words.length-1;
str = words[(int)random(rnd)].toUpperCase();
strChar = new char[str.length()];
winner = str.length();
guessed = new char[str.length()];
for (int c=0; c<str.length(); c++) {
strChar[c] = str.charAt(c);
guessed[c] = '_';
}
wrong = new char[6];
for (int i=0; i<wrong.length; i++) {
wrong[i] = '*';
}
}
void draw() {
background(10);
display = "Write a letter then press ENTER.";
display2 = " ";
wrongAnswers = "Incorrect Guesses: ";
for (int d=0; d<guessed.length; d++) {
display2 = display2 +" "+guessed[d];
}
for (int i=0; i<wrong.length; i++) {
wrongAnswers = wrongAnswers+" "+wrong[i];
}
fill(255);
textSize(40);
text(display2, 40, 750);
textSize(20);
text(display, 450, 380);
textSize(250);
text(typing.toUpperCase(), 450, 245);
strokeWeight(1);
d.gallows();
fill(55, 200, 155);
textSize(50);
text(win, 110, 680);
textSize(50);
text(lost, 110, 680);
textSize(20);
text(wrongAnswers, 410, 690);
//origins
stroke(100, 150, 200);
strokeWeight(2);
line(0, 700, x, 700);//seperate line
line(x/2, 0, x/2, 700);//vertical line
line(x/2, y/2, x, y/2);//horizontal line
fill(255);
textSize(35);
text(str, 90, 560);
}
void game(String guess) {
guess = guess.toUpperCase();
char myGuess = guess.charAt(0);
boolean guessedRight = false;
for (int m=0; m<str.length(); m++) {
if (myGuess==str.charAt(m)) {
if (exist(display2, myGuess)) {
guessed[m] = myGuess;
numRight++;
guessedRight = true;
}
if (numRight == winner) {
win = "YOU WIN!!";
}
}
}
if (guessedRight == false) {
wrong[numWrong] = myGuess;
numWrong++;
noStroke();
fill(255);
if (numWrong==1) {
d.headAndRope();
}
if (numWrong==2) {
d.body();
d.headAndRope();
}
if (numWrong==3) {
d.leftArm();
d.body();
d.headAndRope();
}
if (numWrong==4) {
d.rightArm();
d.leftArm();
d.body();
d.headAndRope();
}
if (numWrong==5) {
d.leftLeg();
d.rightArm();
d.leftArm();
d.body();
d.headAndRope();
}
if (numWrong==6) {
d.rightLeg();
d.leftLeg();
d.rightArm();
d.leftArm();
d.body();
d.headAndRope();
}
if (numWrong == wrong.length) {
lost = "YOU LOSE!!";
}
}
}
void keyPressed() {
if (key == '\n') {
game(typing);
typing = "";
} else {
typing+=key;
}
}
boolean exist(String sng, char cha) {
for (int i=0; i<sng.length(); i++) {
if (sng.charAt(i)==cha) {
return false;
}
}
return true;
}
//DEAD CLASS
class Dead {
void gallows() {
stroke(0);
//base
fill(127);
rect(40, 600, 340, 30);
//left vertical rect
fill(200, 100, 50);
rect(60, 50, 10, 550);
//right vertical rect
fill(100, 50, 25);
rect(70, 50, 10, 550);
//top horizontal rect
fill(200, 100, 50);
rect(60, 40, 300, 10);
//bottom horizontal rect
fill(100, 50, 25);
rect(70, 50, 290, 10);
//diagonal bottom rect
fill(100, 50, 25);
beginShape();
vertex(80, 250);
vertex(80, 265);
vertex(265, 60);
vertex(250, 60);
endShape(CLOSE);
//diagonal top rect
fill(200, 100, 50);
beginShape();
vertex(70, 245);
vertex(70, 260);
vertex(260, 50);
vertex(245, 50);
endShape(CLOSE);
}
void headAndRope() {
//rope
fill(255);
rect(300, 40, 2, 95);
//head
fill(255);
ellipse(301, 155, 50, 75);
}
void body() {
//body
stroke(255);
strokeWeight(3);
line(301, 193, 301, 375);
}
void leftArm() {
//left arm
stroke(255);
strokeWeight(2);
line(301, 223, 251, 300);
}
void rightArm() {
//right arm
stroke(255);
strokeWeight(2);
line(301, 223, 351, 300);
}
void leftLeg() {
//left leg
stroke(255);
strokeWeight(2);
line(301, 375, 251, 450);
}
void rightLeg() {
//right leg
stroke(255);
strokeWeight(2);
line(301, 375, 351, 450);
}
}
In Processing the draw function gets called every frame, completely redrawing everything on the screen. So if you want the hangman to always appear on the screen, you'll need to draw it in the draw function (or in a function that gets called from draw).
If you restructure your code slightly everything should work:
void draw() {
// draw UI and input prompt based on `numRight` value
// NEW: draw the current state of the hangman based on `numWrong` value
}
void game(String guess) {
// update the game state (`numRight` and `numWrong` variables)
// based on `guess` input
// NEW: since this is only called momentarily, don't do any drawing here
}
void keyPressed() {
// receive key input and pass it to `game`
}
Since game only gets called momentarily when the user enters a guess, you don't want to be doing any drawing in there. It will get overwritten in the next draw cycle. You can still update the game state in game, but the drawing representation of that game state should happen from draw to ensure it gets drawn every time the screen updates.

Java - Trouble Passing Variables Between Main Method and Drawing Method

I'm creating a dots and boxes program and I am trying to feed the coordinate values from the main method where the user inputs them to the paintComponent method in the JFrame class. However I have to throw in the (Graphics g) parameter, and I don't see a way around it to feed in the values. It's probably big cringe because I'm still starting out but any help would be great.
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
JFrame f = new JFrame("Dots & Boxes");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Drawing a = new Drawing();
f.add(a);
f.setSize(1440,990);
f.setVisible(true);
Scanner input = new Scanner(System.in);
System.out.println("You will choose two coordinates on the dot grid to place a line between.");
System.out.println("Make sure that they are right next to each other, either vertically or horizontally (not diagonal)");
int xOne;
int yOne;
int xTwo;
int yTwo;
boolean playerOneTurn = true;
for (int i = 0; i <= 760; i++){
System.out.println("Pick Your First X-Coordinate: ");
xOne = input.nextInt();
System.out.println("Pick Your First Y-Coordinate: ");
yOne = input.nextInt();
System.out.println("Pick Your Second X-Coordinate: ");
xTwo = input.nextInt();
System.out.println("Pick Your Second Y-Coordinate: ");
yTwo = input.nextInt();
playerOneTurn = !playerOneTurn;
}
}
}
class Drawing extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.drawString("0", 75, 45);
g.drawString("1", 110, 45);
g.drawString("2", 145, 45);
g.drawString("3", 180, 45);
g.drawString("4", 215, 45);
g.drawString("5", 250, 45);
g.drawString("6", 285, 45);
g.drawString("7", 320, 45);
g.drawString("8", 355, 45);
g.drawString("9", 390, 45);
g.drawString("10", 417, 45);
g.drawString("11", 452, 45);
g.drawString("12", 487, 45);
g.drawString("13", 522, 45);
g.drawString("14", 557, 45);
g.drawString("15", 592, 45);
g.drawString("16", 627, 45);
g.drawString("17", 662, 45);
g.drawString("18", 697, 45);
g.drawString("19", 732, 45);
g.drawString("0", 40, 75);
g.drawString("1", 40, 110);
g.drawString("2", 40, 145);
g.drawString("3", 40, 180);
g.drawString("4", 40, 215);
g.drawString("5", 40, 250);
g.drawString("6", 40, 285);
g.drawString("7", 40, 320);
g.drawString("8", 40, 355);
g.drawString("9", 40, 390);
g.drawString("10", 35, 425);
g.drawString("11", 35, 460);
g.drawString("12", 35, 495);
g.drawString("13", 35, 530);
g.drawString("14", 35, 565);
g.drawString("15", 35, 600);
g.drawString("16", 35, 635);
g.drawString("17", 35, 670);
g.drawString("18", 35, 705);
g.drawString("19", 35, 740);
int dotx1 = 80;
int doty1 = 70;
((Graphics2D) g).setStroke(new BasicStroke(5));
for (int h = 0; h <= 19; h++) {
for (int i = 0; i <= 19; i++) {
g.drawLine(dotx1, doty1, dotx1, doty1);
dotx1 = dotx1 + 35;
}
dotx1 = 80;
doty1 = doty1 + 35;
}
}
}
You shouldn't call paintComponent by yourself. The method is called when Java is drawing the window.
The reason is that the user shouldn't care about re-drawing, most of the time. Java will decide when to redraw, for example on window minimize/maximize or resizing or when an element is clicked.
To draw animated shapes you must ask Java to redraw your window. You can add f.revalidate() to force components to redraw. Take a look at the documentation here.
Be really careful when using this. Never call this inside a loop without waiting between frames, because your CPU will go crazy if not !
If you want animated shapes, call revalidate() at fixed rate, for example 60fps.
In your case, you could simple put your Scanner inside the loop, ask the user for input, process it and then redraw the window.
Also, revalidate() is not blocking, it will just tell Java that the components tree has changed and must be redraw. But it will do it when he will have the time to do it.
Edit : As we are discussing in commentary, to feed your Drawing with the data to draw you must give him the informations.
First, create your graphical elements, let start with points :
class Point {
public float x, y;
Point(float x, float y) {
this.x = x;
this.y = y;
}
}
In your Drawing (who is in fact your Scene, let rename it), add setters and List
class Scene {
private List<Point> mPoints = new LinkedList<Point>();
public addPoint(Point p) {
mPoints.add(p);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
....
for (Point p : mPoints) {
// draw your points here
}
....
}
}
There several way to improve this simple example. First, you could add a paint(Graphics g) method on Point class.
When you will add another kind of component, you should create a base class Item and extend it in your graphical items (Point, Box...) and put the paint method in this new base class.
It's the way to don't have one list for each kind of element, and then you can just iterate over items and call paint without worrying about the kind behind it (Point, Box...)

Animating a painted object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've gone through and made classes for my objects and calls to them in my paint component, but I cant actually get them to move. Here is my move and check walls program that is in the object class:
public void move()
{
ballX += dx;
ballY += dy;
checkWalls();
}
//bounce of top/bottom, pass through left/right
public void checkWalls() {
//left-right
if(ballX > w) {
ballX = -diam;
}
else if(ballX < -diam) {
ballX = w;
}
//top-bottom
if(ballY < 0) {
dy *= -1;
}
else if(ballY + diam > h) {
dy *= -1;
}
}
And here is my call to them:
while(true) // infinite loop
{
jelly1.move();
frame.repaint();
try
{
Thread.sleep(10);
}
catch(Exception e){}
}
Also i feel the need to mention i have a background and a background component. The while(true) is in the background component because that's where the objects are created. And the frame is set visible in the background where the main method is.
Paint component is as follows:
public class BackgroundComponent extends JComponent {
Jellyfish jelly1;
Jellyfish jelly2;
Jellyfish jelly3;
Diver diver;
public BackgroundComponent() {
diver = new Diver(100, 300);
jelly1 = new Jellyfish(450, 450);
jelly2 = new Jellyfish(150, 300);
jelly3 = new Jellyfish(350, 75);
diver = new Diver(100, 300);
}
public void paintComponent(Graphics g){
//Drawing instructions go here
//Recover Graphics2D
Graphics2D g2 = (Graphics2D)g;
//Make gradient
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
Color color1 = Color.CYAN;
Color color2 = Color.BLACK;
GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
g2.setPaint(gp);
g2.fillRect(0, 0, w, h);
//Constructs rectangles on edge of screen and draws them
Rectangle box = new Rectangle(0,0,75,700);
g.setColor(Color.LIGHT_GRAY);
g2.fill(box);
Rectangle box2 = new Rectangle(625, 0, 75, 700);
g.setColor(Color.LIGHT_GRAY);
g2.fill(box2);
//Draws lines, with a stroke of 5, over rectangles
Line2D.Double segment = new Line2D.Double(10, 0, 10, 700);
g2.setStroke(new BasicStroke(5));
g.setColor(Color.GRAY);
g2.draw(segment);
Line2D.Double segment2 = new Line2D.Double(30, 0, 30, 700);
g.setColor(Color.GRAY);
g2.draw(segment2);
Line2D.Double segment3 = new Line2D.Double(50, 0, 50, 700);
g.setColor(Color.GRAY);
g2.draw(segment3);
Line2D.Double segment4 = new Line2D.Double(70, 0, 70, 700);
g.setColor(Color.GRAY);
g2.draw(segment4);
Line2D.Double segment5 = new Line2D.Double(690, 0, 690, 700);
g.setColor(Color.GRAY);
g2.draw(segment5);
Line2D.Double segment6 = new Line2D.Double(670, 0, 670, 700);
g.setColor(Color.GRAY);
g2.draw(segment6);
Line2D.Double segment7 = new Line2D.Double(650, 0, 650, 700);
g.setColor(Color.GRAY);
g2.draw(segment7);
Line2D.Double segment8 = new Line2D.Double(630, 0, 630, 700);
g.setColor(Color.GRAY);
g2.draw(segment8);
//Draws rectangle around title with thick boarder
Rectangle box3 = new Rectangle(40,40,620,75);
g.setColor(Color.WHITE);
g2.setStroke(new BasicStroke(5));
g2.draw(box3);
//Drawing text
String title = "Through the Depths";
//Sets font, font size, and color
g.setFont(new Font("Purisa", Font.BOLD, 50));
g.setColor(Color.DARK_GRAY);
g2.drawString(title, (50), 100);
//Places same text slightly up and over
g.setFont(new Font("Purisa", Font.BOLD, 50));
g.setColor(Color.WHITE);
g2.drawString(title, 53, 97);
//Draws ellipses with a stroke of 2 (these are the bubbles)
Ellipse2D.Double ellipse = new Ellipse2D.Double(450, 200, 150, 150);
g2.setStroke(new BasicStroke(2));
g2.draw(ellipse);
Ellipse2D.Double ellipse2 = new Ellipse2D.Double(510, 375, 90, 90);
g2.draw(ellipse2);
Ellipse2D.Double ellipse3 = new Ellipse2D.Double(470, 485, 70, 70);
g2.draw(ellipse3);
Ellipse2D.Double ellipse4 = new Ellipse2D.Double(510, 580, 45, 45);
g2.draw(ellipse4);
// Draws curves for bubbles
QuadCurve2D q = new QuadCurve2D.Float();
q.setCurve(548, 210, 607, 240, 590, 295);
g2.setStroke(new BasicStroke(3));
g2.draw(q);
QuadCurve2D q2 = new QuadCurve2D.Float();
q2.setCurve(575, 387, 607, 415, 585, 445);
g2.draw(q2);
QuadCurve2D q3 = new QuadCurve2D.Float();
g2.setStroke(new BasicStroke(2));
q3.setCurve(515, 493, 545, 511, 528, 540);
g2.draw(q3);
QuadCurve2D q4 = new QuadCurve2D.Float();
g2.setStroke(new BasicStroke(1));
q4.setCurve(538, 585, 558, 595, 545, 617);
g2.draw(q4);
// Sets color to pink before drawing jellyfish
g.setColor(Color.PINK);
//draws jellyfish
jelly1.draw(g);
jelly2.draw(g);
jelly3.draw(g);
// Draws diver
diver.draw(g);
while(true) // infinite loop
{
jelly1.move();
repaint();
try
{
Thread.sleep(10);
}
catch(Exception e){}
}
}
}
while(true){ ... } and Thread.Sleep inside a paintComponent implementation is completely the wrong way of doing things. By doing this, you are blocking the Event Dispatching Thread completely which means that your UI will no longer be updated properly and the UI will no longer be responsive.
What you should do:
Remove the while(true){ ... } loop from the paintComponent override
Create a javax.swing.Timer, set it to run every 10 milliseconds
In the ActionListener.actionPerformed implementation - the action that will be performed each 10 ms - move the jelly and call for a repaint
Start this timer after initialization is done, eg at the end of your constructor or initialization method (not paintComponent).
Stop the timer when it is no longer needed
Simplified example for this Timer, based on your snippet:
new javax.swing.Timer( 10, new ActionListener( ) {
#override
public void actionPerformed( ActionEvent e ) {
jelly1.move();
repaint();
}
}).start();

Display card in Java

I am writing a program simulating a single round of the card game WAR.
I don't know how to graphically display the card (number/color/suit).
import java.util.*; // for Scanner class
import java.awt.*;
import javax.swing.*;
// Class Definition
class Project4 {
// Main method definition
public static void main(String[] args) {
// Object and Variable Declarations
JFrame win;
Container contentPane;
Graphics g;
String player1Name, player2Name, scoreWinLoss;
//This is the graphics portion, all of the graphics (so far) are working.
win = new JFrame("War Game");
win.setSize(900, 600);
win.setLocation(100, 100);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Color white = new Color(255, 255, 255);
Color white2 = new Color(255, 255, 255);
Color black = new Color(0, 0, 0);
Color black2 = new Color(0, 0, 0);
contentPane = win.getContentPane();
//Also if anyone knows how to change this .setBackground(Color.Green)from lime green to forest(card table) green that would be awesome!
contentPane.setBackground(Color.GREEN);
g = contentPane.getGraphics();
Font font = new Font("Serif", Font.BOLD, 25);
g.setFont(font);
try {
Thread.sleep(200);
} catch (Exception e) {}
player1Name = JOptionPane.showInputDialog(null, "Player 1, what is your name?");
player2Name = JOptionPane.showInputDialog(null, "Player 2, what is your name?");
g.setColor(black);
g.drawString(player1Name, 220, 35);
g.setColor(black2);
g.drawString(player2Name, 625, 35);
g.setColor(white);
g.fillRoundRect(125, 50, 250, 450, 20, 20);
g.setColor(white2);
g.fillRoundRect(525, 50, 250, 450, 20, 20);
g.setColor(black);
g.drawRoundRect(125, 50, 250, 450, 20, 20);
g.setColor(black2);
g.drawRoundRect(525, 50, 250, 450, 20, 20);
//This is where it gets confusing and this stuff is all not working
int card1Max = 14, card1Min = 2, card2Max = 14, card2Min = 2, randomNum1 = 0, randomNum2 = 0;
g.setColor(black);
g.drawInt(randomNum1, 150, 35);
g.setColor(black2);
g.drawInt(randomNum2, 500, 35);
Random randomPicker = new Random(System.currentTimeMillis());
randomNum1 = randomPicker.nextInt(card1Max - card1Min + 1) + card1Min;
randomNum2 = randomPicker.nextInt(card2Max - card2Min + 1) + card2Min;
if (randomNum1 < randomNum2) {
scoreWinLoss = player2Name + " won!";
} else if (randomNum1 > randomNum2) {
scoreWinLoss = player1Name + " won!";
} else if (randomNum1 == randomNum2) {
scoreWinLoss = "It's a tie! Play again to determine a winner.";
}
Do not play with the graphics object like you are doing :
g.setColor(black);
g.drawString(player1Name, 220, 35);
This is bad!
Instead you should look at a layout. Look at GridLayout, or GridBagLayout. These allow you to organise JPanels as a grid. With these panels you can then set the background color and add text (via a JLabel).
if i understand your problem: as simple way, you can use JPanel with CardLayout and then find card picture from web then, with JLabel.setImageIcon(ImageIcon imageIcon) method of JLabel set this pictures on it and by CardLayout bring up cards on toghether.

Java fullscreen mode breaks JPopupMenu. Still works, but doesn't render

I have a JPopupMenu that appears when a user right clicks on the window (as per usual with popups). When you're out in the middle of the screen, there's never a problem, but when you're up against the right side of the screen or the bottom, the menu just doesn't show up when in fullscreen mode.
Oddly enough, if you do the subsequent left click - pretending that the menu is there (because it actually is) - it will still select the correct value as if the menu's vertical and / or horizontal positions had been adjusted to compensate for the edges of the screen.
Even more oddly, this only happens on certain machines for reasons I can't fathom. E.g., I have two PCs here at work, both running Win7; one of them exhibits the failure, the other does not. On the machine that does exhibit the failure, the Win7 VM I have in it also does, but the Ubuntu VM does not. Now, one thing I noticed was that on the machines that do exhibit the rendering problem, the title bar of the JFrame disappears once full screen mode is entered, whereas the others do not (i.e. they still show the close and minimize buttons, making it seem like fullscreen exclusive mode on those machines was little more than maximizing).
Here is a fully functioning example of the problem (assuming your machine is magically susceptible to it) (enter fullscreen to see the problem)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.xml.ws.Holder;
public class ExclusiveModePopup {
public static void main(String[] args) {
final JFrame frame = new JFrame("Exclusive Popup test");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Holder<Boolean> isInFullScreen = new Holder<Boolean>(false);
final Holder<String> lastSelected = new Holder<String>("");
final JPanel pane = new JPanel(new BorderLayout());
pane.add(new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
FontMetrics fm = g.getFontMetrics();
int fontHeight = fm.getMaxAscent();
g.setColor(Color.green);
g.drawOval(5, 5, 20, 20);
g.drawString("Right click here to see normal", 5, 25 + fontHeight);
if(!isInFullScreen.value){
g.drawOval(5, this.getHeight() - 30, 20, 20);
g.drawString("Right click here to see vertical adjustment",
5, this.getHeight() - 35);
g.drawOval(this.getWidth() - 30, 5, 20, 20);
String alongRight = "Right click here to see horizontal adjustment";
int strWidth = fm.charsWidth(alongRight.toCharArray(), 0, alongRight.length());
g.drawString(alongRight, this.getWidth() - 5 - strWidth, 25 + fontHeight);
g.drawOval(this.getWidth() - 30, this.getHeight() - 30, 20, 20);
alongRight = "Right click here to see both values adjusted";
strWidth = fm.charsWidth(alongRight.toCharArray(), 0, alongRight.length());
g.drawString(alongRight, this.getWidth() - 5 - strWidth, this.getHeight() - 35);
} else {
g.setColor(Color.red);
g.drawOval(5, this.getHeight() - 30, 20, 20);
g.drawString("Right click here to see failure",
5, this.getHeight() - 35);
g.drawOval(this.getWidth() - 30, 5, 20, 20);
String alongRight = "Right click here to see more failure";
int strWidth = fm.charsWidth(alongRight.toCharArray(), 0, alongRight.length());
g.drawString(alongRight, this.getWidth() - 5 - strWidth, 25 + fontHeight);
g.drawOval(this.getWidth() - 30, this.getHeight() - 30, 20, 20);
alongRight = "Right click here to see yet some moar failure";
strWidth = fm.charsWidth(alongRight.toCharArray(), 0, alongRight.length());
g.drawString(alongRight, this.getWidth() - 5 - strWidth, this.getHeight() - 35);
}
g.setColor(Color.white);
String lastSel = "Last selected value: " + lastSelected.value;
int strWidth = fm.charsWidth(lastSel.toCharArray(), 0, lastSel.length());
g.drawString(lastSel, this.getWidth() / 2 - strWidth / 2, this.getHeight() / 2);
}
}, BorderLayout.CENTER);
final JPopupMenu popup = new JPopupMenu();
for (int i = 0; i < 10; i++) {
final int j = i;
popup.add(new JMenuItem(new AbstractAction("Long name item number " + i){
#Override
public void actionPerformed(ActionEvent arg0) {
lastSelected.value = "Item #" + j;
pane.repaint();
}
}));
}
pane.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) == MouseEvent.BUTTON3_MASK) {
popup.show((Component) e.getSource(), e.getX(), e.getY());
}
}
});
final GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
pane.add(new JButton(new AbstractAction("Toggle Fullscreen") {
#Override
public void actionPerformed(ActionEvent arg0) {
if (gd.isFullScreenSupported()) {
if (!isInFullScreen.value) {
gd.setFullScreenWindow(frame);
isInFullScreen.value = true;
} else {
gd.setFullScreenWindow(null);
isInFullScreen.value = false;
}
}
}
}), BorderLayout.SOUTH);
frame.setContentPane(pane);
Rectangle screenBounds = gd.getDefaultConfiguration().getBounds();
frame.setSize(800, 600);
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gd.getDefaultConfiguration());
frame.setLocation(screenBounds.width - frame.getWidth() - screenInsets.right,
screenBounds.height - frame.getHeight() - screenInsets.bottom);
frame.setVisible(true);
}
}
Thoughts? Thanks in advance.

Categories