JFrame program and running another class in Java - java

So currently I want to use a jframe program that would run another class in a window.
A working example:
Jframe:
import javax.swing.JFrame;
public class FaceJFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("A Rectangle Object in a JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Face aRectangle = new Face();
frame.add(aRectangle);
frame.setVisible(true);
}
}
The program:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
public class Face extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// Construct face and eyes
Rectangle face = new Rectangle(0, 0, 50, 50);
Rectangle eye = new Rectangle(5, 5, 15, 15);
Rectangle eye2 = new Rectangle(25, 5, 15, 15);
//make some lines for the mouth
Line2D mouth1 = new Line2D.Double(15, 30, 15, 35);
Line2D mouth2 = new Line2D.Double(15, 35, 35, 35);
Line2D mouth3 = new Line2D.Double(35, 35, 35, 30);
// draw the rectangle
g2.draw(face);
g2.draw(eye);
g2.draw(eye2);
g2.draw(mouth1);
g2.draw(mouth2);
g2.draw(mouth3);
}
}
With these two code snippets, running the Jframe one in cmd would give a pop-up window with a little face on it.
I want to do the same with the following code:
Jframe:
import javax.swing.JFrame;
public class Car_JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("a car");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Car aRectangle = new Car();
frame.add(aRectangle);
frame.setVisible(true);
}
}
and the main class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
public class Car
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle body = new Rectangle(0, 10, 60, 20);
Line2D roof1 = new Line2D.Double(10, 10, 20, 0);
Line2D roof2 = new Line2D.Double(20, 0, 40, 0);
Line2D roof3 = new Line2D.Double(40, 0, 50, 10);
Ellipse2D.Double wheel1 = new Ellipse2D.Double(15, 25, 10,10);
Ellipse2D.Double wheel2 = new Ellipse2D.Double(45, 25, 10,10);
// draw the rectangle
g2.draw(body);
g2.draw(roof1);
g2.draw(roof2);
g2.draw(roof3);
g2.draw(wheel1);
g2.draw(wheel2);
}
}
It doesn't produce the same result. In fact, running car_jframe in cmd would output the face program. (they're in the same blueJ project)
What should I do?

Your main problem is that your Car class does not extend JPanel or JComponent or any class that derives from these, and so it cannot be added to your JFrame, and any attempts to do so will result in a compilation error. You have two main possible solutions:
Make Car a true component by having it extend JPanel (or JComponent, but I recommend JPanel).
Or if you want Car to be a logical class and not a component class, then create a JPanel that contains a Car object and that draw the Car object by directly calling that object's paintComponent method within the JPanel's own paintComponent method.
Other notes:
You almost always want to call the super.paintComponent(g) method within your override so that the JPanel can do housekeeping painting.
You always want to preface any method that you think is an override method with the #Override annotation as this way the compiler will warn you if your assumption is incorrect.
e.g.,
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.*;
import javax.swing.*;
public class TestCar {
private static void createAndShowGui() {
Car mainPanel = new Car();
JFrame frame = new JFrame("A Car");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
// start all code on the Swing event thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Car extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final Rectangle BODY = new Rectangle(0, 10, 60, 20);
private static final Line2D ROOF_1 = new Line2D.Double(10, 10, 20, 0);
private static final Line2D ROOF_2 = new Line2D.Double(20, 0, 40, 0);
private static final Line2D ROOF_3 = new Line2D.Double(40, 0, 50, 10);
private static final Ellipse2D WHEEL_1 = new Ellipse2D.Double(15, 25, 10,10);
private static final Ellipse2D WHEEL_2 = new Ellipse2D.Double(45, 25, 10,10);
public Car() {
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// draw the rectangle
g2.draw(BODY);
g2.draw(ROOF_1);
g2.draw(ROOF_2);
g2.draw(ROOF_3);
g2.draw(WHEEL_1);
g2.draw(WHEEL_2);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
If you want to get real fancy, use a Path2D object, AffineTransform and a Swing Timer and give your GUI a little animation:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Car2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final Rectangle BODY = new Rectangle(0, 10, 60, 20);
private static final Line2D ROOF_1 = new Line2D.Double(10, 10, 20, 0);
private static final Line2D ROOF_2 = new Line2D.Double(20, 0, 40, 0);
private static final Line2D ROOF_3 = new Line2D.Double(40, 0, 50, 10);
private static final Ellipse2D WHEEL_1 = new Ellipse2D.Double(15, 25, 10,
10);
private static final Ellipse2D WHEEL_2 = new Ellipse2D.Double(45, 25, 10,
10);
private static final int TIMER_DELAY = 30;
private static final int CAR_DELTA_X = 1;
private static final int CAR_DELTA_Y = CAR_DELTA_X;
private Path2D path2D = new Path2D.Double();
public Car2() {
path2D.append(BODY, false);
path2D.append(ROOF_1, false);
path2D.append(ROOF_2, false);
path2D.append(ROOF_3, false);
path2D.append(WHEEL_1, false);
path2D.append(WHEEL_2, false);
new Timer(TIMER_DELAY, new CarTimerListener()).start();;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(path2D);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
class CarTimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
path2D.transform(AffineTransform.getTranslateInstance(CAR_DELTA_X, CAR_DELTA_Y));
repaint();
}
}
}

You should only have one main method in your application. I'd change it like below to let the user select which shape to print when running the application.
import javax.swing.JFrame;
public class DrawFrame {
public static void main(String[] args) {
if(args[0].equals("face") {
paintFace()
}
else if(args[0].equals("car") {
paintCar();
}
else {
System.out.println("No Shape Selected to Print");
}
}
private static paintFace() {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("A Rectangle Object in a JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Face face = new Face();
frame.add(face);
frame.setVisible(true);
}
private static paintCar() {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("a car");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Car car = new Car();
frame.add(car);
frame.setVisible(true);
}
}
Also your car does not extend Component. It won't work.
Correct it as
public class Car extends JComponent { ... }

Related

intersectsLine() function is not working as expected

I am trying to check if a line intersects a set of rectangles.
This is my code:
public class Test {
public static void main(String args[]) {
Rectangle2D.Double rectangle1 = new Rectangle2D.Double(32, 64, 32, 32);
Rectangle2D.Double rectangle2 = new Rectangle2D.Double(0, 32, 32, 32);
Line2D.Double line = new Line2D.Double(36, 63, 5, 12);
System.out.println(rectangle1.intersectsLine(line)); // outputs false. Why?
System.out.println(rectangle2.intersectsLine(line)); // outputs true as expected
}
}
As you can see, the start point (36, 63) is within rectangle1, but apparently this line segment doesn't intersect the rectangle that it starts in.
However, it intersects the rectangle that stores the end point (5, 12).
Any idea why?
How do I get it to detect intersection?
The line does not intersect rectangle1, and that's why Java is giving you back the correct answer. Draw the lines in a GUI and see for yourself. Perhaps you're confused on the Rectangle2D.Double constructor -- the last parameters are width and height.
Draw the GUI and see; they almost touch, but not quite:
Drawing both rectangles:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.*;
import javax.swing.*;
public class Test extends JPanel {
private static final int PREF_W = 850;
private static final int PREF_H = PREF_W;
Rectangle2D rectangle1 = new Rectangle2D.Double(32, 64, 32, 32);
// Rectangle2D rectangle2 = new Rectangle2D.Double(0, 32, 32, 32);
Line2D line = new Line2D.Double(36, 63, 5, 12);
public Test() {
// TODO Auto-generated constructor stub
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
double scale = 8.0;
g2.scale(scale, scale); // make it big to show it for you
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.draw(rectangle1);
// g2.draw(rectangle2);
g2.draw(line);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Test mainPanel = new Test();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Drawing to a Panel from separate classes

I have been trying to learn how to draw to a Jpanel for a game. I want to draw to it from different classes (like a class that manages maps and a class that manages player models).
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Java Game");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (1000, 600);
JPanel panel = new JPanel();
panel.setBackground (Color.WHITE);
Dimension size = new Dimension(1000,500);
panel.add (new Player()); // Class with paintComponent method.
panel.setPreferredSize(size);
panel.setBackground(Color.BLUE);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
next class
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
#SuppressWarnings ("serial")
public class Player extends JComponent
{
int x = 50;
int y = 450;
public void paintComponent (Graphics g)
{
super.paintComponent(g);
g.setColor (Color.BLACK);
g.fillRect (x, y, 50, 50);
}
}
You probably want to extend JPanel. It's already opaque, and it can handle the background color for you. Also give your panel a size like they do here, then you can do the drawing relative to the size.
Player p = new Player();
p.setBackground(Color.cyan);
frame.add(p);
frame.pack();
frame.setVisible(true);
…
public class Player extends JPanel {
private static final int X = 320;
private static final int Y = 240;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(getWidth() / 2 - 25, getHeight() / 2 - 25, 50, 50);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(X, Y);
}
}

Java window doesn't repaint properly until I resize the window manually

I am using a quite basic setup with a class extending JPanel, which I add to a JFrame.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class PinTestMCVE extends JPanel implements ActionListener{
BufferedImage loadedImage;
JButton calcButton;
public static void main(String[] args) {
new PinTestMCVE();
}
public PinTestMCVE() {
loadedImage = getTestImage();
JPanel toolbarPanel = new JPanel();
calcButton = new JButton("calcButton...");
toolbarPanel.add(calcButton);
calcButton.addActionListener(this);
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(toolbarPanel, BorderLayout.NORTH);
jf.getContentPane().add(this, BorderLayout.CENTER);
jf.setSize(1250, 950);
jf.setVisible(true);
}
public void paintComponent(Graphics g) {
g.drawImage(loadedImage, 0, 0, this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent " + e.getActionCommand());
if(e.getSource().equals(calcButton)){
this.repaint();
}
}
//Please ignore the inner workings of this
public static BufferedImage getTestImage(){
BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setPaint(Color.GRAY);
g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(Color.gray);
int x = 5;
int y = 7;
GradientPaint redtowhite = new GradientPaint(x, y, Color.red, 200, y, Color.blue);
g2d.setPaint(redtowhite);
g2d.fill(new RoundRectangle2D.Double(x, y, 200, 200, 10, 10));
return image;
}
}
What happens is that INITIALLY the window is painted properly, but once paintComponent is called, a strip of the old image (with the same height as the toolbar panel) is visible below the newly painted images - similar to playing card sticking out from a deck. But then, if I manually resize the window by for instance dragging the border, the background is grayed out as it should.
What is going on and how do I fix this?
As outlined here, you need to pack() the frame before calling setVisible(). You can override getPreferredSize() to specify a suitable initial Dimension. Also consider using a Border. See also Initial Threads.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.*;
public class PinTestMCVE extends JPanel implements ActionListener{
private static final int SIZE = 200;
BufferedImage loadedImage;
JButton calcButton;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new PinTestMCVE();
}
});
}
public PinTestMCVE() {
loadedImage = getTestImage();
JPanel toolbarPanel = new JPanel();
calcButton = new JButton("calcButton...");
toolbarPanel.add(calcButton);
calcButton.addActionListener(this);
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(toolbarPanel, BorderLayout.NORTH);
jf.add(this, BorderLayout.CENTER);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(loadedImage, 0, 0, this);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent " + e.getActionCommand());
if(e.getSource().equals(calcButton)){
this.repaint();
}
}
//Please ignore the inner workings of this
public static BufferedImage getTestImage(){
BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setPaint(Color.GRAY);
g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(Color.gray);
GradientPaint redtowhite = new GradientPaint(5, 5, Color.red, SIZE, 5, Color.blue);
g2d.setPaint(redtowhite);
g2d.fill(new RoundRectangle2D.Double(5, 5, SIZE - 10, SIZE - 10, 10, 10));
return image;
}
}

Creating and overriding a shape to fit into JPanel?

In this program a polygon is created to show up into a JPanel tab.
In-order to make it show I had to over-ride the shape and create a setter method for it. Unfortunately it is not showing and the program is not running either.
The error:
Exception in thread "main" java.lang.IllegalArgumentException: adding
a window to a container
at SelectShape component1 = new SelectShape(x, y, vert); in method
Page1.
The only way it would work is by making a frame and removing the JTab and assigning the shape onto the frame but that is not what I want to make. I want to make a program that can distribute shapes to * different tabs* using one graphics method.
Here is the code:
import java.awt.*;
import java.io.IOException;
import javax.swing.*;
/* This program create a graphics component that draws a polygon
*/
public class SelectShape extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel panel1;
// //////////////////////////
static int[] x = { 20, 40, 50, 65, 80, 95 }; // Co-ords for a polygon
static int[] y = { 60, 105, 105, 110, 95, 95 };
static int vert = 6;
public SelectShape() throws IOException // Builds GUI
{
setTitle("Program");
setSize(900, 600);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
// Create the tab pages
createPage1();
// Create a tabbed pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab("Shape Panel", panel1);
}
public void createPage1() throws IOException // Creates JPanel
{
panel1 = new JPanel();
panel1.setLayout(null);
SelectShape component1 = new SelectShape(x, y, vert); //error
SelectShape component2 = new SelectShape(x, y, vert); //over-rides shape
component1.setBounds(290, 70, 120, 40);
component2.setBounds(290, 70, 120, 40);
panel1.add(component1); // is not displayed!
panel1.add(component2); // component2 overwrites component1!!!
panel1.setVisible(true);
}
// overrides javax.swing.JComponent.paintComponent
public void paintComponent(Graphics g) {
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Construct a polygon then draw it
Polygon polygon = new Polygon(x, y, vert);
g2.draw(polygon);
g2.fill(polygon);
}
public SelectShape(int[] x, int y[], int vert) { // setter method
this.x = x;
this.y = y;
this.vert = vert;
}
public static void main(String[] args) throws IOException {
SelectShape mainFrame = new SelectShape(); //Frame
mainFrame.setVisible(true);
}
}
I think you are mixing many concepts together in your code which eventually leads to ununderstandable code.
JFrame does not extends JComponent and does not have a paintComponent method. Consider using the #Override annotation on methods that override another. This will allow you to easily mistakes like this.
No need to extend JFrame anyway and never override the paint() method of a Top-level container (JDialog, JFrame, ...)
Always invoke the super method of paintXXX methods
public SelectShape(int[] x, int y[], int vert) { // setter method is not a setter method. It is a constructor that takes 3 arguments and assign them. In all cases, this does absolutely nothing in your case because you made those variables static. Avoid the use of static unless if you describe constants, in which case it should be also followed by the final keyword.
Start the UI, and perform all modifications to the UI, on the Event Dispatching Thread (EDT). This can easily be done by using SwingUtilities.invokeLater().
The error you are seeing: Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container is thrown because you are trying to add a JFrame to a JComponent which is forbidden. JFrame cannot be added to anything. If you want to do that, you need to use JDesktopPane and add JInternalFrame (but that is another story).
I am not too sure as to what you are trying to achieve, but here is a working code derived from yours which works much better:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
/* This program create a graphics component that draws a polygon
*/
public class SelectShape extends JPanel {
// Constants
private static final int[] x = { 20, 40, 50, 65, 80, 95 }; // Co-ords for a polygon
private static final int[] y = { 60, 105, 105, 110, 95, 95 };
private static final Polygon POLYGON = new Polygon(x, y, Math.min(x.length, y.length));
private static final Ellipse2D CIRCLE = new Ellipse2D.Double(100, 40, 45, 45);
// Class variables
private final Shape shape;
private Dimension preferredSize;
public SelectShape(Shape shape) {
this.shape = shape;
Rectangle bounds = shape.getBounds();
this.preferredSize = new Dimension(bounds.x + bounds.width, bounds.y + bounds.height);
}
#Override
public Dimension getPreferredSize() {
return preferredSize;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.BLUE);
g2.draw(shape);
g2.fill(shape);
}
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame mainFrame = new JFrame("Program");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SelectShape polygon = new SelectShape(POLYGON);
SelectShape circle = new SelectShape(CIRCLE);
// Create a tabbed pane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Polygon", polygon);
tabbedPane.addTab("Circle", circle);
mainFrame.add(tabbedPane);
mainFrame.pack();
mainFrame.setVisible(true);
}
});
}
}

How do I draw a circle and rectangle with specified radius?

I am trying to draw a circle of a radius 60 centerd in the lower right quarter of the frame, and a square of radius 50 centered in the upper half of the frame.
The frame size is 300 x 300.
I've done this till now.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class Test {
public static void main ( String[] args){
JFrameTest5 frame = new JFrameTest5();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setTitle("Test");
}
}
class JFrameTest5 extends JFrame {
public JFrameTest5()
{
setLocation(0,0);
setSize(300,300);
PanelTest1 panel = new PanelTest1();
add(panel);
}
}
class PanelTest1 extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Ellipse2D circle = new Ellipse2D.Double(250, 225, 120,120);
g2.draw(circle);
Rectangle2D rect = new Rectangle2D.Double(75,0,100,100);
g2.draw(rect);
}
}
The problem is the circle and the rectangle don't seem to be right , are there another methods to set the exact radius ?
The example below includes several important changes:
Use constants wherever possible.
Use panel-relative geometry.
Use initial threads correctly.
Use pack() to size the enclosing frame.
Code:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/a/10255685/230513 */
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrameTest frame = new JFrameTest();
}
});
}
}
class JFrameTest extends JFrame {
public JFrameTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test");
this.add(new JPanelTest());
this.pack();
this.setLocationByPlatform(true);
this.setVisible(true);
}
}
class JPanelTest extends JPanel {
private static final int R = 60;
private static final int D = 2 * R;
private static final int W = 50;
private static final int E = 2 * W;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(
getWidth() - D, getHeight() - D, D, D);
g2.draw(circle);
Rectangle2D rect = new Rectangle2D.Double(0, 0, E, E);
g2.draw(rect);
}
}

Categories