• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Java Swing Help

Joined
Jun 17, 2007
Messages
7,326 (1.88/day)
Likes
995
Location
C:\Program Files (x86)\Aphexdreamer\
System Name Unknown
Processor AMD Bulldozer FX8320 @ 4.4Ghz
Motherboard Asus Crosshair V
Cooling XSPC Raystorm 750 EX240 for CPU
Memory 8 GB CORSAIR Vengeance Red DDR3 RAM 1922mhz (10-11-9-27)
Video Card(s) XFX R9 290
Storage Samsung SSD 254GB and Western Digital Caviar Black 1TB 64MB Cache SATA 6.0Gb/s
Display(s) AOC 23" @ 1920x1080 + Asus 27" 1440p
Case HAF X
Audio Device(s) X Fi Titanium 5.1 Surround Sound
Power Supply 750 Watt PP&C Silencer Black
Software Windows 8.1 Pro 64-bit
#1
How can I draw a circle from circle class that extends an abstract shape class?

I managed to use paintCompontent in my MainWidnow class to get a circle to draw in my Window but now I'm trying to do the same thing via a class circle that extends an abstract class shape.

I declared an abstract method draw and I have moved the actual drawing code from the paintComponent to my Circle class and adjusted the object but it won't draw on the screen, probably because I'm not using paintComponent anywhere, but I juts don't know where to put it given that I have to use draw in my circle/shape class.
MainWindow my GUI window
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class MainWindow //implements ActionListener
{
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    JFrame frame;
    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";
    //JPanel jp = new JPanel();

    Color currentColor = Color.red;

    public MainWindow( ){

        frame = new JFrame("Menu Demonstration");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //frame.setLayout(new FlowLayout(-2,10,10));
       // frame.setLayout(new GridLayout(1, 3));
        //setLayout(new BoxLayout( , BoxLayout.Y_AXIS));
        //setBackground(Color.LIGHT_GRAY);;

        String[] colorBoarder = { "Red", "Green", "Blue", "Yellow", "Black", "White" };

//Adds menu and thier selections
//Select Fill
        JMenu shapeColor = new JMenu("Shape Color");
        

        JMenuItem redChoice = new JMenuItem("Fill Red");
        //redChoice.addActionListener(this);
        shapeColor.add(redChoice);

        JMenuItem whiteChoice = new JMenuItem("Fill White");
        //whiteChoice.addActionListener(this);
        shapeColor.add(whiteChoice);
        whiteChoice.setOpaque(true);

        JMenuItem blueChoice = new JMenuItem("Fill Blue");
        //blueChoice.addActionListener(this);
        shapeColor.add(blueChoice);
//Draw Shapes
        JMenu shapeType = new JMenu("Shape Type");

        JMenuItem circle = new JMenuItem("Draw Circle");
                circle.addActionListener(new ActionListener() {
            Integer index;
            int x,y,r;

            @Override
            public void actionPerformed(ActionEvent e) {
                JPanel pn = new JPanel();
                JTextField xInput = new JTextField(5);
                JTextField yInput = new JTextField(5);
                JTextField rInput = new JTextField(5);
                pn.add(xInput);
                pn.add(yInput);
                pn.add(rInput);
                int result = JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
                if (result == JOptionPane.OK_OPTION) {
                   //don't forget to throw/catch exception here
                    x = Integer.parseInt(xInput.getText());
                    index = Integer.parseInt(xInput.getText());
                    y = Integer.parseInt(yInput.getText());
                    System.out.println(yInput.getText());
                    r = Integer.parseInt(rInput.getText());
                }
                toDraw(index.toString(),x,y,r);
            }
        });
        shapeType.add(circle);

        JMenuItem rectangle  = new JMenuItem("Draw Rectangle");
        //rectangle.addActionListener(this);
        shapeType.add(rectangle);

        JMenuItem rightTriangle  = new JMenuItem("Draw Right Triangle");
        //rightTriangle.addActionListener(this);
        shapeType.add(rightTriangle);

        JMenuBar bar = new JMenuBar( );
        bar.add(shapeColor);
        bar.add(shapeType);
        frame.setJMenuBar(bar);

    }
    ShapeArray shapes = new ShapeArray(4);
    void toDraw(String p, int x, int y,int r) {
       //ShapeArray d = new ShapeArray(4);
        Circle d = new Circle(p,x,y,r);
        frame.add(d);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.revalidate();
        frame.repaint();

    }

   /*public void actionPerformed(ActionEvent e)
    {
        String buttonString = e.getActionCommand( );

        //if (buttonString.equals("Fill Red"))
             //redPanel.setBackground(Color.RED);
        //else if (buttonString.equals("Fill Blue"))
            //bluePanel.setBackground(Color.BLUE);
        //if(buttonString.equals("Draw Circle"))
            //addShape(new Circle());// to add the shape when chosen
        //else
            //System.out.println("Unexpected error.");


        //String text = textField.getText();
        //textArea.append(text + newline);
        //textField.selectAll();

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        //textArea.setCaretPosition(textArea.getDocument().getLength());


    }*/
    
   /*class Draw extends JPanel {

    String inp;
    int xValue;
    int yValue;
    int radius;

    public Draw(String gn, int x, int y,int r) {
        inp = gn;
        xValue = x;
        yValue = y;
        radius = r;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        //Graphics2D g2 = (Graphics2D) g;

        drawCircle(g, xValue, yValue, radius);
        //g2.drawString(inp, x + (x / 2), x + (x / 2));
    }
    public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {
 
        cg.drawOval(xCenter-r, yCenter-r, 2*r, 2*r);
 
    }//end drawCircle

   }*/
}
Circle Class
Code:
import java.awt.*;
public class Circle extends Shape{

    public int radius;

    public Circle(String gn, int x, int y,int r) {
        //inp = gn;
        super.xValue = x;
        super.yValue = y;
        this.radius = r;
    }
//@Override
    public void draw(Graphics g) {
        //super.paintComponent(g);

        drawCircle(g, xValue, yValue, radius);
        //g2.drawString(inp, x + (x / 2), x + (x / 2));
    }
    public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {

        cg.drawOval(xCenter-r, yCenter-r, 2*r, 2*r);

    }//end drawCircle

}
Shape Class
Code:
import java.awt.*;
import javax.swing.*;
public abstract class Shape extends JPanel{

    public int xValue, yValue,area,perimeter;
    public Color color = Color.white;
    
   public Shape(){
          xValue=0;
          yValue=0;
          area=0;
          perimeter=0;

     }


      void setColor(Color color) {
             // Set the color of this shape
         this.color = color;
      }


      abstract void draw(Graphics g);
            // Draw the shape in the graphics context g.
            // This must be overriden in any concrete subclass

}
 

Easy Rhino

Linux Advocate
Joined
Nov 13, 2006
Messages
14,422 (3.50/day)
Likes
4,278
System Name VHOST01 | Desktop
Processor i7 980x | i5 7500 Kaby Lake
Motherboard Gigabyte x58 Extreme | AsRock MicroATX Z170M Exteme4
Cooling Prolimatech Megahelams | Stock
Memory 6x4 GB @ 1333 | 2x 8G Gskill Aegis DDR4 2400
Video Card(s) Nvidia GT 210 | Nvidia GTX 970 FTW+
Storage 4x2 TB Enterprise RAID5 |Corsair mForce nvme 250G
Display(s) N/A | Dell 27" 1440p 8bit GSYNC
Case Lian Li ATX Mid Tower | Corsair Carbide 400C
Audio Device(s) NA | On Board
Power Supply SeaSonic 500W Gold | Seasonic SSR-650GD Flagship Prime Series 650W Gold
Mouse N/A | Logitech G900 Chaos Spectrum
Keyboard N/A | Posiden Z RGB Cherry MX Brown
Software Centos 7 | Windows 10
#2
wish i could help you as it has been many years since i have written anything for swing. when i got stuck i would actually create what i wanted using netbeans and then learn from the code. i wouldn't steal the code, i would see how netbeans made it happen and that usually was enough information to help me solve the problem on my own. good luck.
 
Joined
Jun 17, 2007
Messages
7,326 (1.88/day)
Likes
995
Location
C:\Program Files (x86)\Aphexdreamer\
System Name Unknown
Processor AMD Bulldozer FX8320 @ 4.4Ghz
Motherboard Asus Crosshair V
Cooling XSPC Raystorm 750 EX240 for CPU
Memory 8 GB CORSAIR Vengeance Red DDR3 RAM 1922mhz (10-11-9-27)
Video Card(s) XFX R9 290
Storage Samsung SSD 254GB and Western Digital Caviar Black 1TB 64MB Cache SATA 6.0Gb/s
Display(s) AOC 23" @ 1920x1080 + Asus 27" 1440p
Case HAF X
Audio Device(s) X Fi Titanium 5.1 Surround Sound
Power Supply 750 Watt PP&C Silencer Black
Software Windows 8.1 Pro 64-bit
#3
I totally forgot about this thread.

I've gotten really far in my code. I've managed to draw circles with abstract shape class and more :D

I basically needed a paintComponent on a JPanel and then I needed to add it to my frame.

Thanks for the tip. That would be a clever way to go about.
 

Tman

New Member
Joined
Oct 14, 2013
Messages
1 (0.00/day)
Likes
0
#4
Im stuck

Hey I have the same problem in one of my assignments. Do you mind elaborating how you managed to solve it? I have values for everything but for some reason it just wont print! Please help!
 
Joined
Jun 17, 2007
Messages
7,326 (1.88/day)
Likes
995
Location
C:\Program Files (x86)\Aphexdreamer\
System Name Unknown
Processor AMD Bulldozer FX8320 @ 4.4Ghz
Motherboard Asus Crosshair V
Cooling XSPC Raystorm 750 EX240 for CPU
Memory 8 GB CORSAIR Vengeance Red DDR3 RAM 1922mhz (10-11-9-27)
Video Card(s) XFX R9 290
Storage Samsung SSD 254GB and Western Digital Caviar Black 1TB 64MB Cache SATA 6.0Gb/s
Display(s) AOC 23" @ 1920x1080 + Asus 27" 1440p
Case HAF X
Audio Device(s) X Fi Titanium 5.1 Surround Sound
Power Supply 750 Watt PP&C Silencer Black
Software Windows 8.1 Pro 64-bit
#5
Hey I have the same problem in one of my assignments. Do you mind elaborating how you managed to solve it? I have values for everything but for some reason it just wont print! Please help!
Post your code and I'll try and help you out.
 

Aquinus

Resident Wat-man
Joined
Jan 28, 2012
Messages
10,560 (4.77/day)
Likes
5,652
Location
Concord, NH
System Name Kratos
Processor Intel Core i7 3930k @ 4.2Ghz
Motherboard ASUS P9X79 Deluxe
Cooling Zalman CPNS9900MAX 130mm
Memory G.Skill DDR3-2133, 16gb (4x4gb) @ 9-11-10-28-108-1T 1.65v
Video Card(s) MSI AMD Radeon R9 390 GAMING 8GB @ PCI-E 3.0
Storage 2x120Gb SATA3 Corsair Force GT Raid-0, 4x1Tb RAID-5, 1x500GB
Display(s) 1x LG 27UD69P (4k), 2x Dell S2340M (1080p)
Case Antec 1200
Audio Device(s) Onboard Realtek® ALC898 8-Channel High Definition Audio
Power Supply Seasonic 1000-watt 80 PLUS Platinum
Mouse Logitech G602
Keyboard Rosewill RK-9100
Software Ubuntu 17.10
Benchmark Scores Benchmarks aren't everything.
#6