Using awt.Graphics in a method - java

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.

Related

Drawing with functions on JFrame or JPanel java

I wanted to know if it is possible to use/make a function in another Class to draw an image/oval and then call it in the paint public void in our main Class.
If I have
public class Trydraw{
public void drawrcircle(Graphics g){
g.setColor(Color.RED);
g.drawOval(0, 0, 20,20);
g.fillOval(0,0,20,20);
}
}
And then call it here this way
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.*;
public class Display extends JPanel{
public static void main(String[]haha){
JFrame frame = new JFrame();
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
Trydraw l = new Trydraw();
l.drawrcircle(g);
}
}
Thanks for your future help.
Yes you can, if I get your question correctly.
Your sample code works for me if I add
frame.add(new Display());
to the end of your
public static void main(String[] haha)
method.
With your snippet the paint(g) method will never be called, because it will be executed with the initialization of the JPanel which will be initialized with the initialization the Display class (because of inheritance).
You probably want to create an instance of Display, which automatically initializes the JPanel with the overridden paint(g) method, thus the new Operator.
As the constructor of a JPanel returns a JPanel, the constructor of Display returns a type of JPanel as well, which contains the red circle. This JPanel needs to be added with the add method to your original JFrame.

Proper way for Repainting JComponent

So, I've taken an AP class on java, and in the class, we never really went over repaint(), and how to properly use it. I've also searched through the internet, and I personally have not found any answers on the standard way of calling repaint(). Are we supposed to call the repaint() method from the main class like the following?
import java.awt.*;
import javax.swing.*;
public class RepaintExample{
public static void main(String[] args){
JFrame frame = new JFrame();
JComponent component = new JComponent();
frame.add(component);
frame.repaint();
}
}
Or would I call the JComponent.repaint() Like this
import java.awt.*;
import javax.swing.*;
public class RepaintExample{
public static void main(String[] args){
JFrame frame = new JFrame();
JComponent component = new JComponent();
frame.add(component);
component.repaint();
}
}
Or, are both approaches wrong, and JComponent.repaint() should be called from the paintComponent as shown here:
import java.awt.*;
import javax.swing.*;
public class ComponentRepaintExample extends JComponent{
public void paintComponent(Graphics g){
//Draw stuff
for(int i = 0; i < 10; i++){
//Draw stuff
this.repaint();
}
}
}
It is quite possible that all three approaches are wrong. Any help figuring out how to properly use the repaint() method is appreciated. The whole topic is very shrouded to me, so I apologize if any terminology I use is incorrect. All thanks in advance.
Why do you think you need to call repaint()?
The repaint() method is invoked by a Swing component automatically when a property of the component is changed.
For example if you have a JLabel and you invoke setText(...) or setIcon(...), then those methods will automatically invoke repaint().
You would NEVER invoke repaint() from a painting method.
If you are doing custom painting, then your code should be structured like any other Swing component. That is you create getter/setter methods for your custom components to change properties of the component. In the setter method you invoke repaint().

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.

Making a drawing application using swing and mouse listener

i have an assignment to make a simple drawing application using swing and mouse listener. the application has to have three classes, one that contains Main, one that contains the frame, and the last one that makes the drawing. The teacher gave us a source code we're supposed to use to complete the assignment and it looks like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Drawsome extends JFrame implements MouseMotionListener {
public Drawsome(){
setSize(300,400);
setForeground(Color.black);
show();;
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent evt) {
start = end;
end = new Point(evt.getX(),evt.getY());
repaint();
}
public void mouseMoved(MouseEvent evt) {
end = null;
}
public void paint(Graphics g) {
if (start!=null && end!=null)
g.drawLine(start.x, start.y, end.x, end.y);
}
public void update(Graphics g) {
paint(g);
}
Point start=null;
Point end=null;
}
now this work perfectly, but since we have to make the frame in another class i tried to do this:
import java.awt.Color;
import javax.swing.JFrame;
public class MainWindow extends JFrame {
public MainWindow() {
setSize(300,400);
setForeground(Color.black);
show();;
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Drawsome extends JFrame implements MouseMotionListener {
public Drawsome(){
MainWindow mainwindow = new MainWindow();
addMouseMotionListener(this);
} (rest is the same as the previous code)
i'll get a frame, but the rest doesn't work, i dont' understand what i'm doing wrong, and would greatly appreciate a push in the right direction
Your teacher's source code is terrible since you should never be drawing within the paint method or within a JFrame, plus his/her paint override doesn't call the super's method, breaking the painting chain. They don't appear to know what they're doing.
Having said that, your main driver should not extend JFrame nor should you try to create a JFrame of it or even an instance of it. Instead, in this class's main method, create an instance of the terrible drawing class.
Note that I don't understand this requirement:
and the last one that makes the drawing.
Please post the exact requirements.
If this were my application, I'd
Do my drawing within a JPanel, and not a JFrame
Do it within the JPanel's paintComponent method, not the paint method.
Be sure to call the super's paintComponent method within my JPanel's paintComponent method override.
Then place my JPanel within a JFrame to display it.
I would not have my GUI class implement the MouseListener but rather would use a nested inner class for this.

Disable painting on a JPanel

I'm trying to completely disable all painting and refreshing on a portion of a JFrame. I got the desired effect on the entire JFrame by simply overriding public void paint(Graphics) like so:
import javax.swing.*;
class Test extends JFrame {
Test () {
setBounds(20,20, 100,100);
setVisible(true);
}
//This disables all painting and refreshing ON A JFRAME.
//Just doing this on a JPanel doesn't work.
public void paint (Graphics g) {}
public static void main (String[] args)
{ new Test(); }
}
I want this same effect, but only on a particular region of the JFrame. I want to be able to add GUI components like normal to the rest of the frame. I've tried disabling double buffering (using JPanel's constructor) and overriding the following methods (extending both JPanel and JComponent) like so:
public class DontRefresh extends JComponent/JPanel {
public void paint (Graphics g) {}
public void paintComponent (Graphics g) {}
public void repaint () {}
public void update (Graphics g) {}
public void updateUI () {}
}
and i also tried disabling refresh via:
DontRefresh component = new DontRefresh();
RepaintManager.currentManager(component).markCompletelyClean(component);
but nothing worked.
Well, without knowing exactly what you're doing I would recommend you have a "filler panel" (just a JPanel you don't do anything with) in the space you don't want anything to appear and then have other panels for everything else.
So say you have a JFrame. If you wanted the top right corner to never display anything, you could fill the JFrame with 4 JPanels, one in each corner (or 3 with one on the left, one in the top right corner and one in the bottom right corner). Then put all you swing components in the other panels. I don't know if this will accomplish your purpose, but I'm not totally certain what you're purpose is, so that's the best I can do :) I hope it helps!

Categories

Resources