60 322
Assignments Done
98%
Successfully Done
In April 2018

Answer to Question #6690 in Java | JSP | JSF for Joe

Question #6690
Building a GRect program in java, it creates rectangle and then allows user to enter a new height of the rectangle. When the program runs the rectangle starts at the bottom left of the screen which it should but when user enters new height the program flips the rectangle to the top of screen and the rectangle grows down the screen, any help?
Expert's answer
package grect;
import java.awt.Container;
import
java.awt.Dimension;
import java.awt.Graphics;
import
java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import
java.awt.event.WindowAdapter;
import
java.awt.event.WindowEvent;

import javax.swing.JButton;
import
javax.swing.JFrame;
import javax.swing.JPanel;

public class Main
{
public static void main(String[] args) {
JFrame frame = new
BounceThreadFrame();
frame.show();
}
}
final class BounceThreadFrame
extends JFrame {

public BounceThreadFrame() {
setSize(300,
200);
setTitle("Bounce");
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Container contentPane =
getContentPane();
canvas = new JPanel();
contentPane.add(canvas,
"Center");
JPanel p = new JPanel();
addButton(p, "Start", new
ActionListener() {
public void actionPerformed(ActionEvent evt) {
Rect b =
new Rect(canvas);
b.start();
}
});
addButton(p, "Close", new
ActionListener() {
public void actionPerformed(ActionEvent evt)
{
canvas.setVisible(false);
System.exit(0);
}
});
contentPane.add(p,
"South");
}
public void addButton(Container c, String title,
ActionListener a) {
JButton b = new
JButton(title);
c.add(b);
b.addActionListener(a);
}
private JPanel
canvas;
}
class Rect extends Thread {
public Rect(JPanel b) {
box =
b;
}
public void move() {
if (!box.isVisible())
return;
Graphics
g = box.getGraphics();
g.setXORMode(box.getBackground());
g.drawRect(x, y,
XSIZE, YSIZE);
y += dy;
g.drawRect(x, y, XSIZE,
YSIZE);
g.dispose();
}
@Override
public void run() {
try
{
x=0;
y=0;
for (int i = 1; i <= 1000; i++)
{
move();
sleep(30);
}
} catch (InterruptedException e)
{
}
}
private JPanel box;
private static int XSIZE = 10;
private
static int YSIZE = 10;
private int x = 0;
private int y = 120;
private
int dy = 2;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions