Stop infinite loop paint() method? Add JButton with paint()? - java

I wrote program to draw wheel (circle with 6 segments) and each segment with different colour. and animate the wheel..
here is the code:
public class ExamWheel extends JFrame implements ActionListener{
JButton b_start = new JButton("Start");
JButton b_stop = new JButton("Stop");
Thread th;
Boolean doDraw = true;
public ExamWheel(){
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("Wheel..");
//add(b_start);
this.setLayout (new FlowLayout());
this.add(b_stop);
b_start.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b_start)
doDraw=true;
}
public void paint(Graphics graphics) {
if (doDraw){
super.paint(graphics);
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
try{
// draw the circle
for(int i=0; ; i=i+1){
g.setColor(Color.CYAN);
g.fillArc(50, 50, 300, 300, i+0, 60);
th.sleep(1);
g.setColor(Color.red);
g.fillArc(50, 50, 300, 300, i+60, 60);
th.sleep(1);
g.setColor(Color.green);
g.fillArc(50, 50, 300, 300, i+120, 60);
th.sleep(1);
g.setColor(Color.blue);
g.fillArc(50, 50, 300, 300, i+180, 60);
th.sleep(1);
g.setColor(Color.gray);
g.fillArc(50, 50, 300, 300, i+240, 60);
th.sleep(1);
g.setColor(Color.pink);
g.fillArc(50, 50, 300, 300, i+300, 60);
th.sleep(1);
}
}
catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
ExamWheel f = new ExamWheel();
}
}
Problems: it is infinite loop, and I can't stop it or close the Frame.
so I had idea:
I created Boolean variable (doDraw) with value true, and add JButton, when click the Button the variable will change to false, and in paint() method I'll use if condition at first of paint()
problem: I can't add JButton to the Frame with paint(), so what can I do?
Note: I tried to use paintComponent() but the loop (for with thread) doesn't work.
IT IS SOLVED
Thanks for Pete Kirham
I added Timer and replaced paint() by paintComponent()
public class ExamWheel extends JPanel implements ActionListener {
int i=0;
Timer tm = new Timer(10, this);
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.CYAN);
g.fillArc(50, 50, 300, 300, i+0, 60);
g.setColor(Color.red);
g.fillArc(50, 50, 300, 300, i+60, 60);
g.setColor(Color.green);
g.fillArc(50, 50, 300, 300, i+120, 60);
g.setColor(Color.blue);
g.fillArc(50, 50, 300, 300, i+180, 60);
g.setColor(Color.gray);
g.fillArc(50, 50, 300, 300, i+240, 60);
g.setColor(Color.pink);
g.fillArc(50, 50, 300, 300, i+300, 60);
tm.start();
}
public void actionPerformed(ActionEvent e) {
i++;
repaint();
}
public static void main(String[] args) {
ExamWheel wh = new ExamWheel();
JFrame jf = new JFrame();
jf.setSize(500,500);
jf.setResizable(false);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setTitle("Wheel..");
jf.add(wh);
}

You need to return from paintComponent to allow the thread which runs the gui to do other stuff, like respond to button events or actually put the contents of the graphics onto the screen.
Use a timer to invalidate the component - see http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html and update the the animation based on the current time, for example current milliseconds modulo 5000 will give a cycle which repeats every five seconds.

Related

Overriding Method with MouseListener

I'm creating a Java program that uses Swing to draw a face, and then I am using MouseListener to respond to mouse clicks to make one of the eyes blink. How would I make one of the eyes blink using MouseListener? The method paint(Graphics g) can only be created once with that name, so if I want to repeat it and edit it under the MouseListener code with one of the eyes turned into a line for blinking, how would I do that?
Here is my code so far:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Sans extends JPanel {
public void paint(Graphics g) {
super.paintComponent(g);
setSize(650, 650);
g.drawOval(110, 250, 500, 275);
g.setColor(new Color(226, 222, 217));
g.fillOval(110, 250, 500, 275);
g.drawOval(475, 300, 75, 75);
g.setColor(new Color(74, 199, 226));
g.fillOval(475, 300, 75, 75);
g.drawOval(505, 330, 15, 15);
g.setColor(new Color(0, 0, 0));
g.fillOval(505, 330, 15, 15);
g.drawOval(175, 300, 75, 75);
g.setColor(new Color(0, 0, 0));
g.fillOval(175, 300, 75, 75);
g.drawOval(205, 330, 15, 15);
g.setColor(new Color(232, 255, 243));
g.fillOval(205, 330, 15, 15);
g.drawOval(350, 375, 20, 50);
g.setColor(new Color(0, 0, 0));
g.fillOval(350, 375, 20, 50);
g.drawArc(290, 360, 150, 150, 180, 180);
g.setColor(new Color(255, 255, 255));
g.fillArc(290, 360, 150, 150, 180, 180);
}
public static void main(String[] args) {
Font font = new Font("TimesRoman", Font.PLAIN, 15);
JFrame frame = new JFrame();
Sans spook = new Sans();
frame.add(spook);
frame.setSize(750, 750);
frame.setTitle("I'VE GOTTEN A TON OF WORK DONE TODAY. A SKELE-TON.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public class BlinkHandler implements MouseListener {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
}

Unable to load a Jbutton to JFrame

I am trying to add a button to my form to bring the user back to the previous screen. I can display the form and drawn objects but unable to get the button to display.
Any help would be greatly appreciated
public static JButton mainMenue = new JButton("Main Menue");
public static void main(String[] args)
{
//creating and setting the values for the Jframe
JFrame form = new JFrame();
Color backColour = new Color(153,153,153);
form.getContentPane().setBackground(backColour);
form.add(mainMenue);
mainMenue.setVisible(true);
mainMenue.setLocation(100,100);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setBounds(30, 30, 1000, 1000);
form.getContentPane().add(new Layout());
form.setVisible(true);
}
#Override
public void paint(Graphics g)
{
//creating the seating
Font titleFont = new Font("Dialog", Font.BOLD, 36);
Font subTitleFont = new Font("Dialog", Font.BOLD, 14);
Graphics2D g2 = (Graphics2D) g;
super.paint(g);
g.setColor(Color.blue);
g.drawLine(225, 60, 255, 60);
g.drawLine(340, 60, 400, 60);
g.drawLine(400, 60, 400, 135);
g.drawLine(400, 135, 650, 135);
g.drawLine(650, 135, 650, 60);
g.drawLine(650, 60, 680, 60);
g.drawLine(765, 60, 825, 60);
g.drawLine(225, 600, 450, 600);
g.drawLine(600, 600, 850, 600);

why when i add a for loop my jframe turns black?

I am trying to make a flashing light in my jframe by creating a list of the colors and then cycling through them with a for loop and then repainting. but when I add a for loop to my code the whole thing bugs out and I get a black screen and it frezzes. Why is this happening?
public class bb {
static Color colors[] = {Color.ORANGE, Color.GRAY};
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(400, 525);
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
JButton smallerButton = new JButton("Flash");
JButton largerButton = new JButton("Steady");
JPanel southPanel = new JPanel();
southPanel.add(smallerButton);
southPanel.add(largerButton);
frame.add(southPanel, BorderLayout.SOUTH);
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(180, 110, 10, 30);
g.drawRect(180, 140, 9, 30);
g.fillRect(180, 170, 10, 30);
g.drawRect(180, 200, 9, 30);
g.fillRect(180, 230, 10, 30);
g.drawRect(180, 260, 9, 30);
g.fillRect(180, 290, 10, 30);
g.drawRect(180, 310, 9, 30);
g.fillRect(180, 340, 10, 30);
int i = 0;
g.setColor(colors[i]);
for(i=0; i <= colors.length; i++){
g.fillOval(160, 70, 50, 50);
if (i ==colors.length){
i=0;
}
frame.repaint();
}
smallerButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals("Flash")){
}
}
});
}
};
frame.add(panel);
frame.validate();
}
}
This statement resets your loop index to 0 causing it to loop indefinitely blocking the EDT
if (i == colors.length) {
i = 0;
}
since you exceed the last array index in the for statement.
Take a look at using a Swing Timer to achieve this functionality.

Creating object of the class with paint method

I created a menu with some options to choose. One of those options is "Play with computer" which starts the game.
JButton ai = new JButton("Play with computer");
ai.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GameBoard play = new GameBoard();
hi.dispose(); //jframe
}
});
And then comes GameBoard:
#SuppressWarnings("serial")
public class GameBoard extends Canvas {
private Image dbi;
private Graphics db;
private JFrame okno;
Rectangle aiPaddle = new Rectangle(10, 590, 10, 50);
Rectangle pPaddle = new Rectangle(10, 100, 10, 50);
Rectangle ball = new Rectangle(560, 10, 10, 10);
Player p = new Player(this);
Ai a = new Ai(this);
Ball b = new Ball(this);
GameBoard() {
okno = new JFrame();
okno.setTitle("Pink Ponk");
okno.setSize(600, 300);
okno.getContentPane().setBackground(Color.black);
okno.setResizable(false);
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(p);
}
public static void main(String[] args) {
GameBoard gra = new GameBoard();
gra.okno.add(gra);
}
#Override
public void update(Graphics g) {
dbi = createImage(10, 50);
db = dbi.getGraphics();
paint(db);
g.clearRect(0, 0, 600, 300);
g.setColor(Color.white);
g.drawRect(p.getX(), p.getY(), 10, 50);
g.fillRect(p.getX(), p.getY(), 10, 50);
g.drawOval(b.getX(), b.getY(), 10, 10);
g.fillOval(b.getX(), b.getY(), 10, 10);
g.drawRect(a.getX(), a.getY(), 10, 50);
g.fillRect(a.getX(), a.getY(), 10, 50);
}
#Override
public void paint(Graphics g) {
pPaddle = new Rectangle(p.getX(), p.getY(), 10, 50);
aiPaddle = new Rectangle(a.getX(), a.getY(), 10, 50);
ball = new Rectangle(b.getX(), b.getY(), 10, 10);
g.clearRect(0, 0, 600, 300);
g.setColor(Color.white);
g.drawRect(p.getX(), p.getY(), 10, 50);
g.fillRect(p.getX(), p.getY(), 10, 50);
g.drawOval(b.getX(), b.getY(), 10, 10);
g.fillOval(b.getX(), b.getY(), 10, 10);
g.drawRect(a.getX(), a.getY(), 10, 50);
g.fillRect(a.getX(), a.getY(), 10, 50);
}
}
I'm sure it should work, but it does not. I'm getting black screen, without any rectangles or ovals. Threads from other classes are working, because I'm still losing the game. :)
The GameBoard constructor, which is the only thing you call when your start button is pressed, creates a new frame, sets its background, and makes it visible. But it doens't add any component to the frame. You probably need to add
okno.add(this);
Note that it's not really the responsibility of the constructor of your Canvas to display a frame and add itself to this frame, though. I would move the frame creation outside of the constructor. Let the constructor do what it's supposed to do: construct the object.

How to make Timer countdown along with progress bar?

How can I make it so that the progress bar slowly goes down with the time limit?
class GamePanel extends JPanel implements MouseListener, ActionListener
{
private JButton quit;
private JButton q;
private Font loadFont;
public GamePanel()
{
setBackground(Color.blue); // sets background color
this.setLayout(null);
quit = new JButton("Quit");
quit.addActionListener(this);
quit.setBounds(550, 700, 100, 30);
this.add(quit);
q = new JButton("Questions");
q.addActionListener(this);
q.setBounds(100, 100, 120, 30);
this.add(q);
loadFont = new Font("Serif", Font.PLAIN, 30);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(80, 100, 610, 560);
g.setColor(Color.white);
g.fillRect(90, 110, 110, 100);// 1st column
g.fillRect(90, 220, 110, 100);//
g.fillRect(90, 330, 110, 100);//
g.fillRect(90, 440, 110, 100);//
g.fillRect(90, 550, 110, 100);//
g.fillRect(210, 110, 110, 100);// 2nd column
g.fillRect(210, 220, 110, 100);//
g.fillRect(210, 330, 110, 100);//
g.fillRect(210, 440, 110, 100);//
g.fillRect(210, 550, 110, 100);//
g.fillRect(330, 110, 110, 100);// 3rd column
g.fillRect(330, 220, 110, 100);//
g.fillRect(330, 330, 110, 100);//
g.fillRect(330, 440, 110, 100);//
g.fillRect(330, 550, 110, 100);//
g.fillRect(450, 110, 110, 100);// 4th column
g.fillRect(450, 220, 110, 100);//
g.fillRect(450, 330, 110, 100);//
g.fillRect(450, 440, 110, 100);//
g.fillRect(450, 550, 110, 100);//
g.fillRect(570, 110, 110, 100);// 5th column
g.fillRect(570, 220, 110, 100);//
g.fillRect(570, 330, 110, 100);//
g.fillRect(570, 440, 110, 100);//
g.fillRect(570, 550, 110, 100);//
g.setColor(Color.green);
g.setFont(loadFont);
g.drawString(input + ":", 100, 710);
}
public void actionPerformed(ActionEvent e)
{
String order = e.getActionCommand();
if(order.equals("Quit"))
cards.show(c, "Introduction");
if(order.equals("Questions"))
cards.show(c, "Questions");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
class QuestionPanel extends JPanel implements ActionListener
{
private long startTime, elapsedTime;
private Timer timer;
private int countdown;
private Font loadFont;
public QuestionPanel()
{
setBackground(Color.pink); // sets background color
this.setLayout(null); // moved into constructor from ActionPerformed: only change layout in constructor
startTime = 0;
elapsedTime = 0;
countdown = 590;
loadFont = new Font("Segoe Script", Font.BOLD, 20);
if(timer == null)
{// use the biggest value possible that provides your desired time keeping precision (usually no less than 15 on Windows)
timer = new Timer(100, this);
startTime = System.currentTimeMillis(); // gets start time in milliseconds
timer.start();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.fillRect(100, 100, 600, 25);
g.setColor(Color.green);
g.fillRect(105, 105, countdown, 15);
g.setColor(Color.black);
g.setFont(loadFont);
g.drawString("" + ((System.currentTimeMillis() - startTime) / 1000.0), 100, 80); // display remaining time
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
elapsedTime = System.currentTimeMillis() - startTime;
if(elapsedTime < (5000))
{
countdown--;
repaint();
}
else
{
timer.stop();
if(timer == null)
{
timer = new Timer(500, this);
timer.start();
}
}
if(elapsedTime >= (5000)) // can't use == here because of limited precision of system clock
cards.show(c, "Correct!");
}
}
class AnswerPanel extends JPanel implements ActionListener
{
private JButton revert;
public AnswerPanel()
{
setBackground(Color.yellow); // sets background color
this.setLayout(null);
revert = new JButton("Back");
revert.addActionListener(this);
revert.setBounds(340, 700, 100, 30);
this.add(revert);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e)
{
String directive = e.getActionCommand();
if(directive.equals("Back"))
cards.show(c, "Start");
}
}
class FailPanel extends JPanel implements ActionListener
{
private JButton turnaround;
public FailPanel()
{
setBackground(Color.green); // sets background color
this.setLayout(null);
turnaround = new JButton("Back");
turnaround.addActionListener(this);
turnaround.setBounds(340, 700, 100, 30);
this.add(turnaround);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e)
{
String bidding = e.getActionCommand();
if(bidding.equals("Back"))
cards.show(c, "Start");
}
}
}// end of the entire program
Sorry, I still could not find the motivation to actually read your code, but just threw together this example based on the question. See if it gives you some ideas.
Note that it is an SSCCE and uses just 40 lines of code in all.
import java.awt.event.*;
import javax.swing.*;
class CountDownProgressBar {
Timer timer;
JProgressBar progressBar;
CountDownProgressBar() {
progressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 10);
progressBar.setValue(10);
ActionListener listener = new ActionListener() {
int counter = 10;
public void actionPerformed(ActionEvent ae) {
counter--;
progressBar.setValue(counter);
if (counter<1) {
JOptionPane.showMessageDialog(null, "Kaboom!");
timer.stop();
}
}
};
timer = new Timer(1000, listener);
timer.start();
JOptionPane.showMessageDialog(null, progressBar);
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
CountDownProgressBar cdpb = new CountDownProgressBar();
}
});
}
}
From the looks of it, all of this code is within a big Java file? That is a bad idea.
You should have a good reason to define a class as an inner class, and from the looks of it, you do not have one for QuestionPanel and others.
As for the problem, your paintComponent method is called every time your counter is updated, which is right now roughly once every 0.1 seconds, yet you only tick by 1 pixel on each update, so by the end of 5 seconds, you've cut off 10*5 pixels (50). What you should do is update the progress bar by a different mechanism, such as a calculating the current time processed:
long processed = System.currentTimeMillis() - startTime;
double percent = Math.max(0, 1 - processed / 5000.0);
int width = (int)(590 * percent);
That is definitely too much information, and a very broad question. I'd say at most you only need to include the code for the class where the timer is, and the class where the progress bar gets drawn.
From skimming the code, I'm guessing you're using a rectangle to draw the progress bar. Based on that, one way you could go about it would be using a variable to store the width of the bar, and every time the timer ticks, decrease the width of the bar by a set amount. Then just set the width of the rectangle drawn to the value stored in the variable.

Categories