Getting a null pointer exception [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Getting a null pointer exception in the MouseDragged function. Been trying to figure out for days what is causing it but I don't know what. Any help would be appreciated thanks. My program is supposed to add an image file and be able to paint over it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.BufferedImage;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.geom.*;
import java.util.Vector;
import java.util.*;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.Toolkit;
public class Lab3 {
public static void main(String[] args)
{
new Lab3Frame();
}
}
class Lab3Frame extends JFrame implements ActionListener, MouseListener, MouseMotionListener, ChangeListener
{
JFrame frame;
JPanel toolbar;
JMenuBar menuBar;
JMenu tool, file;
JLabel image;
JToggleButton b1, b2, b3, b4, bcol;
JMenuItem pencil, eraser, brush, line, open;
final JFileChooser fc = new JFileChooser();
BufferedImage img;
JColorChooser tcc;
JScrollBar hbar, vbar;
PaintPanel inkPanel;
private Point[] stroke;
public Color ink_color = Color.black;
public Stroke ink_stroke = new BasicStroke(5.0f,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
final int MAX_SAMPLES = 500;
private int sampleCount;
//private Vector<Line2D.Double> v;
Lab3Frame(){
frame = new JFrame();
menuBar = new JMenuBar();
image = new JLabel();
tool = new JMenu("Tools");
file = new JMenu("File");
pencil = new JMenuItem("Pencil");
eraser = new JMenuItem("Eraser");
brush = new JMenuItem("Brush");
line = new JMenuItem("Line");
tool.add(pencil);
tool.add(line);
tool.add(eraser);
tool.add(brush);
open = new JMenuItem("Open");
file.add(open);
menuBar.add(file);
menuBar.add(tool);
frame.setJMenuBar(menuBar);
tcc = new JColorChooser();
inkPanel = new PaintPanel();
toolbar = new JPanel();
toolbar.setSize(100,300);
image.setBackground(Color.blue);
//TOOLBAR BUTTONS
toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.Y_AXIS));
b1 = new JToggleButton("1");
toolbar.add(b1);
b2 = new JToggleButton("2");
toolbar.add(b2);
b3 = new JToggleButton("3");
toolbar.add(b3);
b4 = new JToggleButton("4");
toolbar.add(b4);
bcol = new JToggleButton(" ");
toolbar.add(bcol);
tcc.setPreviewPanel(new JPanel());
//LISTENERS
pencil.addActionListener(this);
open.addActionListener(this);
image.addMouseMotionListener(this);
pencil.addMouseMotionListener(this);
tcc.getSelectionModel().addChangeListener(this);
inkPanel.addMouseMotionListener(this);
inkPanel.addMouseListener(this);
//hbar.addAdjustmentListener(this);
//vbar.addAdjustmentListener(this);
//tcc.addChangeListener(this);
//ADD ELEMENTS TO FRAME
frame.setSize(600, 600);
hbar = new JScrollBar(JScrollBar.HORIZONTAL, 30, 20, 0, 300);
vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300);
frame.setLayout(new BorderLayout());
image.setLayout(new BorderLayout());
image.setBackground(Color.white);
frame.add(toolbar, BorderLayout.WEST);
frame.add(tcc, BorderLayout.SOUTH);
frame.add(image, BorderLayout.CENTER);
frame.setGlassPane(inkPanel);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == open){
int returnVal = fc.showOpenDialog(Lab3Frame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
// frame.add(inkPanel);
img=ImageIO.read(file);
ImageIcon icon=new ImageIcon(img); // ADDED
image.setIcon(icon); // ADDED
Dimension imageSize = new Dimension(icon.getIconWidth(),icon.getIconHeight()); // ADDED
image.setPreferredSize(imageSize); // ADDED
image.setVisible(true);
//
//image.add(hbar, BorderLayout.SOUTH);
//image.add(vbar, BorderLayout.EAST);
//image.revalidate(); // ADDED
//image.repaint(); // ADDED
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
}
public void stateChanged(ChangeEvent changeEvent) {
Color customCol = tcc.getColor();
bcol.setBackground(customCol);
}
/*
AdjustmentListener adjustmentListener = new AdjustmentListener(){
public void adjustmentValueChanged(AdjustmentEvent adjustmentEvent) {
System.out.println("Adjusted: " + adjustmentEvent.getValue());
}
};
*/
public void mouseClicked(MouseEvent me) {
int x = me.getX();
int y = me.getY();
if (SwingUtilities.isLeftMouseButton(me))
{
stroke[sampleCount] = new Point(x, y);
int x1 = (int)stroke[sampleCount - 1].getX();
int y1 = (int)stroke[sampleCount - 1].getY();
int x2 = (int)stroke[sampleCount].getX();
int y2 = (int)stroke[sampleCount].getY();
if (sampleCount < MAX_SAMPLES - 1)
++sampleCount;
// draw ink trail from previous point to current point
inkPanel.drawInk(x1, y1, x2, y2);
}
}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mousePressed(MouseEvent me) {
int x = me.getX();
int y = me.getY();
stroke[sampleCount] = new Point(x, y);
if (sampleCount < MAX_SAMPLES - 1)
++sampleCount;
}
public void mouseDragged(MouseEvent me) {
sampleCount = 1;
int x = me.getX();
int y = me.getY();
System.out.println("y2:" + y );
if (SwingUtilities.isLeftMouseButton(me))
{
// try{
stroke[sampleCount] = new Point(x, y);
int x2 = (int)stroke[sampleCount].getX();
int y2 = (int)stroke[sampleCount].getY();
int x1 = (int)stroke[sampleCount - 1].getX();
int y1 = (int)stroke[sampleCount - 1].getY();
if (sampleCount < MAX_SAMPLES - 1){
++sampleCount;}
//draw.Line2D.
inkPanel.drawInk(x1, y1, x2, y2);
//inkPanel.repaint();
}
/*catch ( Exception err1 ) {
System.out.println( err1.getMessage( ) );
}*/
// draw ink trail from previous point to current point
// }
}
public void mouseReleased(MouseEvent me) {
}
public void mouseMoved(MouseEvent me) {
}
class PaintPanel extends JPanel
{
private Vector<Line2D.Double> v;
private final Stroke INK_STROKE = new BasicStroke(5.0f,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
PaintPanel()
{
v = new Vector<Line2D.Double>();
this.setBackground(Color.white);
}
#Override
public void paintComponent(Graphics gd) {
super.paintComponent(gd);
paintImage(gd);
}
public void paintImage(Graphics gd){
Graphics2D g2 = (Graphics2D)gd;
//Rectangle aa = new Rectangle( 10, 10, 100, 100);
//g2.draw(aa);
g2.setColor(Color.red);
Stroke s = g2.getStroke(); // save current stroke
g2.setStroke(INK_STROKE);
for (int i = 0; i < v.size(); ++i)
g2.draw((Line2D.Double)v.elementAt(i));
g2.setStroke(s);
repaint();
}
public void drawInk(int x1, int y1, int x2, int y2)
{
// get graphics context
Graphics2D g2 = (Graphics2D)this.getGraphics();
//System.out.println("dn " + g2 + "method was called");
// create the line
Line2D.Double inkSegment = new Line2D.Double(x1, y1, x2, y2);
g2.setColor(Color.red); // set the inking color
Stroke s = g2.getStroke(); // save current stroke
g2.setStroke(INK_STROKE); // set desired stroke
g2.draw(inkSegment); // draw it!
g2.setStroke(s); // restore stroke
v.add(inkSegment); // add to vector
repaint();
}
}
}

stroke[sampleCount]
I don't see the var stroke to be allocated, so this can be your null pointer exception.

You try to use stroke but you never initialized it. Initialize that with new array!!

Related

How to prevent flushing when draw a rectangle in Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
class DrawningBoard extends Canvas implements MouseMotionListener{
private List<Point> points = new ArrayList<>();
private List<List<Point>> curves = new ArrayList<>();
private boolean isRectangle = false;
private int xr, yr, widthr, heightr;
public void setIsRectangle(boolean trueOrFalse){
isRectangle = trueOrFalse;
}
public boolean getIsRectangle(){
return isRectangle;
}
public DrawningBoard(){
setBackground(Color.MAGENTA);
addMouseMotionListener(this);
addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
curves.add(points);
points = new ArrayList<>();
}
public void mousePressed(MouseEvent e){
points.add(new Point(e.getX(), e.getY()));
}
});
}
public void paint(Graphics g){
g.setColor(Color.CYAN);
if(isRectangle){
g.drawRect(xr, yr, widthr, heightr);
}
for(List<Point> curve : curves){
for(int i = 0; i < curve.size() - 1; i++){
g.drawLine((int)curve.get(i).getX(), (int)curve.get(i).getY(), (int)curve.get(i + 1).getX(), (int)curve.get(i + 1).getY());
}
}
}
public void mouseDragged(MouseEvent e){
Graphics g = getGraphics();
g.setColor(Color.CYAN);
int xx = e.getX();
int yy = e.getY();
int x = (int)points.get(points.size() - 1).getX();
int y = (int)points.get(points.size() - 1).getY();
int dx = xx-x;
int dy = yy-y;
if(isRectangle){
if(dx >= 0 && dy >= 0){
xr = x;
yr = y;
widthr = dx;
heightr = dy;
} else if(dx < 0 && dy < 0){
xr = xx;
yr = yy;
widthr = -dx;
heightr = -dy;
} else if(dx >= 0 && dy < 0){
xr = x;
yr = yy;
widthr = dx;
heightr = -dy;
} else if(dx < 0 && dy >= 0){
xr = xx;
yr = y;
widthr = -dx;
heightr = dy;
}
repaint();
}
else {
g.drawLine(xx, yy, (int)points.get(points.size() - 1).getX(), (int)points.get(points.size() - 1).getY());
points.add(new Point(xx, yy));
}
}
public void mouseMoved(MouseEvent e) { }
}
class GUI extends JFrame implements ActionListener{
private JPanel[] panel;
private JButton[] button;
private DrawningBoard board;
public GUI(String title){
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(416, 400);
board = new DrawningBoard();
board.setBounds(0,0, 400, 400);
panel = new JPanel[3];
panel[0] = new JPanel();
panel[1] = new JPanel();
panel[2] = new JPanel();
panel[0].setLayout(null);
panel[1].setLayout(null);
panel[2].setLayout(null);
panel[0].setBounds(0, 0, 400, 20);
panel[1].setBounds(0, 20, 400, 400);
panel[2].add(panel[0]);
panel[2].add(panel[1]);
panel[0].setBackground(Color.red);
button = new JButton[5];
button[0] = new JButton("Rectangle");
button[1] = new JButton("b1");
button[2] = new JButton("b2");
button[3] = new JButton("b3");
button[4] = new JButton("b4");
button[0].addActionListener(this);
button[3].addActionListener(this);
button[0].setBounds(0, 0, 100, 20);
button[1].setBounds(100, 0, 100, 20);
button[2].setBounds(200, 0, 100, 20);
button[3].setBounds(300, 0, 100, 20);
button[4].setBounds(0, 0, 100, 20);
panel[0].add(button[0]);
panel[0].add(button[1]);
panel[0].add(button[2]);
panel[0].add(button[3]);
panel[0].add(button[4]);
panel[1].add(board);
add(panel[2]);
show();
}
public void actionPerformed(ActionEvent e){
String command = e.getActionCommand();
if(command.equals("Rectangle"))
board.setIsRectangle(!board.getIsRectangle());
}
}
public class Paint{
public static void main(String []str){
new GUI("Paint");
}
}
I want to create a Paint application. If I draw multiple curves on the board and then I want to draw a rectangle (using drawRect(x, y, width, height)), those curves are repainted and results some flushing as result of use repaint() method. How can I avoid that flushing?
I tried to use update() method, but many rectangles are drawn when mouse dragging.
Swing is double buffered by default.
public void paint(Graphics g){
Don't override paint(). You have done this incorrectly and have lost the benefit of double buffering.
Instead, custom painting should be done by overriding the paintComponent(...) method. Read the section from the Swing tutorial on Custom Painting for more information and working examples.
You can also check out the DrawOnComponent example from Custom Painting Approaches for a more complete example that does what you want.

how to output a user selected shape & color, whose location and dimensions depend upon the coordinate location of user clicks

As part of a larger project I'm trying to create a basic UI that will allow a user to click a JButton to select a desired color and then allow that user to click another JButton to designate a shape to be displayed, filled in according to the previously selected color. I understand that I must make use of action events.
Please note I am referencing this similar question:
GUI Application that allows the user to choose the shape and color of a drawing
My code thus far is:
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener, WindowListener
{
private final JButton circleButton, rectangleButton, redButton;
private final JButton greenButton, blueButton, exitButton;
private final JTextArea textArea;
private final JLabel label1;
private final JPanel colorPane;
private String shapeColor = "black";
private String actualShape = "rectangle";
private static final int ROWS = 2, COLS = 3;
public GUI (String title)
{
super(title);
//setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colorPane = new JPanel();
label1 = new JLabel("current date here");
label1.setVerticalAlignment(SwingConstants.BOTTOM);
label1.setHorizontalAlignment(SwingConstants.LEFT);
label1.setPreferredSize(new Dimension(200,0));
getContentPane().add(label1, BorderLayout.WEST);
colorPane.setLayout(new GridLayout(ROWS,COLS));
getContentPane().add(colorPane, BorderLayout.CENTER);
redButton = makeButton("Red");
colorPane.add(redButton);
greenButton = makeButton("Green");
colorPane.add(greenButton);
blueButton = makeButton("Blue");
colorPane.add(blueButton);
rectangleButton = makeButton("Rectangle");
colorPane.add(rectangleButton);
circleButton = makeButton("Circle");
colorPane.add(circleButton);
exitButton = makeButton("Exit");
colorPane.add(exitButton);
textArea = new JTextArea(0,20);
getContentPane().add(textArea, BorderLayout.EAST);
pack();
}
public void paint(Graphics g, String color)
{
if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("rectangle"))
{
g.setColor(Color.BLUE);
g.fillRect(50, 90, 100, 50);
}
else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("circle"))
{
g.setColor(Color.GREEN);
g.fillOval(50, 180, 55, 55);
}
else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("rectangle"))
{
g.setColor(Color.RED);
g.fillRect(50, 90, 100, 50);
}
else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("rectangle"))
{
g.setColor(Color.GREEN);
g.fillRect(50,90,100,50);
}
else if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("circle"))
{
g.setColor(Color.BLUE);
g.fillOval(50, 180, 55, 55);
}
else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("circle"))
{
g.setColor(Color.RED);
g.fillOval(50, 180, 55, 55);
}
}
//method designed to create new JButtons while avoiding code duplication
private JButton makeButton(String text)
{
JButton b = new JButton(text);
b.setHorizontalAlignment(SwingConstants.LEFT);
b.addActionListener(this);
b.setPreferredSize(new Dimension(125,55));
return b;
}
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
#Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println( ( (JButton)e.getSource() ).getText() + " button pressed ");
if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Red")) )
{
setShapeColor("Red");
System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
//paint(this.getGraphics());
}
else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Blue")) )
{
setShapeColor("Blue");
System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
//paint(this.getGraphics());
}
else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Green")) )
{
setShapeColor("Green");
System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
//paint(this.getGraphics());
}
if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Rectangle")) )
{
setActualShape("rectangle");
System.out.println("selected shape is: " + actualShape + " selected color is: " + shapeColor);
paint(this.getGraphics(), shapeColor);
}
else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Circle")) )
{
setActualShape("circle");
System.out.println("selected shape is: " + actualShape + " selected color is: " + shapeColor);
paint(this.getGraphics(), shapeColor);
}
}
public String getShapeColor() {
return shapeColor;
}
public void setShapeColor(String shapeColor) {
this.shapeColor = shapeColor;
}
public String getActualShape() {
return actualShape;
}
public void setActualShape(String actualShape) {
this.actualShape = actualShape;
}
public static void main(String[] args)
{
new GUI("My Gui").setVisible(true);
}
}
What I've thus far achieved is an output that shows both the selected color as well as the selected shape to be rendered in the selected color.
Furthermore, I've been successful in outputting a shape whose position is hard-coded but whose type (either circle or square) and whose color (red, blue or green), is correctly output as a result of the user clicks.
The final phase, upon which I am struggling, is the implementation of the shape's output so that the user's sequence of clicks determines the location and dimensions of the shape output to the screen.
The goal is to achieve the functionality demonstrated here:
https://metrostate.learn.minnstate.edu/content/2020/4560296-20201000539/ICS372%20-%20Assignment%202%20Video.mp4?d2lSessionVal=ARifwbCHriCBrkgxBWpL9g8fL&ou=4560296
I'm relatively certain that the correct solution is similar to the following code:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* Note: Normally the ButtonPanel and DrawingArea would not be static
classes.
* This was done for the convenience of posting the code in one class and
to
* highlight the differences between the two approaches. All the
differences
* are found in the DrawingArea class.
*/
public class DrawOnComponent
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
DrawingArea drawingArea = new DrawingArea();
ButtonPanel buttonPanel = new ButtonPanel( drawingArea );
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Draw On Component");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add(drawingArea);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(400, 400);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
static class ButtonPanel extends JPanel implements ActionListener
{
private DrawingArea drawingArea;
public ButtonPanel(DrawingArea drawingArea)
{
this.drawingArea = drawingArea;
add( createButton(" ", Color.BLACK) );
add( createButton(" ", Color.RED) );
add( createButton(" ", Color.GREEN) );
add( createButton(" ", Color.BLUE) );
add( createButton(" ", Color.ORANGE) );
add( createButton(" ", Color.YELLOW) );
add( createButton("Clear Drawing", null) );
}
private JButton createButton(String text, Color background)
{
JButton button = new JButton( text );
button.setBackground( background );
button.addActionListener( this );
return button;
}
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
if ("Clear Drawing".equals(e.getActionCommand()))
drawingArea.clear();
else
drawingArea.setForeground( button.getBackground() );
}
}
static class DrawingArea extends JPanel
{
private final static int AREA_SIZE = 400;
private ArrayList<ColoredRectangle> coloredRectangles = new ArrayList<ColoredRectangle>();
private Rectangle shape;
public DrawingArea()
{
setBackground(Color.WHITE);
MyMouseListener ml = new MyMouseListener();
addMouseListener(ml);
addMouseMotionListener(ml);
}
#Override
public Dimension getPreferredSize()
{
return isPreferredSizeSet() ?
super.getPreferredSize() : new Dimension(AREA_SIZE, AREA_SIZE);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Custom code to paint all the Rectangles from the List
Color foreground = g.getColor();
g.setColor( Color.BLACK );
g.drawString("Add a rectangle by doing mouse press, drag and release!", 40, 15);
for (DrawingArea.ColoredRectangle cr : coloredRectangles)
{
g.setColor( cr.getForeground() );
Rectangle r = cr.getRectangle();
g.drawRect(r.x, r.y, r.width, r.height);
}
// Paint the Rectangle as the mouse is being dragged
if (shape != null)
{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor( foreground );
g2d.draw( shape );
}
}
public void addRectangle(Rectangle rectangle, Color color)
{
// Add the Rectangle to the List so it can be repainted
ColoredRectangle cr = new ColoredRectangle(color, rectangle);
coloredRectangles.add( cr );
repaint();
}
public void clear()
{
coloredRectangles.clear();
repaint();
}
class MyMouseListener extends MouseInputAdapter
{
private Point startPoint;
public void mousePressed(MouseEvent e)
{
startPoint = e.getPoint();
shape = new Rectangle();
}
public void mouseDragged(MouseEvent e)
{
int x = Math.min(startPoint.x, e.getX());
int y = Math.min(startPoint.y, e.getY());
int width = Math.abs(startPoint.x - e.getX());
int height = Math.abs(startPoint.y - e.getY());
shape.setBounds(x, y, width, height);
repaint();
}
public void mouseReleased(MouseEvent e)
{
if (shape.width != 0 || shape.height != 0)
{
addRectangle(shape, e.getComponent().getForeground());
}
shape = null;
}
}
class ColoredRectangle
{
private Color foreground;
private Rectangle rectangle;
public ColoredRectangle(Color foreground, Rectangle rectangle)
{
this.foreground = foreground;
this.rectangle = rectangle;
}
public Color getForeground()
{
return foreground;
}
public void setForeground(Color foreground)
{
this.foreground = foreground;
}
public Rectangle getRectangle()
{
return rectangle;
}
}
}
}
I know that I must override the 'paint' method and as a hard-coded exercise I have included the following in my code:
public void paint(Graphics g, String color)
{
if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("rectangle"))
{
g.setColor(Color.BLUE);
g.fillRect(50, 90, 100, 50);
}
else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("circle"))
{
g.setColor(Color.GREEN);
g.fillOval(50, 180, 55, 55);
}
else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("rectangle"))
{
g.setColor(Color.RED);
g.fillRect(50, 90, 100, 50);
}
else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("rectangle"))
{
g.setColor(Color.GREEN);
g.fillRect(50,90,100,50);
}
else if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("circle"))
{
g.setColor(Color.BLUE);
g.fillOval(50, 180, 55, 55);
}
else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("circle"))
{
g.setColor(Color.RED);
g.fillOval(50, 180, 55, 55);
}
}
}
I am unsure how to record coordinates of a user's button click and to then pass those coordinates into the constructor of the desired shape.
There are a couple of errors to change in your code:
Don't extend JFrame, see Extends JFrame vs. creating it inside the program, instead create an instance of it inside your class. If you need to extend from a JComponent let it be a more flexible one such as JPanel.
Don't override paint(...) method, you need to override JPanel's paintComponent(...) method and don't forget to call super.paintComponent(g) as the first line in it, otherwise you might break the paint chain and have funny / weird behaviors. Neither pass the getGraphics() object, see the Tutorial on Custom Painting
Use the Shape API rather than drawing directly on the JPanel as it provides more functionality. See this post: Create the square, rectangle, triangle of java in jframe
Don't call setPreferredSize, override the getPreferredSize, see: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Place your program on the EDT, see point #7 in the linked post in point #3 in this same answer.
So, here's an example that follows the above recommendations:
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.event.*;
public class PaintExample {
private JFrame frame;
private JPanel pane;
private JPanel buttonsPane;
private CustomShape customShape;
private JButton squareButton;
private JButton circleButton;
private JButton purpleButton;
private JButton blueButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new PaintExample().createAndShowGUI());
}
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName()); //Create a new JFrame with a title = this class name
pane = new JPanel();
buttonsPane = new JPanel();
buttonsPane.setLayout(new GridLayout(2, 2, 5, 5)); // We generate a grid layout of 2 x 2 for our JButtons
squareButton = new JButton("Square");
circleButton = new JButton("Circle");
purpleButton = new JButton("Purple");
blueButton = new JButton("Blue");
squareButton.addActionListener(listener);
circleButton.addActionListener(listener);
purpleButton.addActionListener(listener);
blueButton.addActionListener(listener);
buttonsPane.add(squareButton);
buttonsPane.add(circleButton);
buttonsPane.add(purpleButton);
buttonsPane.add(blueButton);
customShape = new CustomShape(); // We create an instance of our custom JPanel class
pane.setLayout(new BorderLayout());
pane.add(customShape);
pane.add(buttonsPane, BorderLayout.SOUTH);
frame.add(pane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
ActionListener listener = e -> { //Java 8+, for Java 7- add the actionPerformed method instead of the lambda expression
// We check which button was clicked and set the shape / color for our custom class
if (e.getSource().equals(squareButton)) {
customShape.setShape(ShapeToDraw.SQUARE);
} else if (e.getSource().equals(circleButton)) {
customShape.setShape(ShapeToDraw.CIRCLE);
} else if (e.getSource().equals(purpleButton)) {
customShape.setColor(Color.MAGENTA);
} else if (e.getSource().equals(blueButton)) {
customShape.setColor(Color.BLUE);
}
};
enum ShapeToDraw {
SQUARE, CIRCLE // You can define here other properties for each enum option
}
class CustomShape extends JPanel {
private Color color;
private ShapeToDraw shape;
public CustomShape() {
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
this.repaint(); // Everytime we set the color we ask the component to repaint itself
}
public ShapeToDraw getShape() {
return shape;
}
public void setShape(ShapeToDraw shape) {
this.shape = shape;
this.repaint(); // Everytime we set the shape we ask the component to repaint itself
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200); // We define the panel's size
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color != null ? color : Color.BLACK); //If we haven't set the Color yet, we default it to black, otherwise we set the color to the one chosen by the user.
if (shape == ShapeToDraw.SQUARE) { //If the shape is a square, we draw a square
g2d.draw(new Rectangle2D.Double(50, 50, 100, 100)); // Change the coordinates that you get by user click using the MouseListener
} else if (shape == ShapeToDraw.CIRCLE) { // Or we draw a circle
g2d.draw(new Ellipse2D.Double(50, 50, 100, 100));
}
}
}
}
This is how the program looks like:
I am unsure how to record coordinates of a user's button click and to then pass those coordinates into the constructor of the desired shape.
To get the coordinates relative to your window see: How to get location of a mouse click relative to a swing window
The following is a suggested implementation, also incorporating the good guidance you got from Frakcool:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class GUI
{
private final ButtonGroup colorGroup; //group buttons
private final ButtonGroup shapeGroup; //so only one can be selected at any given time
private final Map<String, Color> colors; //map colors to it names.
private Color color; // color for painting
private Shape shape; //shape to paint
private JFrame frame;
private JPanel buttonsPane;
private JTextArea textArea;
private static final int ROWS = 2, COLS = 3;
private static final String[] BUTTONS_LABELS = {"Rectangle", "Circle", "Exit"};
public GUI()
{
shapeGroup = new ButtonGroup(); colorGroup = new ButtonGroup();
colors = new HashMap<>();
colors.put("Red", Color.RED); colors.put("Green", Color.GREEN); colors.put("Blue", Color.BLUE);
}
private void createAndShowGUI(String title) {
frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//use a GridLayout for the buttons pane
buttonsPane = new JPanel();
buttonsPane.setLayout(new GridLayout(ROWS, COLS));
frame.getContentPane().add(buttonsPane, BorderLayout.CENTER);//each BorderLayout position can hold ONE component
for(String colorName : colors.keySet()){
JToggleButton button = makeButton(colorName);
buttonsPane.add(button);
colorGroup.add(button);
button.addActionListener(changeColorAction());
}
for(String text : BUTTONS_LABELS){
JToggleButton button = makeButton(text);
buttonsPane.add(button);
shapeGroup.add(button);
button.addActionListener(changeShapeAction());
}
setDefaults();
frame.getContentPane().add(new Draw(), BorderLayout.WEST);
textArea = new JTextArea(0,20);
frame.getContentPane().add(textArea, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
private JToggleButton makeButton(String text) {
JToggleButton b = new JToggleButton(text); //use toggle buttons
b.setHorizontalAlignment(SwingConstants.LEFT);
b.setPreferredSize(new Dimension(100, 80)); //set preferred and let Layout manager do its work
return b;
}
private ActionListener changeColorAction() {
return e->{
color = colors.get(((JToggleButton)e.getSource()).getText());
frame.repaint();
};
}
private ActionListener changeShapeAction() {
return e->{
switch (((JToggleButton)e.getSource()).getText()){
case "Circle":
shape = Shape.CIRCLE;
break;
case "Rectangle":
shape = Shape.RECTANGLE;
break;
default: System.exit(0);
}
frame.repaint();
};
}
private void setDefaults() {
colorGroup.getElements().nextElement().setSelected(true);
color = colors.get(colorGroup.getElements().nextElement().getText());
shapeGroup.getElements().nextElement().setSelected(true);
shape = Shape.RECTANGLE;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GUI().createAndShowGUI("My Gui"));
}
class Draw extends JPanel{
private final Point[] points; // an array to hold clicked points
private int mouseClicks = 0;
private static final int POINT_SIZE = 2;
Draw(){
setLayout(new BorderLayout());
setBackground(Color.WHITE);
setPreferredSize(new Dimension(200, 200));
JLabel help = new JLabel("Click 2 points to draw");
help.setHorizontalAlignment(SwingConstants.CENTER);
add(help, BorderLayout.PAGE_START);
JLabel timeLabel = new JLabel("current time here");
timeLabel.setHorizontalAlignment(SwingConstants.LEFT);
add(timeLabel, BorderLayout.PAGE_END);
points = new Point[2];
addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
addPoint(e.getX(), +e.getY() );
}
});
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(color);
for(Point point : points)
if(point != null){
g.drawOval(point.x, point.y, POINT_SIZE, POINT_SIZE);
}
drawShape((Graphics2D)g);
}
private void addPoint(int x, int y) {
if(mouseClicks ==2){
mouseClicks = 0;
points[1] = null;
}
points[mouseClicks++] = new Point(x, y);
repaint();
}
private void drawShape(Graphics2D g2d) {
if(points[0] == null || points[1] == null) return;
if(shape == Shape.RECTANGLE) {
drawRectangle(g2d);
}else{
drawCircle(g2d);
}
}
private void drawRectangle(Graphics2D g2D) {
int minX = Math.min(points[0].x, points[1].x);
int minY = Math.min(points[0].y, points[1].y);
int maxX = Math.max(points[0].x, points[1].x);
int maxY = Math.max(points[0].y, points[1].y);
int width = maxX - minX;
int height = maxY - minY;
Rectangle2D.Double rectangle = new Rectangle2D.Double(minX, minY, width, height);
g2D.draw(rectangle);
}
private void drawCircle(Graphics2D g2D) {
int minX = Math.min(points[0].x, points[1].x);
int minY = Math.min(points[0].y, points[1].y);
int maxX = Math.max(points[0].x, points[1].x);
int maxY = Math.max(points[0].y, points[1].y);
double dx = maxX - minX;
double dy = maxY - minY;
double radius = Math.sqrt(dx*dx + dy*dy)/2;
double centerX = minX + dx/2;
double centerY = minY + dy/2;
g2D.draw(new Ellipse2D.Double(centerX - radius , centerY - radius, 2* radius, 2* radius));
}
}
enum Shape {
RECTANGLE, CIRCLE
}
}

How to paint 2Dgraphics and images separately in the same class to the same JPanel

I have a method (drawImages) that draws an arraylist of bufferedimages to the extended JPanel. However, it is only being called in the paintComponent method when another method (drawPerfectRect) is called.
This method (drawPerfectRect) is responsible for using co-ordinates passed to it to draw a rectangle using points clicked on by the user.
Essentially, the two problems I am having are:
It does not paint the arraylist of bufferedimages until the user clicks and drags to create a rectangle (want the images to be painted at after selectDirectory (JButton) is clicked).
It also paints the bufferedimages again for every subsequent rectangle that is painted.
It seems that the bufferedimages are only painted when the rectangles are painted.
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import com.sun.tools.internal.ws.wsdl.document.Import;
import net.coobird.thumbnailator.*;
import com.mortennobel.imagescaling.*;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.geom.RoundRectangle2D;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Timer;
public class ImportWorkspace extends JPanel{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x, y, x2, y2;
ArrayList<BufferedImage> thumbnailList = new ArrayList<BufferedImage>();
int ContentPanelWidth;
private boolean addThumbnails = false;
public ImportWorkspace(){
x = y = x2 = y2 = 0;
setLayout(null);
setBackground(Color.decode("#2a2e37"));
setBounds(85, 0, screenSize.width-85, screenSize.height);
//System.out.println("W: " + super.getWidth() + ", H: " + super.getHeight());
ContentPanelWidth = getWidth();
System.out.println(ContentPanelWidth);
JLabel dataIcon = new JLabel(new ImageIcon(new ImageIcon ("folder.png").getImage().getScaledInstance(256,256, Image.SCALE_DEFAULT)));
dataIcon.setBounds((getWidth()/2)-128, (getHeight()/2)-200, 256, 256);
add(dataIcon);
JLabel askImport = new JLabel("No Data Files have been selected: To begin importing data please select a directory.");
askImport.setFont(new Font("Helvetica", Font.PLAIN, 20));
askImport.setForeground(Color.white);
askImport.setBounds((getWidth()/2)-375, (getHeight()/2)+50, 750, 100);
add(askImport);
JButton selectDirectory = new JButton("Select Directory");
selectDirectory.setBounds((getWidth()/2)-75, (getHeight()/2)+150, 150, 50); //+half of width or height
add(selectDirectory);
selectDirectory.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
removeAll();
revalidate();
repaint();
setLayout(new FlowLayout(FlowLayout.LEFT));
ImportingImages getImages = new ImportingImages();
getImages.importFiles();
File curDir = new File("");
File[] files = curDir.listFiles();
long noFiles = curDir.length();
for (File f : files) {
String fileName = f.getName();
String hiddenFile = ".DS_Store";
if (fileName.equals(hiddenFile)){
//System.out.println("Do nothing");
} else {
String thumbnailPath = curDir + "/" + f.getName();
try {
BufferedImage thumbnailIcon = ImageIO.read(new File(thumbnailPath));
thumbnailList.add(thumbnailIcon);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
MyMouseListener listener = new MyMouseListener();
addMouseListener(listener);
addMouseMotionListener(listener);
//DisplayImages(thumbnailList, ContentPanelWidth);
}
});
}
public void setStartPoint(int x, int y) {
this.x = x;
this.y = y;
}
public void setEndPoint(int x, int y) {
x2 = (x);
y2 = (y);
}
public void drawPerfectRect(Graphics g, int x, int y, int x2, int y2) {
int px = Math.min(x,x2);
int py = Math.min(y,y2);
int pw = Math.abs(x-x2);
int ph = Math.abs(y-y2);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int alpha = 100; // 127 50% transparent
Color cyanTransparent = new Color(0,206,209, alpha);
g2.setColor(cyanTransparent);
g2.fillRoundRect(px, py, pw, ph, 5, 5);
g2.setColor(Color.cyan);
g2.setStroke(new BasicStroke(1));
g2.drawRoundRect(px, py, pw, ph, 5, 5);
}
public void drawImages(Graphics g){
int xSpacing = 10;
int ySpacing = 20;
int noImages = 0;
for (BufferedImage thumbnail : thumbnailList){
g.drawImage(thumbnail, xSpacing, ySpacing,null );
if ((xSpacing+100) > (ContentPanelWidth-100)){
ySpacing = ySpacing + 77;
xSpacing = 10;
} else{
xSpacing = xSpacing + 110;
}
noImages = noImages + 1;
//System.out.println(noImages);
}
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
setStartPoint(e.getX(), e.getY());
}
public void mouseDragged(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
revalidate();
repaint();
}
public void mouseReleased(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
revalidate();
repaint();
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
System.out.println(addThumbnails);
drawImages(g2);
drawPerfectRect(g2, x, y, x2, y2);
}
}
Improve the action listener added to the selectDirectory button, as follows:
Remove the repaint() call inside the action listener (will fix it later on).
Clear the list of thumbnails each time the button is pressed. That is, thumbnailList.clear() inside the action listener. This way, only the last imported images will be displayed for each directory selection.
Call repaint() inside the button's action listener after the for loop which adds the thumbnails in the list. This way, the panel will be repainted (with the new images) after the images are actually loaded into the list.
As a result, the ImportWorkspace constructor can be written as follows:
public ImportWorkspace(){
x = y = x2 = y2 = 0;
setLayout(null);
setBackground(Color.decode("#2a2e37"));
setBounds(85, 0, screenSize.width-85, screenSize.height);
//System.out.println("W: " + super.getWidth() + ", H: " + super.getHeight());
ContentPanelWidth = getWidth();
System.out.println(ContentPanelWidth);
JLabel dataIcon = new JLabel(new ImageIcon(new ImageIcon ("folder.png").getImage().getScaledInstance(256,256, Image.SCALE_DEFAULT)));
dataIcon.setBounds((getWidth()/2)-128, (getHeight()/2)-200, 256, 256);
add(dataIcon);
JLabel askImport = new JLabel("No Data Files have been selected: To begin importing data please select a directory.");
askImport.setFont(new Font("Helvetica", Font.PLAIN, 20));
askImport.setForeground(Color.white);
askImport.setBounds((getWidth()/2)-375, (getHeight()/2)+50, 750, 100);
add(askImport);
JButton selectDirectory = new JButton("Select Directory");
selectDirectory.setBounds((getWidth()/2)-75, (getHeight()/2)+150, 150, 50); //+half of width or height
add(selectDirectory);
selectDirectory.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
removeAll();
revalidate();
//repaint(); //Removed this line. It is not necessary in this place. Will be re-added AFTER the `for` loop below...
thumbnailList.clear(); //Added this line.
setLayout(new FlowLayout(FlowLayout.LEFT));
ImportingImages getImages = new ImportingImages();
getImages.importFiles();
File curDir = new File("");
File[] files = curDir.listFiles();
long noFiles = curDir.length();
for (File f : files) {
String fileName = f.getName();
String hiddenFile = ".DS_Store";
if (fileName.equals(hiddenFile)){
//System.out.println("Do nothing");
} else {
String thumbnailPath = curDir + "/" + f.getName();
try {
BufferedImage thumbnailIcon = ImageIO.read(new File(thumbnailPath));
thumbnailList.add(thumbnailIcon);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
repaint(); //Added this line! Now the newly loaded images shall be painted.
MyMouseListener listener = new MyMouseListener();
addMouseListener(listener);
addMouseMotionListener(listener);
//DisplayImages(thumbnailList, ContentPanelWidth);
}
});
}

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.

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