How to decrease a height of a rectangle? (Java, AWT) - java

I'm beginner in Java. So, please help me with my problem.
I can do animation when a rectangle's height increases. But I have problem with decreasing rectangle's height. Please look at this code:
public class Animation extends JPanel implements ActionListener {
Timer timer;
int i = 100;
public Animation() {
timer = new Timer(10, this);
timer.start();
}
public void paint(Graphics g) {
Graphics2D g2d1 = (Graphics2D) g;
g2d1.fillRect(0, 100, 30, i);
}
public static void main(String[] args) {
JFrame frame = new JFrame("animation");
frame.add(new Animation());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
--i;
repaint();
}
}
Please help me.
Best regards
Pawel

It isn't clearing the screen between draws, so it draws over the old larger rectangle.
Try this:
public void paint(Graphics g) {
Graphics2D g2d1 = (Graphics2D) g;
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight()); // draw a rectangle over the display area in the bg color
g.setColor(Color.BLACK);
g2d1.fillRect(0, 100, 30, i);
}
Or:
public void paint(Graphics g) {
super.paint(g); // call superclass method, which does clear the screen
Graphics2D g2d1 = (Graphics2D) g;
g2d1.fillRect(0, 100, 30, i);
}
And as camickr pointed out below, custom painting should be done in paintComponent not paint, so you should change the name of the method to paintComponent.

Related

I can't draw to a JPanel

I am trying to use JPanel to draw to a window, but nothing shows up.
I've tried looking online, but I couldn't find anything.
private void initialize()
{
_frame = new JFrame(_name);
_panel = new JPanel();
_frame.setSize(_scaledSize);
_frame.setLocationRelativeTo(null);
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_frame.setResizable(true);
_panel.setPreferredSize(_scaledSize);
_panel.setMinimumSize(_scaledSize);
_panel.setMaximumSize(_scaledSize);
_frame.getContentPane().add(_panel);
_frame.pack();
_frame.setVisible(true);
}
public JPanel getPanel()
{
return _panel;
}
Method that is responible for drawing
public void draw()
{
Graphics graphics;
graphics = _display.getPanel().getGraphics();
graphics.setColor(Color.black);
graphics.drawRect(20, 20, 100, 100);
}
It shows a blank screen... nothing is drawn.
To draw to a JPanel set its layout to null _panel.setLayout(null); (If you want to add multiple shapes).Set it to _panel.setLayout(new CardLayout (if you want to add Only 1 Shape).
Hence Your main method will becomes *NB Shape is the panel that we are going to draw
Shape shape = new Shape();
shape.setSize(new Dimension(150, 150));
shape.setPreferredSize(new Dimension(150, 150));
_panel.add(shape).setLocation(0, 0);
Shape code will then become
class Shape extends JPanel {
public GeneralPath getShape() {
GeneralPath path = new GeneralPath();
path.moveTo(20, 20);
path.lineTo(20, 40);
path.lineTo(40,40);
path.lineTo(40,20);
path.closePath();
return path;
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
GeneralPath pt = getShape();
g2d.scale(2, 2);
g2d.draw(pt);
}
}

Drawing a simple circle with Java swing does not work

I think I am missing something really obvious but somehow this code does give me an empty window but it does not paint the red oval. What am I missing?
public class Test extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
g = this.getGraphics();
Graphics2D g2 = (Graphics2D) g;
// Anti-aliasing
g2.setColor(new Color(255, 0, 0));
g2.fillOval(0, 0, 20, 20);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Ball");
Test panel = new Test();
frame.getContentPane().add(panel);
frame.setPreferredSize(new Dimension(250, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
the paintComponent is not correct, remove this g = this.getGraphics();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
Ellipse2D.Double circle = new Ellipse2D.Double(xR, yR, diameter, diameter);
g2d.fill(circle);
...
}

Change rectangle color in Java GUI

How to change the color of rectangle ? I want change it to yellow color. I added g.setColor(Color.YELLOW); inside rectDraw, but the color of the rectangle still remain the same. Can someone tell me what wrong I did please?
public class SelectSeat {
static JFrame frame;
public JPanel createContentPane() throws IOException
{
JPanel totalGUI = new JPanel();
RectDraw rect= new RectDraw();
rect.setPreferredSize(new Dimension(330,35)); //for size
totalGUI.setLayout(null);
totalGUI.setBackground(Color.WHITE);
totalGUI.add(rect);
Dimension d = rect.getPreferredSize();
rect.setBounds(100, 20, d.width, d.height); // for location
return totalGUI;
}
void setVisible(boolean b) {
// TODO Auto-generated method stub
}
static void createAndShowGUI() throws IOException
{
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Seat Selection");
//Create and set up the content pane.
SelectSeat demo = new SelectSeat();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(535, 520);
frame.setLocation(500,220);
frame.setVisible(true);
}
private static class RectDraw extends JPanel
{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawString("Movie Sceen", 130, 20);
}
}
}
How to change the color of rectangle ? I want change it to yellow color.
You need to set the color to yellow, followed by filling a rectangle the size of the component.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(0,0,getWidth(), getHeight());
g.setColor(Color.BLUE);
g.drawString("Movie Sceen", 130, 20);
}
And for what its worth:
totalGUI.setLayout(null);
I would recommend against using null Layouts. Use a LayoutManager appropriate to the task, and remember that you can nest layouts within the Component hierarchy.

JSlider not adjusting shape size

I'm testing a program that uses a JSlider to adjust the width of a circle, and the value of the slider is working, but its not actually changing the 'width' variable. Please help!!! Here is what I have so far:
public class SliderTest extends JFrame{
private static DrawShape circle = new DrawShape();
JSlider slider;
JLabel label;
public SliderTest() {
setLayout(new FlowLayout());
slider = new JSlider(JSlider.HORIZONTAL, 150, 450, 300);//orientation, min val, max value, starting val
slider.setMajorTickSpacing(50);//every 5 integers will be a new tick position
slider.setPaintTicks(true);
add(slider);
label = new JLabel("Current value 300");
add(label);
event e = new event();
slider.addChangeListener(e);;
}//end cons
public class event implements ChangeListener{
public void stateChanged(ChangeEvent e) {
JSlider slider = (JSlider)e.getSource();
int value = slider.getValue();
label.setText("Current Value " + value);
circle.setWidth(value);
repaint();
}//end stateChanged
}//end class event
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Circle");
frame.add(circle);
frame.setSize(500,400);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JFrame frame1 = new SliderTest ();
frame1.setTitle("Toolbar");
frame1.setSize(300,200);
frame1.setLocation(200,100);
frame1.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame1.setVisible(true);
}
}
The other class:
public class DrawShape extends JPanel{
private float width = 300;
private Ellipse2D circle = new Ellipse2D.Float(100, 20, 300, 300);
public DrawShape() {
}
public DrawShape(float width) {
circle.setFrame(100, 20, width, 300);
}
public void setWidth(int w) {
this.width = w;
circle.setFrame(100, 20, w, 300);
revalidate();
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = circle.getBounds().width;
return size;
}
public void paintComponent (Graphics g) {
super.paintComponents(g);
Graphics2D graphics = (Graphics2D)g;
graphics.setColor(Color.black);
graphics.fill(circle);
}//end paintComponent
}//end class
Two (major) issues popup.
Firstly, in your event handler, you're repainting the slider frame, which isn't going to help, so it your setWidth you should add a repaint request, for example.
public void setWidth(int w) {
System.out.println("setWidth " + w);
this.width = w;
circle.setFrame(100, 20, w, 300);
revalidate();
repaint();
}
Secondly, you all calling super.paintComponents (note the s at the end) instead of super.paintComponent, for example...
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.black);
g2d.fill(circle);
}//end paintComponent
This will cause you a significant amount of grieve with strange paint artifacts...

Pause before painting the panel in Java

I am trying to slow down the painting by adding a pause between two consecutive paints. Thread.sleep() apparently doesn't work. Here is the code:
import javax.swing.*;
import java.awt.*;
public class Sa {
int x = 70;
int y = 70;
public static void main(String[] args) {
Sa gui = new Sa();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
for(int i=0; i<130; i++) {
x++;
y++;
drawPanel.repaint();
try {
Thread.sleep(1500);
} catch(Exception ex) {}
}
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
Thread.sleep(1500); // will not work!!
g.setColor(Color.green);
g.fillOval(x, y, 80, 40);
}
}
}
Remove Thread.sleep() inside paint() method, not need it, and second, you Thread.sleep() needs to be caught InterruptedException, it may give an error while compiling:
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//Thread.sleep(1500); // will not work!! (DONT NEED this
g.setColor(Color.green);
g.fillOval(x, y, 80, 40);
Have you looked at Swing Timer ?

Categories

Resources