Eclipse do not show output - java

I'm making 2D drawing on Eclipse Oxygen, there are no error in my code but why it does not show any output. I mean when I click run there are no progress.
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Rectangle2D;
public class HOUSE1 extends Frame {
public void paint(Graphics2D g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("HOME SWEET HOME",80,60);
setBackground(Color.white);
Arc2D arc1 = new Arc2D.Double(250,50,500,300,225,90,Arc2D.Double.PIE);
g2d.draw(arc1);
g2d.setColor(Color.red);
g2d.fill(arc1);
Rectangle2D rect = new Rectangle2D.Double(325,300,350,300);
g2d.draw(rect);
g2d.setColor(Color.blue);
g2d.fill(rect);
Rectangle2D rect1 = new Rectangle2D.Double(325,300,350,300);
g2d.draw(rect1);
g2d.setColor(Color.black);
g2d.fill(rect1);
}
public static void main(String[]args){
HOUSE1 f = new HOUSE1();
f.setTitle("HOUSE");
f.setSize(300,100);
}
}

1st: In your main void you need to set your frame (f) to visible --> f.setVisible(true)
2nd: Also you might want to f.pack(); right before you set it to visible to to make sure your components are behaving like expected.
3th: In java we use a capital first letter in class like this "House", fully capital words are used for final's.

Your window is blank because your paint method is never called. Your method
public void paint(Graphics2D g) // DOESN'T WORK
needs to be changed to
public void paint(Graphics g) // Correct
so that it overrides the paint method in Frame. The graphics system will only call paint(Graphics); if your method called paint isn't overriding the method paint(Graphics) in Frame, the one in Frame gets called instead of yours.

You forgot to make your frame visible.
Just add :
f.setVisible(true);
You have to fix your paint method declaration to :
#override
public void paint(Graphics g) {
// your code
}

Related

Rectangle won't display in JFrame

So I've been trying for the last two hours to get this program to draw a simple rectangle in a frame but nothing gets displayed in the frame when i run the program. I've looked through textbooks and old notebooks and everything in my program seems to be fine, yet nothing is displayed. Help?
This is the class that creates the frame and is supposed to draw the rectangle.
import javax.swing.JFrame;
public class FrameViewer {
public static void main(String[] args) {
//creates an empty frame.
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//draws the rectangle within the frame.
RectangleComponent component = new RectangleComponent();
frame.add(component);
frame.setVisible(true);
}
}
And here is the RectangleComponent
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class RectangleComponent extends JComponent{
public void paintCOmponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
Rectangle box = new Rectangle(5,10,20,30);
g2.draw(box);
}
}
Java is case sensitive, instead of
paintCOmponent
You want
paintComponent
You should use the #Override annotation to mark methods you think you are overriding as it will highlight problems like this.
The method should also remain protected, as there is no reason any one should be calling from outside the class
You may also want to take a look at Initial Threads

Rectangle2D, borders go missing?

Helo guys,
my problem is that sometimes if my Rectangle2D gets a big width or height its bottom,left border splits and no longer makes a continous border and if I even make it wider the border goes smaller and smaller, like if there were a limitation of how long a rectangles border can be... It is really confusing and so far I have not found the solution :S I put there a link to a picture so you can see for yourself.
new Rectangle2D.Double(mojrectangle.getUpperleftPointmojRectangle().getX(), mojrectangle.getUpperleftPointmojRectangle().getY(),1000,1000)
repaint();
thanks for your help..
BTW I have the same problem with Arc2D if it gets really big
UPDATE: I removed from the function the setStroke command and now it draws it correctly, but in the future I will need to set the Rectangles stroke so it leaves me sad.
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
//g2.setStroke(stroke);
g2.draw(rectangle);
}
Here I put an example code of my project, please try it with g2.setStroke(selectedstroke)- it wont work, and without it...I hope I explained myself clear .
package com.awtgraphicsdemo;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JComboBox;
public class AWTgraphicsdemo extends Frame {
final float dash[] = {10.0f};
final float solid[] = {1000.0f}; // these must be in an Array
float lineWidth[]={2.0f,4.0f,6.0f,8.0f,10.0f}; // width of the drawing line
String[] lineWidthString={"2.0","4.0","6.0","8.0","10.0"};
JComboBox strokecombobox=new JComboBox(lineWidthString);
BasicStroke selectedStroke = new BasicStroke(lineWidth[0],BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f, solid, 0.0f);
public AWTgraphicsdemo(){
super("Java AWT Examples");
prepareGUI();
}
public static void main(String[] args){
AWTgraphicsdemo awtGraphicsDemo = new AWTgraphicsdemo();
awtGraphicsDemo.setVisible(true);
}
private void prepareGUI(){
setSize(400,400);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
#Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(selectedStroke);
g2.draw (new Rectangle2D.Double(10, 10, 1000, 900));
Font font = new Font("Serif", Font.PLAIN, 24);
g2.setFont(font);
g.drawString("Welcome to TutorialsPoint", 50, 70);
g2.drawString("Rectangle2D.Rectangle", 100, 120);
}
}
Helo again,
I figured out my problem, it was in the properties of stroke,so after some lenght of the compoment the stroke got activated which made changed to the drawn shape.By modifying the strokes solid array I was able the get the result I wanted.
Thank you for your help and suggestions :)
Take Care
Better to:
Not override paint(...) in top level windows (as MadProgrammer states) since this also changes painting of borders and child components -- a dangerous thing to do.
Instead override paintComponent(...) of a JPanel (again as MadProgrammer states) and place that JPanel into your top level window.
Don't set the Stroke of the Graphics object passed into your painting method, but rather a copy of the Graphics object so not to have side effects down the road.
e.g.,
public class MyPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setStroke(....);
// do drawing with g2 here
g2.dispose();
}
}

Trying to use drawString method to print a name

I'm just going through some basic tutorials at the moment. The current one wants a graphics program that draws your name in red. I've tried to make a NameComponent Class which extends JComponent, and uses the drawString() method to do this:
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;
public class NameComponent extends JComponent {
public void paintMessage(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.drawString("John", 5, 175);
}
}
and use a NameViewer Class which makes use of JFrame to display the name:
import javax.swing.JFrame;
public class NameViewer {
public static void main (String[] args) {
JFrame myFrame = new JFrame();
myFrame.setSize(400, 200);
myFrame.setTitle("Name Viewer");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
NameComponent myName = new NameComponent();
myFrame.add(myName);
myFrame.setVisible(true);
}
}
...but when I run it, the frame comes up blank! Could anyone let me know what I'm doing wrong here?
Thanks a lot!
You need to override the method paintComponent rather than paintMessage. Adding the #Override annotation over the method will show that paintMessage is not a standard method of JComponent. Also you may want to reduce the y-coordinate in your drawString as the text is currently not visible due to the additional decoration dimensions of the JFrame. Finally remember to call super.paintComponent to repaint the background of the component.
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.drawString("John", 5, 100);
}
See: Painting in AWT and Swing
You need to add this line after public void paintMessage(Graphics g){ :
super.paint(g);
This tells Java to use the superclass (JComponent) to paint the message.
You will also need to call your method paintComponents() rather than paintMessage()

How to rotate the square in my swing app

I have developed a little swing application in which i have drawn a square.Now i want to rotate this square at its center using Thread.The problem i'm having is how to get reference to that square in my rotateSquare() method.
(Actually i need a method,if possible, to rotate the same square instead of wiping out the entire content pane and drawing another rotated square at its position).
Here is my code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Rotation extends JFrame implements Runnable{
Thread t;
Rotation()
{
super("Animation of rotation about center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setContentPane(new Container(){
public void paint(Graphics g)
{
Graphics2D g2=(Graphics2D)g.create();
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, getWidth(), getHeight());
g2.setColor(Color.GRAY);
g2.fillRect(100, 100, 100, 100);
}
});
t=new Thread(this,"pr");
t.start();
setVisible(true);
//setOpacity(0.8f);
}
public void run()
{
try{
for(;;)
{
Thread.sleep(100);
SwingUtilities.invokeLater(new Runnable(){public void run(){
rotateSquare();
}});
}
}catch(InterruptedException e){System.out.println("Thread interrupted");}
}
public void rotateSquare();
{
}
public static void main(String args[])
{
//setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable(){public void run(){new Rotation();}});
}
}
see AffineTransform
add parameters AffineTransform.rotate(intDegrees);
fit rotated Object to the parents bounds myAffineTransform.translate(getWidth(), getHeight())
then returns back Graphics2D#transform(myAffineTransform);
use Swing Timer instead of Runnable#Thread with Thread.sleep(int), that caused freeze or flickering for Graphics2D and locked EventDispatchThread untill endless Thread ended (never ending in your case)
You should define a Square class that would include code defining a square object. This would have a draw(Graphics g) method that would know how to draw the Square.
In your other class, you would have a reference to a Square object. Under the paint method you would call square.draw(g).
This way, you can apply the rotation under the Square draw() method.

paint(Graphics g) function is called but I don't know Where?

package donut;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
public class Board extends JPanel{
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
RenderingHints rh =
new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(rh);
Dimension size = getSize();
double w = size.getWidth();
double h = size.getHeight();
Ellipse2D e = new Ellipse2D.Double(0, 0, 80, 130);
g2.setStroke(new BasicStroke(1));
g2.setColor(Color.gray);
for (double deg = 0; deg < 360; deg += 5) {
AffineTransform at =
AffineTransform.getTranslateInstance(w / 2, h / 2);
at.rotate(Math.toRadians(deg));
g2.draw(at.createTransformedShape(e));
}
}
}
Then The JFrame Extended Class Where Board Object is instantiated
package donut;
import javax.swing.JFrame;
public class Donut extends JFrame {
public Donut() {
add(new Board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(360, 310);
setLocationRelativeTo(null);
setTitle("Donut");
setVisible(true);
}
public static void main(String[] args) {
new Donut();
}
}
I was expecting to See Line Like this : new Board().paint(graphicsObject) So Where Actually This Line is executed Or in a proper way Where actually paint(Graphics g) function is called ?!
If you want to follow the invocation stack to paint(), simply write new Throwable().printStackTrace() or Thread.dumpStack(), this will allow you to follow the calling-stack.
Otherwise, have a look at RepaintManager.addDirtyRegion(JComponent, int, int, int, int);
Anyway, when you are painting to the screen, you should never call paint/paintComponent/paintXXX methods. Only call repaint().
You cannot rely on "when" your method paintComponent(Graphics) or paint(Graphics) will be invoked.
paint is automatically called by Swing whenever it is needed, for example when the component becomes visible (for the first time, or after a minimize of the window, etc), or when the window is resized, basically whenever the contents of a component need to be painted. You should never explicitly call paint in your code, if you wish to force paint then you should call repaint instead.
This link might be helpful
P.S. The code of paint method that is called by super.paint(g) resides in JComponent class, which is extended by JPanel (which is extended by your Board class).

Categories

Resources