Repaint through ActionListener not getting executed - java

I have tried reading similar questions on stack overflow, but I am not able to get a concrete solution. So, I am posting it back. I am calling repaint on the click of a button. As in paint function, I draw the objects randomly. I suppose they should move, when I click the button. But, nothing happens when I click the button.
Does anybody knows why such a behavior is happening and how to solve this?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
#SuppressWarnings("serial")
public class Filter extends JFrame
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Filter mainFrame = new Filter();
mainFrame.setVisible(true);
}
});
}
public Filter()
{
//Creating the JFrame main window
setSize(800, 500);
setTitle("Particle Filter");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocation(100, 100);
getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.X_AXIS));
//creates two panels content and sidebar. Sidebar has null layout
JPanel content = new JPanel();
content.setPreferredSize(new Dimension(700,500));
content.setBackground(Color.LIGHT_GRAY);
this.getContentPane().add(content);
JPanel sidebar = new JPanel();
sidebar.setBackground(Color.LIGHT_GRAY);
sidebar.setPreferredSize(new Dimension(100,500));
this.getContentPane().add(sidebar);
sidebar.setLayout(null);
//creates three buttons in sidebar
JButton start_button = new JButton("START");
start_button.setBounds(10, 75, 77, 23);
start_button.addActionListener(new MainPanel());
sidebar.add(start_button);
JButton stop_button = new JButton("STOP");
stop_button.setBounds(10, 109, 77, 23);
sidebar.add(stop_button);
JButton reset_button = new JButton("RESET");
reset_button.setBounds(10, 381, 77, 23);
sidebar.add(reset_button);
//calls the content_Walls class and sends the number of ovals to be generated
content.add( new MainPanel());
}
}
#SuppressWarnings("serial")
class MainPanel extends JPanel implements ActionListener
{
public MainPanel()
{
setPreferredSize(new Dimension(680,450));
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.black));
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("start_button"))
repaint();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawParticles(g);
createObstacles(g,150,225,100,40);
createObstacles(g,500,300,40,100);
createRobot(g);
}
private void createRobot(Graphics g)
{
int x=0, y=0;
int robot_radius=50;
ArrayList<Integer> robot_list= new ArrayList<Integer>();
robot_list=positionRobot(x,y);
drawRobot(g,robot_list.get(0),robot_list.get(1),robot_radius);
}
private void drawParticles(Graphics g)
{
int n=1000; // n denotes the number of particles
ArrayList<Integer> list;
list = new ArrayList<Integer>(Collections.nCopies(n, 0));
for(int i=0;i<list.size();i++)
{
generateParticles(g);
}
}
private void generateParticles(Graphics g)
{
int x=0;
int y=0;
int radius = 4;
ArrayList<Integer> list= new ArrayList<Integer>();
list=positionParticles(x,y);
g.setColor(Color.RED);
g.fillOval(list.get(0),list.get(1), radius, radius);
}
private ArrayList<Integer> positionParticles(int x, int y)
{
int radius = 4;
ArrayList<Integer> list= new ArrayList<Integer>();
x=randomInteger(2,678); // bounds of x between which the particles should be generated
y=randomInteger(2,448); // bounds of y between which the particles should be generated
x=x-(radius/2);
y=y-(radius/2);
if((x<251&&x>=150)&&(y<266&&y>=225))
{
x=0;
y=0;
positionParticles(x,y);
}
if((x<541&&x>499)&&(y<401&&y>299))
{
x=0;
y=0;
positionParticles(x,y);
}
list.add(x);
list.add(y);
return list;
}
private ArrayList<Integer> positionRobot(int x, int y)
{
int robot_radius=50;
ArrayList<Integer> list= new ArrayList<Integer>();
x=randomInteger(25,655);//so that it stays inside the content_Walls panel
y=randomInteger(25,425); //so that it stays inside the content_Walls panel
x=x-(robot_radius/2);
y=y-(robot_radius/2);
if((x<250&&x>=150)||(y<=265&&y>=225))
{
x=0;
y=0;
positionRobot(x,y);
}
if((x<=540&&x>=500)||(y<=400&&y>=300))
{
x=0;
y=0;
positionRobot(x,y);
}
list.add(x);
list.add(y);
return list;
}
private void createObstacles(Graphics g, int x, int y, int width, int height)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, width, height);
}
private void drawRobot(Graphics g, int x, int y, int radius)
{
g.setColor(Color.GREEN);
g.fillOval(x, y, radius, radius);
}
private static int randomInteger(int min, int max)
{
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}

e.getActionCommand() return "START" so you have to change:
if (e.getActionCommand().equals("start_button"))
TO
if (e.getActionCommand().equals("START"))
Your second problem is, that you work with two different Mainpanel. Create an instance of Mainpanel and use this in start_button.addActionListener(mainPanel) and content.add(mainPanel);

Related

Swing draws only after resizing

Program should draw the line twice longer after clicking the button, but it only does that after clicking AND THEN resizing the window. I don't know what is happening, i thought this is gonna be easy.
Could you tell me how can I fix it?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Random;
import java.util.Stack;
class MyButtonPanel extends JPanel {
public static final int HEIGHT = 800;
public static final int WIDTH = 800;
private JButton greenButton;
private JPanel buttonPanel;
Stack<Point> points;
int X = 25;
int Y = 25;
public MyButtonPanel() {
greenButton = new GreenButton();
points = new Stack<Point>();
buttonPanel = this;
setLayout(new FlowLayout());
setPreferredSize(new Dimension(WIDTH, HEIGHT));
add(greenButton);
}
class GreenButton extends JButton implements ActionListener
{
GreenButton() {
super("LongerLine");
addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
//points.push(new Point(0,0));
X = 2 * X;
Y = 2 * Y;
validate();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
//g2d.setColor(Color.WHITE);
//g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.setColor(Color.BLACK);
//drawLines(g2d);
Line2D lin = new Line2D.Double(0,0, X, Y);
g2d.draw(lin);
}
private void drawLines(Graphics2D g2d) {
//Line2D lin = new Line2D.Float(100, 100, 250, 260);
//g2d.draw(lin);
double x1, y1, x2, y2;
/*
for(Point point: points) {
x1 = (double) point.getX();
y1 = (double) point.getY();
Line2D line = new Line2D.Double(x1,y1,200,200);
g2d.draw(line);
}
*/
}
}
public class MyActionFrame extends JFrame {
public MyActionFrame() {
super("Test akcji");
JPanel buttonPanel = new MyButtonPanel();
add(buttonPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
//setResizable(false);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MyActionFrame();
}
});
}
}
This validate();, or better revalidate(); is called when a container's layout needs to be re-done, often when components are added or removed, and is not what you're doing or desiring. Instead you want to call repaint() which suggests that the component be painted.

Extra dummy components painted during thread execution

In a Java applet, I'm trying to slow down the painting of an image made up of parts, so I wrote a test program to get the basic concept working. I'm using a thread to draw a number of boxes one at a time instead of a timer because I want to be able to click the go button to reset the drawing process at any time.
The problem is, after drawing a box, it moves down a bit and an extra of the label shows up at the top of the screen. When the mouse moves off the button at the bottom, a dummy button also shows up at the top of the screen. The dummy button doesn't respond to clicks (only the real one at the bottom does), it's just there.
I'm still pretty new at this, so any help would be greatly appreciated.
Here's the JApplet class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestDraw extends JApplet implements ActionListener
{
private DrawPanel panel;
private JLabel lbl1;
JButton go;
Thread t;
public void init()
{
lbl1 = new JLabel("hi");
go = new JButton("GO");
go.addActionListener(this);
panel = new DrawPanel();
getContentPane().setBackground(Color.yellow);
add(lbl1, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(go, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae){
// tried adding these. didnt help
//panel.validate();
//panel.repaint();
//validate();
panel.resetBoxes();
repaint();
}
public void start(){
t = new Thread(panel);
t.start();
}
}
Here's the DrawPanel Class:
import java.awt.*;
import java.security.SecureRandom;
import javax.swing.*;
public class DrawPanel extends JPanel implements Runnable
{
private SecureRandom randGen = new SecureRandom();
private Box[] boxes;
private int box2draw = 0;
public DrawPanel()
{
setBackground(Color.WHITE);
boxes = new Box[5];
for (int count = 0; count < boxes.length; count++){
int x = randGen.nextInt(300);
int y = randGen.nextInt(300);
int w = randGen.nextInt(300);
int h = randGen.nextInt(300);
Color color = new Color(randGen.nextInt(256), randGen.nextInt(256), randGen.nextInt(256));
boxes[count] = new Box(x,y,w,h,color);
}
}
public void paintComponent(Graphics g)
{
boxes[box2draw].draw(g);
box2draw++;
}
public void resetBoxes(){
boxes = new Box[5];
for (int count = 0; count < boxes.length; count++){
int x = randGen.nextInt(300);
int y = randGen.nextInt(300);
int w = randGen.nextInt(300);
int h = randGen.nextInt(300);
Color color = new Color(randGen.nextInt(256), randGen.nextInt(256), randGen.nextInt(256));
boxes[count] = new Box(x,y,w,h,color);
box2draw = 0;
}
}
public void run(){
while(true){
try{
Thread.sleep(750);
}
catch(InterruptedException e){
JOptionPane.showMessageDialog(null, "interrupted");
}
repaint();
}
}
}
And finally, the Box class:
import java.awt.Color;
import java.awt.Graphics;
public class Box
{
private int x;
private int y;
private int w;
private int h;
private Color color;
public Box(int x,int y,int w,int h,Color color)
{
// initialise instance variables
this.x = x;
this.y=y;
this.w=w;
this.h = h;
this.color=color;
}
public void draw(Graphics g)
{
g.setColor(color);
g.drawRect( x, y, w, h);
}
}
Thank you for your time!
Problems:
You've got code logic within a painting method -- something that you should never do -- including your incrementing an array index. You don't have full control of when or even if this method is called and so program logic does not belong there, just painting. If you need to increment your array index, do it elsewhere, perhaps within your thread's while (true) loop. Also take care not to have the index go beyond the size of the array.
You never call the super's paintComponent method within your override, and this will prevent the component from doing housekeeping painting, probably your main problem.
If you need to display multiple items, then consider either drawing to a BufferedImage and displaying that within paintComponent, or creating a collection of Shape objects and drawing all of them within paintComponent via a for-loop.
I prefer to use the Swing-safer Swing Timer. While it doesn't matter if only calling repaint() if you want to make any other Swing calls intermittently, it makes life much easier and coding safer.
For example
package foo1;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TestDraw2 {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final DrawPanel2 drawPanel = new DrawPanel2();
JButton drawButton = new JButton(new AbstractAction("Draw!") {
#Override
public void actionPerformed(ActionEvent e) {
drawPanel.resetBoxes();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(drawButton);
JFrame frame = new JFrame("TestDraw2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(drawPanel);
frame.getContentPane().add(btnPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class DrawPanel2 extends JPanel {
private static final int BOX_COUNT = 5;
private static final int TIMER_DELAY = 750;
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private Random randGen = new Random();
private Box[] boxes;
private int box2draw = 0;
public DrawPanel2() {
setBackground(Color.YELLOW);
boxes = new Box[BOX_COUNT];
for (int count = 0; count < boxes.length; count++) {
int x = randGen.nextInt(300);
int y = randGen.nextInt(300);
int w = randGen.nextInt(300);
int h = randGen.nextInt(300);
Color color = new Color(randGen.nextInt(256), randGen.nextInt(256),
randGen.nextInt(256));
boxes[count] = new Box(x, y, w, h, color);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < box2draw; i++) {
boxes[i].draw(g);
}
}
public void resetBoxes() {
boxes = new Box[BOX_COUNT];
for (int count = 0; count < boxes.length; count++) {
int x = randGen.nextInt(300);
int y = randGen.nextInt(300);
int w = randGen.nextInt(300);
int h = randGen.nextInt(300);
Color color = new Color(randGen.nextInt(256), randGen.nextInt(256),
randGen.nextInt(256));
boxes[count] = new Box(x, y, w, h, color);
box2draw = 0;
}
repaint();
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
box2draw++;
if (box2draw > BOX_COUNT) {
box2draw = BOX_COUNT;
((Timer) e.getSource()).stop();
}
repaint();
}
}).start();
}
}

Java Animation with ActionListener

So I'm trying to draw 2 circles on top of each other (kinda like a snowman) and move the snowman to the right when the user clicks on the "Start" button and stop moving the snowman when the user clicks on the "Stop" button. However, the only thing that I am able to come up with is 2 snowmen drawn next to each other that don't react to the buttons.
Here is what I've come up with:
import java.awt.Graphics2D;
public interface MoveableShape {
void draw(Graphics2D g);
void translate(int dx, int dy);
}
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
public class SnowmanShape implements MoveableShape {
private int x;
private int y;
private int width;
public SnowmanShape(int x, int y, int width){
this.x = x;
this.y = y;
this.width = width;
}
#Override
public void draw(Graphics2D g2) {
// TODO Auto-generated method stub
Ellipse2D.Double head = new Ellipse2D.Double(0, 0, 10, 10);
Ellipse2D.Double body = new Ellipse2D.Double(0, 11, 10, 10);
g2.draw(head);
g2.draw(body);
}
#Override
public void translate(int dx, int dy) {
// TODO Auto-generated method stub
x += dx;
y += dy;
}
}
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class MyPanel extends JPanel{
MoveableShape s;
public MyPanel (MoveableShape m){
s = m;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
s.draw((Graphics2D)g);
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AnimationTester {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 200;
private static final int SNOWMAN_WIDTH = 50;
final static MoveableShape shape = new SnowmanShape(0, 0, SNOWMAN_WIDTH);
final static JPanel panel = new MyPanel(shape);
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
frame.setLayout(new BorderLayout());
frame.add(panel);
frame.add(startButton, BorderLayout.NORTH);
frame.add(stopButton, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
final int DELAY = 100;
// Milliseconds between timer ticks
Timer t = new Timer(DELAY, translateSnowman());
startButton.addActionListener(startTimer(t));
stopButton.addActionListener(stopTimer(t));
}
public static ActionListener translateSnowman(){
return new ActionListener(){
public void actionPerformed(ActionEvent event){
shape.translate(1, 0);
panel.repaint();
}
};
}
public static ActionListener startTimer(final Timer t){
return new ActionListener(){
public void actionPerformed(ActionEvent event){
t.start();
}
};
}
public static ActionListener stopTimer(final Timer t){
return new ActionListener(){
public void actionPerformed(ActionEvent event){
t.stop();
}
};
}
}
Could someone please let me know where I went wrong or point me in the right direction?
EDIT: I fixed up the AnimationListener so now it doesn't draw 2 snowmans. The snowman still won't move however. I updated the code in the post as well.
Add g2.translate(x, y); to SnowmanShape#draw, before you are painting:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
class SnowmanShape implements MoveableShape {
static final Color headColor = new Color(0xFFE9C9);
static final Color bodyColor = new Color(0xEAF6FF);
static final Color outlineColor = new Color(0x252525);
int x;
int y;
int size;
Ellipse2D.Double head;
Ellipse2D.Double body;
SnowmanShape(int x, int y, int size) {
this.x = x;
this.y = y;
this.size = size;
initModel();
}
void initModel() {
head = new Ellipse2D.Double(0, 0, size, size);
body = new Ellipse2D.Double(0, head.height, size * 1.3d, size * 1.5d);
body.x -= (body.width - head.width) * (1 / 2d);
}
#Override
public void draw(Graphics2D g2) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.translate(x, y);
g2.setColor(headColor);
g2.fill(head);
g2.setColor(outlineColor);
g2.draw(head);
g2.setColor(bodyColor);
g2.fill(body);
g2.setColor(outlineColor);
g2.draw(body);
}
#Override
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
}
I not an expert on doing things like this, but if I were you I would use the timer to move the objects and then call the paint to repaint the objects in a new position. Therefore, your ShapeIcon class would just keep track of the position of your objects. That probably wasn't all that helpful, so to point you in right direction, you can check out some code in this tutorial here.

Using a GUI to input then draw several shapes

I'm trying to create a GUI that allows the user to input a number, then the GUI creates an array of Points of that size, then draws that number of circles. However, when I run this code, the GUI only displays a black panel and using a system.out.println it says that the number in the JTextField never reaches the panel. How can I alter my code so that the user can input a number in the textfield, press enter, then the GUI draws that number of circles?
import java.awt.BorderLayout;
import java.awt.Color;
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.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class ControlPanel extends JPanel{
JLabel inLabel;
JTextField inText;
public ControlPanel(){
setBackground(Color.lightGray);
inLabel = new JLabel("Enter the number of points: ");
inText = new JTextField(20);
add(inLabel);
add(inText);
}
public JTextField getInText(){
return inText;
}
public int getNPoints(){
int nP = Integer.parseInt(inText.getText());
return nP;
}
}
class PiPanel2 extends JPanel{
private Point[] points;
int nPoints;
Dimension d = new Dimension();
private int X = d.width;
private int Y = d.height;
private int w = 5;
private int h = 5;
public PiPanel2(){
setBackground(Color.BLACK);
}
public void setNPoints(int nPoints){
this.nPoints = nPoints;
}
public int getNP(){
return nPoints;
}
public void paintComponent(Graphics g){
int n = getNP();
points = new Point[n];
System.out.println(n);
for(int i = 0; i < n; i++){
points[i] = new Point(Math.random(), Math.random());
}
g.setColor(getBackground());
super.paintComponent(g);
g.setColor(Color.red);
g.drawOval(-X, -Y, X*2, Y*2);
for(int i = 0; i < points.length; i++){
int x = (int)(points[i].getX()*X);
int y = (int)(points[i].getY()*Y);
if(points[i].withinR()){
g.setColor(Color.blue);
g.fillOval(x, y, w, h);
}else if(!points[i].withinR()){
g.setColor(Color.orange);
g.fillOval(x, y, w, h);
}
}
}
}
class PiFrame2 extends JFrame implements ActionListener{
private int X = 600;
private int Y = 600;
ControlPanel control;
PiPanel2 piPan;
public PiFrame2(){
control = new ControlPanel();
piPan = new PiPanel2();
control.getInText().addActionListener(this);
setLayout(new BorderLayout());
// and add the panels to the frame
getContentPane().add(control, BorderLayout.SOUTH);
getContentPane().add(piPan, BorderLayout.CENTER);
// this code enables you to close the window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(X,Y);
setLocation(500,0);
}
public void actionPerformed(ActionEvent e) {
int nPoints = control.getNPoints();
piPan.setNPoints(nPoints);
}
}

Draw a rectangle with the corresponding size taken from a TextField

I have got a program where someone enters a width and a length and it draws the corresponding size on a dialog.
The Scenario
Here is what happens. I start it up,
Then I press go:
And the dialogue comes up with nothing.
The code
So here is the event handling code:
public void actionPerformed(ActionEvent e){
d.init();
}
d is the class that shows the dialogue. I didn't think I would show it but all the init does is add a DrawRectangle panel to it (this is the DrawRectangle` class):
import java.awt.*;
import javax.swing.*;
public class DrawRectangle extends JPanel{
int x = 100;
int y = 50;
int h;
int w ;
private void Dodrawing(Graphics g, int w, int h, int x, int y){
g2d.fillRect(x, y, w, h);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
//Graphics, width, heigth, x coordinate, y coordinate
Dodrawing(g, w, h, x, y);
}
}
The question
Can I change the value of h and w to the values in the textfield and then update the drawing?
Edit
Here is an SSCCE:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Area;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SSCCE extends JFrame implements ActionListener{
//Variable declaration
JLabel LengthLabel = new JLabel("Length");
JLabel WidthLabel = new JLabel("Width");
JLabel Area = new JLabel ();
JLabel Perimeter = new JLabel ();
JLabel Volume = new JLabel();
JTextField Length = new JTextField();
JTextField Width = new JTextField();
int LengthInt;
int WidthInt;
String LengthStr;
String WidthStr;
JDialog dialog;
Color darkGreen = new Color(50, 150, 50);
JButton close = new JButton("Close");
boolean visi = true;
JButton go = new JButton("Go");
public SSCCE(){
super("Geometry");
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(20 , 10);
setLayout(grid);
add(LengthLabel);
add(Length);
add(WidthLabel);
add(Width);
add(go);
add(Area);
add(Perimeter);
go.addActionListener(this);
setVisible(true);
}
JPanel p = new JPanel();
int x = 100;
int y = 50;
int h ;
int w ;
private void Dodrawing(Graphics g, int w, int h, int x, int y){
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(x, y, w, h);
}
protected void paintComponent(Graphics g)
{
p.paintComponents(g);
//Graphics, width, heigth, x coordinate, y coordinate
Dodrawing(g, w, h, x, y);
}
//Action Peformed method
public void actionPerformed(ActionEvent e){
//Getting the text from the input fields
LengthStr = Length.getText().toString();
WidthStr = Width.getText().toString();
try{
LengthInt = Integer.parseInt(LengthStr);
WidthInt = Integer.parseInt(WidthStr);
init();
}catch(Exception event){
System.out.println(event);
}
}
protected void init() {
dialog = new JDialog(this, "Copie", true);
dialog.setResizable(false);
dialog.add(p);
dialog.pack();
dialog.setSize(300, 200);
Dimension Size = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(new Double((Size.getWidth()/2) - (dialog.getWidth()/2)).intValue(), new Double((Size.getHeight()/2) - (dialog.getHeight()/2)).intValue());
dialog.setVisible(visi);
}
protected void close() {
this.dialog.dispose();
this.dialog.setVisible(false);
}
public static void main(String[] args){
SSCCE ge = new SSCCE();
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Area;
import javax.swing.*;
public class SSCCE extends JFrame implements ActionListener {
//Variable declaration
JLabel LengthLabel = new JLabel("Length");
JLabel WidthLabel = new JLabel("Width");
JLabel Area = new JLabel();
JLabel Perimeter = new JLabel();
JLabel Volume = new JLabel();
JTextField Length = new JTextField();
JTextField Width = new JTextField();
int LengthInt;
int WidthInt;
String LengthStr;
String WidthStr;
JDialog dialog;
Color darkGreen = new Color(50, 150, 50);
JButton close = new JButton("Close");
boolean visi = true;
JButton go = new JButton("Go");
public SSCCE() {
super("Geometry");
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(20, 10);
setLayout(grid);
add(LengthLabel);
add(Length);
add(WidthLabel);
add(Width);
add(go);
add(Area);
add(Perimeter);
go.addActionListener(this);
setVisible(true);
}
JPanel p = new JPanel();
int x = 100;
int y = 50;
int h;
int w;
private void Dodrawing(Graphics g, int w, int h, int x, int y) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(x, y, w, h);
}
protected void paintComponent(Graphics g) {
p.paintComponents(g);
//Graphics, width, heigth, x coordinate, y coordinate
Dodrawing(g, w, h, x, y);
}
//Action Peformed method
public void actionPerformed(ActionEvent e) {
//Getting the text from the input fields
LengthStr = Length.getText().toString();
WidthStr = Width.getText().toString();
try {
LengthInt = Integer.parseInt(LengthStr);
WidthInt = Integer.parseInt(WidthStr);
init();
} catch (Exception event) {
System.out.println(event);
}
}
protected void init() {
dialog = new JDialog(this, "Copie", true);
dialog.setResizable(false);
dialog.add(p);
dialog.pack();
Dimension Size = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(new Double((Size.getWidth() / 2) - (dialog.getWidth() / 2)).intValue(), new Double((Size.getHeight() / 2) - (dialog.getHeight() / 2)).intValue());
dialog.setLayout(new BorderLayout());
dialog.add(new DrawRectangle(WidthInt, LengthInt));
dialog.pack();
dialog.setSize(300, 200);
dialog.setVisible(visi);
}
protected void close() {
this.dialog.dispose();
this.dialog.setVisible(false);
}
public static void main(String[] args) {
SSCCE ge = new SSCCE();
}
}
class DrawRectangle extends JPanel {
int x = 100;
int y = 50;
int h = 100;
int w = 100;
DrawRectangle(int w, int h) {
this.w = w;
this.h = h;
}
private void Dodrawing(Graphics g, int w, int h, int x, int y) {
g.setColor(Color.RED);
g.fillRect(x, y, w, h);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paintComponent");
//Graphics, width, heigth, x coordinate, y coordinate
Dodrawing(g, w, h, x, y);
}
}
Other tips
Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow.
A single blank line of white space in source code is always enough.
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use them consistently.
Don't set the size of top level containers. Instead layout the content & call pack().
Java GUIs should be started & updated on the EDT.
Use a JSpinner instead of a text field when the app. requires numbers.
you have to do g.repaint() after g2d.fillRect(x,y,w,h)

Categories