drawString not drawing text on window - java

I'm trying to make a test window with some text on it, when I run my code, it doesn't draw the string. I specified the color for it. Can anybody help me with this?
import javax.swing.*;
import java.awt.*;
class Main
{
public static void main(String[] args) {
DrawFrame f = new DrawFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
class DrawFrame extends JFrame
{
public DrawFrame(){
setTitle("For Aylin");
setSize(1280,720);
DrawPanel panel = new DrawPanel();
Container cp = getContentPane();
cp.add(panel);
}
}
class DrawPanel extends JPanel
{
public void paintComponents(Graphics g)
{
super.paintComponents(g);
g.setColor(Color.darkGray);
g.drawString("Hi", 100, 10);
}
}

You should override the JPanel's paintComponent method not its paintComponents method as they are for two very different purposes. The first paints the component itself (what you want) while the second gets the child components held by this parent to paint themselves.
Also remember to change the super call so that it matches, and to use the #Override annotation above the method.

Related

How to draw shape inside of JPanel that is inside JFrame

I have issue with drawing shapes inside of JPanel that I already added using Netbeans GUI. Now, I have no idea where to add code for drawing a circle inside of that JPanel and how to insert and call it in the JPanel that is sitting empty now, waiting for this shape to be drawn. I already set up destination JPanel to be Flow layout.
Netbeans Designer created a big class in which I have entire frame with this JPanel, and I want to keep it inside of it as I can't really add it any other way because Designer doesn't let me change main initComponents method in which all components are sitting now. I have been reading tutorials and previous posts but noone really encountered this using Netbeans Designer.
SO can someone just help me with adding proper method in this frame class and how to call it from JPanel I want to draw in. JPanel is 50x50 pixels.
So as per #Abra, I changed some code:
so I made a new Circle Class, adjusted it a bit as I don't want to create a new frame but put this in JPanel.
public class Circle extends JPanel {
Color color;
public void circle(Color color) {
this.color = color;
setPreferredSize(new Dimension (30,30));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, 0, r, r);
g.setColor(color);
}
private void showGUI() {
JPanel panel = new JPanel();
panel.add(this, FlowLayout.CENTER);
panel.setVisible(true);
}
}
Then I opened JPanel in Designer, and added code to run it, in initComponents method like this:
circlePanel.setPreferredSize(new java.awt.Dimension(40, 40));
new Circle().showGUI();
PanelDS.add(circlePanel);
circlePanel is destination for this drawing and is inside PanelDS itself. It doesn't work this way tho, but Netbeans shows no errors in code. Additionally, how can I forward color to circle class.
In order to draw on a JPanel you need to override the paintComponent() method of JPanel. In order to override the method, you need to create a class that extends JPanel. I don't think that there exists a GUI designer that can generate the required code for you. So you have to write the code of the class that extends JPanel.
Here is a minimal example. It displays a blue circle.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Drawing2 extends JPanel {
private JFrame frame;
public Drawing2() {
setPreferredSize(new Dimension(100, 100));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(25, 25, 50, 50);
}
private void showGui() {
frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
new Drawing2().showGui();
}
}
Here's what you should see when you run the above code.

PaintComponent don't seem to get call or to show

My problem is really simple : I have this little program, and it just don't show the red box I'm trying to make :
Main
public class Main {
public static void main(String[] args) {
Affichage a = new Affichage();
a.setVisible(true);
}
}
Affichage :
import java.awt.*;
import javax.swing.*;
public class Affichage extends Frame{
public Affichage(){
setTitle("Exo 1 : Galerie");
setSize(1120,560);
Graphique graph = new Graphique();
this.add(graph);
}
}
Graphique :
import javax.swing.*;
import java.awt.*;
public class Graphique extends JComponent {
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
Graphics pinceau = g.create();
pinceau.setColor(Color.RED);
pinceau.fillRect(100, 100, 200, 200);
System.out.println("test");
}
}
I bet it's ridicule but I can't find what it is, help me.
PS : yes the test don't get print too
Actually, don't extend JFrame as it is bad practice. Just make an instance of it. To paint, extend JPanel and override paintComponent.
JFrame f = new JFrame();
f.add(new MyPanel());
class MyPanel extends JPanel {
// other stuff
public void paintComponent(Graphics g) {
super.paintComponent(g);
// painting stuff.
}
}
And remember not to mix Swing and AWT components.
You are adding a Swing component (javax.swing.JComponent) to an AWT frame (java.awt.Frame). Noone will call the paintComponents() method, that's why you don't get any output or result. Extend from javax.swing.JFrame instead, so you have a Swing frame with a Swing component.

How to Draw some shape on JPanel using ActionListener?

I'm practising to draw a shape on a JPanel by clicking on a Jbutton, but I cannot. It's been five hours that I'm surfing the web, but I cannot find the way to do it.
This is what I want to do: if I click on "Rectangle" button a rectangle appears under the buttons and if I click on "Circle" button a circle appears.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Shape extends JFrame {
JButton rec, circle;
static String botSelected;
Shape (){
frameSet ();
}
void frameSet(){
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600,300);
rec = new JButton ("Rectangle");
circle = new JButton("Circle");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(rec);
panel.add(circle);
Click clk = new Click();
rec.addActionListener(clk);
circle.addActionListener(clk);
}
public void paint (Graphics g){
super.paint(g);
if (botSelected.equals("Rectangle"))
g.fillRect(50,50,50,50);
else if (botSelected.equals("Circle"))
g.fillOval(50,50,50,50);
}
public static void main (String [] arg){
Shape s = new Shape();
}
}
class Click implements ActionListener{
public void actionPerformed (ActionEvent e){
Shape.botSelected = e.getActionCommand();
}
}
The first thing I would do is have a read through Painting in Swing and Performing custom painting to better understand how the painting process works.
Next you need to understand that JFrame is a bad choice for painting to. Why? Because it's multilayered.
A JFrame contains a JRootPane, which contains a JLayeredPane the contentPane, glassPane and the JMenuBar and in your example, it also contains a JPanel.
With the (default) exception of the glassPane, all these components are opaque.
While it's possible to have something drawn in the paint method show it, if any of the other components paint themselves, it will be wiped clean - this is because Swing components can actually be painted independently of each other, with having to have the parent paint itself first.
A better solution is to start by extending from JPanel and override its paintComponent method.
For simplicity, I'd also encourage you to implement the ActionListener against this class as well, it will allow the actionPerformed method to access the properties of the component and, in your case, call repaint to trigger a paint cycle when you want to update the UI.
Here is a derived example from your code.
As #MadProgrammer said, don't extend JFrame.
In the following example, here are the major changes :
give a non-null value to botSelected, or the first calls to paintComponent will give you a NullPointerException
the class now extends JPanel, and overrides paintComponent for custom painting
the ActionListener is an anonymous class, because you don't need a separate class, and it has direct access to the fields from Shape
botSelected is no longer static (see above point)
.
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Shape extends JPanel {
JButton rec, circle;
String botSelected = "";// don't let it be null, it would make paintComponent crash on startup
Shape() {
frameSet();
}
void frameSet() {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 300);
rec = new JButton("Rectangle");
circle = new JButton("Circle");
frame.add(this);
this.add(rec);
this.add(circle);
// anonymous class, has access to fields from the outer class Shape
ActionListener clk = new ActionListener() {
public void actionPerformed(final ActionEvent e) {
botSelected = e.getActionCommand();
repaint();
}
};
rec.addActionListener(clk);
circle.addActionListener(clk);
}
//custom painting of the JPanel
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
if (botSelected.equals("Rectangle")) {
g.fillRect(50, 50, 50, 50);
} else if (botSelected.equals("Circle")) {
g.fillOval(50, 50, 50, 50);
}
}
public static void main(final String[] arg) {
Shape s = new Shape();
}
}

why wont my background change color?

I was working on this lab in class and when I tried changing the background color it would stay at its default of white can someone please explain where I my programming went wrong.
import javax.swing.*;
import java.awt.*;
public class DemoPoly extends JFrame {
// constructor
public DemoPoly() {
// defines Frame characteristics
int size = 300;
setSize(size,size);
setTitle("a random window");
getContentPane().setBackground(Color.red);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main (String[] args){
// instantiates a JFrame
// exits on close (opional)
JFrame object = new DemoPoly();
}
public void paint (Graphics g){
// This provides the Graphics object g, where
// you are going to use you graphics primitive
// to paint on the content pane of the frame.
int[] arr = {0,100,100,0};
int[] yarr = {0,0,100,100};
Square object = new Square(arr,yarr,Color.red);
AbstractPolygon randSquare = new Square(arr, yarr, Color.red);
}
I see a couple of problems in your code:
Extending JFrame is like saying your class is a JFrame, JFrame is a rigid container, instead create your GUI based on JPanels. See Java Swing extends JFrame vs calling it inside of class for more information.
You're breaking the paint chain by removing the super.paint(g) call on the paint(...) method. When changing your GUI to extend JPanel instead of JFrame you should use the paintComponent(...) method instead. Take the Lesson: Performing Custom Painting in Swing.
You forgot to add #Override notation on the paint(...) method.
You're not placing your program on the Event Dispatch Thread (EDT) which could cause threading issues.
You can solve this by changing your main() method like this:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Your constructor here
}
});
}
Instead of setting the JFrame size, override the getPreferredSize() method and call pack(). See Should I setPreferred|Maximum|MiniumSize in Java Swing?. The general consensus says yes.
Your problem gets solved by adding
super.paint(g);
on the paint(...) method:
#Override
public void paint(Graphics g) {
super.paint(g); //Never remove this
//Your code goes here
}
With all the above recommendations taken into account, your code should look like this now:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class DemoPoly {
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DemoPoly().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
CustomPanel cp = new CustomPanel();
cp.setBackground(Color.RED);
frame.add(cp);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class CustomPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
Which produces this output (and is the same output that you'll get with your current code but better because it gives you more control over your components)
I'm don't understand your question. But here is code for change your background to RED;
public class DemoPoly extends JFrame {
public DemoPoly() {
// defines Frame characteristics
int size = 300;
setSize(size, size);
setTitle("a random window");
//change background here
getContentPane().setBackground(Color.red);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
// instantiates a JFrame
// exits on close (opional)
JFrame object = new DemoPoly();
}
}
Your code is well. Maybe use #override in your paint method.

Making an image show up in Java

I've been struggling to get an image to show up for some time now. Ive read a few different things, and all of them seem to have different ways of showing images. Can someone tell me what I'm doing wrong? I'm trying to make a program that uses 2 classes to make a picture show up in a frame. I guess what I don't understand still is what a Graphics object is, what a Graphics2D object is and how its different, and what method from what class do I call in order to make an image show up. Here is my code:
public class Smiley {
private BufferedImage smileyFace;
private Graphics2D renderWindow;
private Dimension smileyPosition;
private File smileyFile;
public Smiley() {
try{
smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
MainScreen.graphicPane.drawImage(smileyFace,50,50, null);
}
and the second class:
public class MainScreen extends JFrame{
public static MainScreen ms;
public static Graphics2D graphicPane;
public static void main (String[] args){
MainScreen ms = new MainScreen();
Smiley newSmiley = new Smiley();
}
public MainScreen(){
super("Main Screen Window");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(500,800);
this.getContentPane().setBackground(Color.black);
graphicPane = (Graphics2D) this.getContentPane().getGraphics();
}
}
the program compiles with no errors and nothing is reported back to me about not finding the file.
Your going to need some sore of paint method. For that you will require a Component to paint on. You need to learn a GUI framework, like Swing. There are clear compoents you can paint on like a JPanel. With that panel you need to override its paintComponent method.
The Graphcics object is what the component uses to actually paint the graphic onto the component.
The Graphics2D object just extends the capabilities of the Graphics object.
You should take a look at the Swing tuorial and the **Graphics toturial
To get your program running though you would do something like this
public class DrawPanel extends JPanel {
BufferedImage smileyFace;
public DrawPanel() {
try{
smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
}
catch (Exception e){
System.out.println("There was an error finding or reading the file \" smiley.png.\"");
}
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(smileyFace,50,50, this);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(500, 500);
}
}
Then you can instantiate that panel in another class, adding it to a JFrame to run it
public class Main {
public static void main(String[] args) {
SwingUtiliites.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
You are calling this in your constructor for your Smiley class.
MainScreen.graphicPane.drawImage(smileyFace,50,50, null);
If you are going to paint the image yourself you need to override paintComponent() in a component that gets added to your main screen.
Or just add the image to a JLabel that you added to the main screen.
You draw image in wrong way.
For using drawImage() you need to use that in paintComponent() method of JComponent(for example JPanel), examine next code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.beans.Transient;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame {
public Example() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Smiley());
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new Example();
}
class Smiley extends JPanel{
private BufferedImage smileyFace;
Smiley(){
try {
File smileyFile = new File("C:\\Users\\MyName\\Desktop\\smiley.png");
smileyFace = ImageIO.read(smileyFile);
} catch (Exception e) {
System.out
.println("There was an error finding or reading the file \" smiley.png.\"");
}
}
#Override
#Transient
public Dimension getPreferredSize() {
return new Dimension(smileyFace.getWidth(),smileyFace.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(smileyFace, 0,0, this);
}
}
}
or you can add your image to JLabel and that do all for you, change Smile class like next:
class Smiley extends JPanel{
Smiley(){
ImageIcon icon = new ImageIcon("C:\\Users\\MyName\\Desktop\\smiley.png");
JLabel l = new JLabel(icon);
add(l);
}
}
ALso read more about customPaintings.

Categories