Why can I post text with JLabel but not with .drawString - java

Im not sure what I'm doing wrong as i've seen it done this way countless times before in various open source programs and games. below is my code that is giving me the error that g2 isn't a assigned variable? im confused..
package scratch;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class okay {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("helllo", JLabel.CENTER);
emptyLabel.setPreferredSize(new Dimension(250, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public void paint ( Graphics g ){
Graphics2D g2 = (Graphics2D) g;
g2.drawString("hello",0,0);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
paint(g2);
}
});
}
}

Your class extends no Swing component and so the paint method is not an override and does nothing. Instead you should have your class extend JPanel, put this JPanel into a JFrame, and override paintComponent. Also, 1) always give methods that you think are overriding super methods the #Override annotation. This way the compiler would have told you immediately that what you're doing is wrong. 2) Don't guess when it comes to learning new Java features -- look at and study the appropriate tutorial before trying this stuff. Here the painting in Swing tutorial would have answered these questions for you.
e.g.,
public class Foo extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("hello", 0, 20);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new Foo());
frame.pack();
frame.setVisible(true);
}
}

Related

paintComponent() in Java is not being called [duplicate]

This question already has answers here:
Swing - paintComponent method not being called
(2 answers)
Closed 5 years ago.
I am trying to draw a simple rectangle but I think the paintComponent method is not getting called.
Here is the code for the class with main method:
package painting;
import java.awt.*;
import javax.swing.*;
public class Painting {
public static void main(String[] args) {
JFrame jf;
jf = new JFrame("JUST DRAW A RECTANGLE");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.setLocationRelativeTo(null);
jf.setSize(600,600);
jf.setVisible(true);
Mainting maint = new Mainting();
jf.add(maint);
}
}
and the class with paintComponent()
package painting;
import java.awt.*;
import javax.swing.*;
public class Mainting extends JPanel {
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(0, 0 , 200, 200);
System.out.println("haha");
g.setColor(Color.red);
}
}
What is the problem here, I cannot figure out...
While the answers already provided might have resulted in the rectangle appearing, the approach was less than optimal. This example aims to show a better approach. Read the comments in the code for details.
Note that Swing/AWT GUIs should be started on the EDT. This is left as an exercise for the reader.
import java.awt.*;
import javax.swing.*;
public class Painting {
public static void main(String[] args) {
JFrame jf = new JFrame("JUST DRAW A RECTANGLE");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// null layouts cause more problems than they solve. DO NOT USE!
//jf.setLayout(null);
jf.setLocationRelativeTo(null);
/* if components return a sensible preferred size,
it's better to add them, then pack */
//jf.setSize(600, 600);
//jf.setVisible(true); // as mentioned, this should be last
Mainting maint = new Mainting();
jf.add(maint);
jf.pack(); // makes the GUI the size it NEEDS to be
jf.setVisible(true);
}
}
class Mainting extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(10, 10, 200, 200);
System.out.println("paintComponent called");
/* This does nothing useful, since nothing is painted
before the Graphics instance goes out of scope! */
//g.setColor(Color.red);
}
#Override
public Dimension getPreferredSize() {
// Provide hints to the layout manager!
return new Dimension(220, 220);
}
}
Try setting your layout manager to eg. BorderLayout
so use
jf.setLayout(new BorderLayout());
and then add your component with some constraints
Mainting maint = new Mainting();
jf.add(maint,BorderLayout.CENTER);

How to make a paint class that doesn't get called twice?

I wrote a paint class, and added the jpanel to the frame, but it's getting called twice for some reason, as I put a print statement inside the graphics method, and it printed it twice. The codes below are all the codes I have in my package.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Paint extends JPanel {
static Paint paint = new Paint();
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Hello");
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(paint);
frame.pack();
frame.setLocation(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I tried your code and paintComponent it's not called twice every time. I don't think you have the control on when the JFrame is calling pack() when you call setVisible. It may depends on how your OS manage the windows.

Can't print any string using drawString() in JFrame

I'm trying to find what is wrong with this short code. I can't print the String TEXT in my JFrame using drawString() method. Please Help . Only a plain white screen will appear if you run the program .
Code:
import javax.swing.*;
import java.awt.*;
public class sample extends JFrame
{
private JPanel panel;
public sample()
{
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
panel =new JPanel();
Container mainP= getContentPane();
mainP.add(panel);
panel.setBounds(0,0,500,500);
panel.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g)
{
Graphics2D eg = (Graphics2D)g;
eg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
eg.setColor(Color.BLACK);
eg.drawString("TEXT", 40, 120);
}
public static void main(String args[])
{
new sample();
}
}
JFrame has no paintComponent method. So you aren't override anything, and not painting will be done.
On that note JPanel does have a paintComponent method, and you should be painting on a JComponent or JPanel, which do have the method. You don't want to paint on top-level containers like JFrame. (if you really need to know though, the correct method to override is paint for JFrame).
That being said, you should also call super.paintComponent inside the paintComponent method so you don't break the paint chain and leave paint artifacts.
Side Notes
As good practice, make use of the #Override annotation, so you know you are correctly overriding a method. You would've seen that paintComponent doesn't override one of JFrames methods.
setVisible(true) after add your components.
panel.setBounds(0,0,500,500); will do absolutely nothing, since the JFrame has a default BorderLayout
Follow Java naming convention and use capital letters for class names.
Run Swing apps from the Event Dispatch Thread. See more at Initial Threads
FINAL
import javax.swing.*;
import java.awt.*;
public class Sample extends JFrame {
private JPanel panel;
public Sample() {
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D eg = (Graphics2D) g;
eg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
eg.setColor(Color.BLACK);
eg.drawString("TEXT", 40, 120);
}
};
Container mainP = getContentPane();
mainP.add(panel);
panel.setBackground(Color.WHITE);
setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Sample();
}
});
}
}

Can not draw oval on a JPanel

I have a JFrame created with GUI builder of Netbeans, which contains a JPanel only. I have created a method getPanel for getting a reference to this JPanel:
public class ShowDrawings extends JFrame {
public ShowDrawings() {
initComponents();
}
public JPanel getPanel(){
return panel;
}
private JPanel panel;
}
In my main function I am doing:
public class Main {
public static void main(String[] args){
ShowDrawings sd = new ShowDrawings();
sd.setSize(800, 600);
Graphics g = sd.getPanel().getGraphics();
g.setColor(Color.BLACK);
g.drawOval(400, 300, 50, 50);
sd.getPanel().paint(g);
sd.repaint();
sd.setVisible(true);
}
}
But it does not draw anything. Please help me.
I have looked some related questions but they are all suggesting extending JPanel and overriding its paint method. But I did not want to do that way.
Thanks.
I have looked some related questions but they are all suggesting
extending JPanel and overriding its paint method. But I did not want
to do that way
You should not override JPanel paint() method, rather paintComponent(..). This is best practice and should be done if you want code that will not produce anomalies. Also doing it in your current approach (as you have seen) makes creating persistent drawings a lot harder as they are wiped away on repaint()
Rather extend JPanel and override paintComponent(Graphics g) not forgetting to call super.paintComponent(g) as first call in overridden paintComponent(..) method. Also dont forget to override getPreferredSize() of JPanel so that we can return correct dimensions and pack() may be called on JFrame (+1 to #mKorbels comment):
Here is some example code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void initComponents() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel testPanel = new JPanel() {
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.GREEN);
//g2d.drawOval(10,10,100,100);//I like fill :P
g2d.fillOval(10,10,100,100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
};
frame.add(testPanel);
frame.pack();
frame.setVisible(true);
}
}
The first time you repaint() your ShowDrawings sd frame anything you've painted like this (sd.getPanel().getGraphics().drawOval(...)) would be erased by the original JPanel#paintComponent() method.
As Andrew Thompson has written:
Do not use Component.getGraphics(). Instead, subclass and override the paint() (AWT), or paintComponent() (Swing) method.
Component.getGraphics() simply can't work. Java uses a callback mechanism for drawing graphics. You are not supposed to "push" graphics information into a component using getGraphics(). Instead you are supposed to wait until Java calls your paint()/paintComponent() method. At that moment you are supposed to provide the Component with the drawings you would like to do.
If you're just checking/debugging something you could even do something like this:
class Test {
private JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawOval(400, 300, 50, 50);
}
};
}

Issue with this simple code

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyDrawPanel extends JPanel{
public void paintComponents(Graphics g){
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.getContentPane().add(paintComponents(g));
frame.setVisible(true);
}
}
I think I should add something arguments in frame.getContentPane().add(paintComponents(g));.
I looked up Graphics class but I'm still struggling with it. What should be the parameter of it?
try this
public class MyDrawPanel extends JPanel{
MyDrawPanel()
{
setOpaque(true);
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyDrawPanel());
frame.setBounds(10,10,500, 500);
frame.setVisible(true);
}
}
I'm no awt expert, but what I think you want to do is add a Canvas object to your content pane from the JFrame, then paint a Graphics object on it.
Okay, this is what I came up with:
public class MyDrawPanel extends JPanel
{
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
MyDrawPanel panel = new MyDrawPanel();
panel.setOpaque(true);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
createAndShowGUI();
}
});
}
}
Notes:
There are several problems with your line frame.getContentPane().add(paintComponents(g));. What you said is "add to the content pane the result of calling paintComponents on g. Where did g come from? You can not used a variable until declared. The result of calling paintComponents is void which means the result cannot be used as an argument to a method. Presumably you had compiler errors.
I changed paintComponents to paintComponent. The former is used to control painting of subcomponents and in general should not be overridden.
Swing objects should not be created on the main thread. The details are complicated for a beginner (and described here in detail). Mostly you can just memorize the SwingUtilities.invokeLater pattern used above.

Categories

Resources