Java: How do I draw my rectangle in my JFrame? [duplicate] - java

This question already has answers here:
drawing simple rectangles on a Jframe in java
(3 answers)
Closed 6 years ago.
I am trying to draw a rectangle in my JFrame but when I run it it just comes up blank. I have tried a few other ways to draw it, but they all come up the same. Keep in mind I'm pretty new, so I'm sorry if there are any obvious mistakes :P.
import javax.swing.*;
import java.awt.*;
public class Main {
JFrame jf1;
public Main() {
jf1 = new JFrame("Draw");
jf1.setVisible(true);
jf1.setSize(900, 700);
jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jf1.setLocation(dim.width/2-jf1.getSize().width/2, dim.height/2-jf1.getSize().height/2);
}
public void paint(Graphics g) {
g.fillRect(0, 60, 100, 50);
g.setColor(Color.BLACK);
}
public static void main(String[] args) {
Main shoe = new Main();
}
}

Your class has a paint method but it's meaningless since the class extends no GUI component and the method is not a true painting method override. Rather than guess at this stuff, read the graphics tutorials:
Lesson: Performing Custom Painting: introductory tutorial to Swing graphics
Painting in AWT and Swing: advanced tutorial on Swing graphics
Then create a class that extends JPanel and draw in its paintComponent method as the tutorials will show you. Place your JPanel in a JFrame and you should be good.
Also -- remember to append #Override before any method that you think should override a super class's method. If you had done this, the compiler would have complained that your paint method is not in fact overriding anything. Also, don't forget to call the super's paintComponent method as well explained in the first tutorial.

Related

Can't draw to canvas: "cannot be applied to given types"

I used a border layout and I put a canvas in the center; where the main game will be, but I can't draw anything to it.
Could anyone point me in the right direction?
import java.awt.*;
import javax.swing.*;
public class TestingGraphics {
public static void main (String[] args) {
GameScene window = new GameScene();
}
}
import java.awt.*;
import javax.swing.*;
public class GameScene extends JFrame {
Canvas gameCanvas;
Graphics Pencil;
JPanel game;
public GameScene() {
game = new JPanel();
add(game);
setTitle("Yet to name this thing.");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameCanvas = new Canvas();
gameCanvas.setPreferredSize(new Dimension(1280, 720));
game.add(gameCanvas);
drawString();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void drawString(Graphics Pencil) {
Pencil.drawString("boo", 100, 100);
}
}
Your problem is that you're making wild guesses on how to draw in Swing and that never works, and your errors include trying to draw directly within a JFrame, trying to call a method without passing in necessary parameters, drawing outside of any painting method.... First and foremost, go to the Swing drawing tutorials which you can find here: Swing Drawing Tutorials -- and read them.
Next, do as they tell you:
Create a class that extends JPanel
Draw in the paintComponent method override of that class, not directly in a JFrame
Be sure to call the super's paintComponent method in your overridden method.
Add your JPanel to a top-level window such as a JFrame
Display the GUI
Done.

Japplet shapes does not shown in Applet

Im working with eclipse.
My Code:
import javax.swing.JApplet;
import java.awt.*;
public class Einstein extends JApplet
{
public void pain(Graphics page)
{
page.drawRect(60,60,40,40); // Square
page.drawString("Out of clutter, find simplicity. " , 110, 70);
}
}
The rectangle and text does not shown in the applet.
what could be the problem?
public void pain(Graphics page) - interesting choice of naming...
I believe the method you're looking for is paint
#Override
public void paint(Graphics g) {
super.paint(g);
//...
}
Make sure you call super.paint before performing any custom painting, otherwise you could end up with a bunch of nasty paint artefacts.
Having said that. Consider using a custom component, extending from JPanel for example, and override it's paintComponent method instead, then add this component to your applet.
You gain the benefit of the double buffering support of Swing for free and the freedom to move you component to another container, like a JFrame or other container for example, making it far more re-usable

Clearing drawings on Jframe

I am making a game in which I move a square with my mouse, but when I move my mouse the old squares do not delete, which results in a trail of squares. I would like it to only have the one square which is following my mouse. This is currently my code. I have read to use paintcomponents but I am not sure how to use it since I am still a beginner.
This is in my "GamePanel" Class
public void mouseMoved(MouseEvent m) {
Graphics g= this.getGraphics();
h.changeX(m.getX());
h.changeY(m.getY());
h.drawHero(g);
}
This is in my "Hero" Class
public void drawHero(Graphics g){
g.drawImage(heroPic,stX,stY,null); //heroPic is a picture I imported
Don't use the this.getGraphics(). That is something you will definitely not want to to do, since it produces artifacts (as you mentioned).
It would be better to store the mouse position as a variable, then handle all the rendering when the paintComponent(Graphics) method has been called. Be sure to also call super.paintComponent(Graphics) to get rid of artifacts.
Generally, you should only handle graphics inside the paintComponent(Graphics) method and in any methods that are called only from the paintComponent(Graphics) method.
Here is a question which touches on why you should avoid Component#getGraphics(): Drawing an object using getGraphics() without extending JFrame
Here is another question I answered revolving around rendering with graphics: Java JFrame draw
Use a seperate class that extends JPanel :
class DrawPane extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(heroPic, x, y, this);
}
}
Then create a variable that will hold this class object :
DrawPane dp = new DrawPane();
after that set the variable to the contence pane. :
JFrame.setContencePane(dp);
Now to repaint this do :
dp.repaint();
Do not worry about the 'Graphics g' you wont have to input anything.

Using awt.Graphics in a method

I created a class called Test, most likely where I went wrong.
import javax.swing.JPanel;
import java.awt.*;
public class Test extends JPanel {
Graphics grap;
public void sun()
{
super.paintComponent(grap);
grap.setColor(Color.YELLOW);
grap.fillOval(0,0,20,20);
}
}
As you can see I want to paint a yellow "Oval" in the top left corner of the panel using a method but I did not use a PaintComponent method. Now I try to implement it in my Paint component method which is in a class called Painting.
//import...;
public class Painting extends JPanel{
protected void paintComponent(Graphics g)
{
Test test = new Test();
test.sun();
}
And now i created a main window that will create a panel and display the yellow oval.
//import...
public class main extends JFrame{
public static main(String [] args){
JFrame window = new JFrame();
window.add(new Painting());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(100,100);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
But this does not work. I have a feeling that it is the sun method in test. How would I get this to work? I have looked in all the java books and cant find anything that can help.
Please note that I do not what to add parameters to the method.
Thank You
Tom.
Few points to be noted here:
Never call super.paintComponent by yourself except within the overriden paintComponent method itself.
If you want to do some Graphics activities then override the paintComponent method and draw graphics over there
When you are overriding paintComponent method then the first statement within the method should be super.paintComponent(g).
Now, going by all above points your code should now be like this:
public class Test extends JPanel {
public void paintComponent(Graphics grap)
{
super.paintComponent(grap);
grap.setColor(Color.YELLOW);
grap.fillOval(0,0,20,20);
}
}
And your Painting class should be like this:
public class Painting extends JPanel{
Test test;
public Painting()
{
test = new Test();
setLayout(new BorderLayout());
add(test);
}
}
If i want to draw 50 ovals on different places then i would have a problem with extensive code
Then you would keep a List of the ovals that you want to paint. See Custom Painting Approaches which paints a bunch of Rectangles on a panel. All the code does is loop through the ArrayList to paint the Rectangle. Only a couple of lines of code are required.

JApplet behaving unexpectedly

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.Timer;
public class CountingSheep extends JApplet
{
private Image sheepImage;
private Image backgroundImage;
private GameBoard gameBoard;
private scoreBoard scoreBoard;
public void init()
{
loadImages();
gameBoard = new GameBoard(sheepImage, backgroundImage);
scoreBoard = new scoreBoard();
getContentPane().add(gameBoard);
getContentPane().add(scoreBoard);
}
public void loadImages()
{
sheepImage = getImage(getDocumentBase(), "sheep.png");
backgroundImage = getImage(getDocumentBase(), "bg.jpg");
}
}
The program works correctly when nothing but the GameBoard class is added to the JApplet, however, when I try to add the ScoreBoard class, both Panel classes do not show on the Applet. I'm guessing this is now down to positioning? Any ideas?
EDIT: Gone back to the previously asked question Hovercraft, and found it was due to the layout of the contentPane and the order at with the components were added.
Some suggestions:
Don't draw in the paint method of a JApplet as that is a top-level window and should not be drawn directly on. Instead draw in the paintComponent(Graphics g) method of a JPanel or other JComponent, and then add that JPanel to the JApplet's contentPane.
Similar to his advice about the super call, your first method call in this method should be the super.paintComponent(g); which will refresh the JPanel's graphics.
The flicker is from your drawing directly in the JApplet's paint method. If you do as I suggest, you'll take advantage of Swing's use of double buffering.
Since this is a Swing application, you should avoid using KeyListeners and instead use Key Bindings.
Don't get the Graphics object of a component by calling `getGraphics(). The Graphics object obtained will be short-lived and thus will not persist after any repaint.
The code you've posted above is somewhat confusing to me. What are you trying to do with it? You've added components to the JApplet, and these components should handle their own graphics, and then you're painting on the JApplet as well. What kind of behavior exactly are you trying to achieve?
In your paint method, make sure to call super.paint(g) since it is a method inherited from Container, a superclass of JApplet.
#Override
public void paint(Graphics g)
{
super.paint(g);
...
}

Categories

Resources