Shapes not showing up - java

I'm trying to make some shapes filled with colors. The shapes doesn't show up!
Somebody Help Please!
I have two classes "menu.java" and "draw.java"
Here is my code for the "menu.java"
import javax.swing.JFrame;
public class menu {
public static void main(String[] args) {
JFrame JF = new JFrame("Menu Bar");
JF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
draw DR = new draw();
JF.add(DR);
JF.setSize(500,300);
JF.setVisible(true);
JF.setLocationRelativeTo(null);
}
}
The code for "draw.java"
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class draw extends JPanel{
public void painComponent(Graphics GPHCS){
super.paintComponent(GPHCS);
this.setBackground(Color.WHITE);
GPHCS.setColor(Color.BLUE);
GPHCS.fillRect(25,25,100,30);
GPHCS.setColor(Color.GRAY);
GPHCS.fillRect(25,65,100,30);
GPHCS.setColor(new Color(190,81,215));
GPHCS.drawString("This is my text", 25, 120);
}
}
Here is a screenshot after running the program
Why does the shapes not showing up?!
Any answers would be appreciated. Thanks

The method is called paintComponent, not painComponent. So the method paintComponent does not get overridden as intended.
Use #Override tag before method to get notified of errors like these.

Related

How is JFrame.setResizable supposed to be used?

I'm trying to followed java tutorials and now I am going over JFrame.
This is a information inquiry more than help question.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login {
public static void main(String[] args){
//Creating object of LoginFrame class and setting some of its properties
LoginFrame frame = new LoginFrame();
frame.setTitle("LoginForm");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This code will cause the frame to be resized to a very small size at the top left corner regardless of the bounds I set.
A simple fix for this is to place frame.setResizable() before setting its bounds.
Does anyone know why this happens or am I doing something wrong?
I'm also on Ubuntu 20.04, maybe this matters but I haven't found an answer.
Tutorial shows above code.
The following is the code for LoginFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//Creating LoginFrame class
public class LoginFrame extends JFrame implements ActionListener {
//Creating constructor of LoginFrame() class
LoginFrame(){
}
//Overriding actionPerformed() method
#Override
public void actionPerformed(ActionEvent e){
}
}
Like I was saying I was only following a tutorial. This was only the beginning of the tutorial but I had the same issue when starting another very simple frame tutorial.
The following works fine for me :
import javax.swing.*;
class Scratch extends JFrame {
public Scratch() {
super();
}
public static void main(String[] args){
//Creating object of LoginFrame class and setting some of its properties
Scratch frame = new Scratch();
frame.setTitle("LoginForm");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Result : I see a big rectangular window - in the shape of a smart phone screen I'd say.
setResizable(false) means you cannot resize the frame. I suspect the problem you're trying to identify lies somewhere in the LoginFrame class... no code for this was included though so hard to comment furhter.

JFrame not displaying all the content? Have to resize to show the content

I'm trying to build a simple GUI interface. I have added a background image to the JPanel using the paintComponent method.
The problem is when the output is built it shows only a small window as follows:
I have to resize the output window to show the full image. How can I make the image fit the window?
Here is my new source code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test extends JFrame {
public test(){
super("Staff Management");
this.setContentPane(new staff());
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.pack();
}
public class staff extends JPanel{
private ImageIcon i;
public staff() {
i = new ImageIcon("D:\\staff-directory.jpg");
}
#Override
public Dimension getPreferredSize() {
return new Dimension(i.getIconWidth(),i.getIconHeight());
}
public void paintComponent(Graphics g){
super.paintComponent(g);
i.paintIcon(this,g,0,0);
}
}
}
It is just that almost all the answers on this website says to use custom painting of JPanel so I spent a day learning how to do this..
These answers usually suggest you just draw the image using the Graphics.drawImage(...) method. Even the answers you got in your last question suggest this, so I have no idea why you would now try to paint an Icon. There is no reason to create an Icon to hold the image.
if you could show me how to do this with JLabel and Icon that would be a great help
There is no trick. It is just like using a JPanel:
JLabel label = new JLabel( ... );
label.setLayout( new FlowLayout() );
label.add( new JButton("one") );
label.add( new JButton("two") );
Read the Swing tutorial on How to Use Icons if you don't know how to add an Icon to a JLabel.
You even got this advice in your question here: https://stackoverflow.com/a/29091847/131872, so why are you asking this question again?
When you paint component you need to override getPreferedSize() method to define size of your custom component. You can change your class like next:
public class staff extends JPanel{
private ImageIcon i;
public staff() {
i = new ImageIcon("d:\\staff.jpg");
}
#Override
public Dimension getPreferredSize() {
return new Dimension(i.getIconWidth(),i.getIconHeight());
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
i.paintIcon(this, g, 0, 0);
}
}
Also use just pack() instead of this.setSize(894,553);.

Failing to draw Image to JFrame

first I want to apologize for any mistakes, I'm not speaking english well, I'm new to Java and I'm new to Stackoverflow. Please be kind!
I keep failing to draw a simple image to screen. I tried everything, but I keep failing and I'm getting more and more confused. Here's my Sourcecode:
package com.Animation;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Class1 extends JFrame{
private BufferedImage backgroundImg;
public Class1(){
this.setTitle("Animation");
this.setSize(1080, 720);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
LoadContent();
}
public static void main(String[] args){
new Class1();
}
private void LoadContent()
{
try
{
URL backgroundImgUrl = this.getClass().getResource("Back.jpg");
backgroundImg = ImageIO.read(backgroundImgUrl);
}
catch (IOException ex) {
System.err.println("Fehler!");
}
}
public void Draw(Graphics2D g2d)
{
g2d.drawImage(backgroundImg, 0, 0, null);
}
}
So what happens is, that a JFrame window opens with nothing to see on it. I think that's beacuse the Draw() method doesn't get called. But when I add like "Draw(g2d);" somewhere, I keep getting a NullPointerException. The picture "Back.jpg" is located in the same package as the class. I'm using eClipse and the JRE JavaSE 1.7.
I really hope you can help me, im totally exhausted by all my tries to figure out what's the problem. It would be cool if you could write the correct code into the answers and explain what I've done wrong. Remember, I'm new to all this.
Thanks a lot!
There are a lot of ways to do that. Examples
1) JLabel. //Not recommended
Add the JLabel in your JFrame, then do label.setIcon(backgroundImg);
2) JPanel
Override the paint() method in JPanel(make sure you've added it to your JFrame).
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backgroundImg, 0, 0, this);
}
Try this. Here I have set the image to a JPanel instead of directly setting it to JFrame.
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
*
* #author Rumesh
*/
public class Test extends JFrame{
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
final BufferedImage image = ImageIO.read(new File("1.jpg"));
JPanel pane = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
frame.add(pane);
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
I don't know if this is what you're searching for:
ImageIcon image = new ImageIcon("src/media/Image.jpg");
JLabel lblImg = new JLabel("", image, JLabel.CENTER);
lblImg.setBounds(..., ..., ..., ...);
add(lblImg);
This way you'll add an image to a JLabel and than place it on the screen. I hope it helps in some way.

paintComponent does painting on its own

My problem is, when I press a button paintComponent should be called then a figure should be drawn on the JPanel, Unfortunately paintComponent draws the figure when the program is loaded, in that case the button is useless.
I made a small version of my program, to make it easy and fast to read and detect the problem.
This code here is not the original one but it demonstrates the same problem.
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class TestPaint extends JPanel implements ActionListener {
private JButton button_1 = new JButton( "Draw Oval" );
public TestPaint() {
add(button_1);
}
#Override
public void actionPerformed(ActionEvent e) {
if ( e.getSource() == button_1 )
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(10, 10, 100, 100);
}
}
To run the program
import javax.swing.JFrame;
public class RunPaint {
public static void main(String[] args) {
TestPaint paint_g = new TestPaint();
JFrame frame = new JFrame("Testing");
frame.add(paint_g);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
As a simple solution you can create an instance variable for your class:
private Boolean buttonPressed = false;
Then in your actionListener you set the value to true.
and in your paintComponent() method you add code like:
if (buttonPressed)
g.drawOval(...);
A better (and more complicated solution) is to keep a List of objects to paint. Initially the List will be empty, and when you press the button you add an object to the List. Then the painting code just iterates through the List to paint the objects.
Check out Custom Painting Approaches for more ideas. The example code doesn't do exactly this, but it does show how to paint from a List.
Let your actionPerformed() implementation add the desired geometric figure to a List<Shape> and have paintComponent() iterate through the list to render the shapes. A complete example is seen here.

Using JFrame in java

Here is my code, I am wondering why it prints "test" two times!? every command I add in "paintcomponent" performs 2 times. I would appreciate if you could help me please!?
import java.awt.geom.*;// For Ellipse2D, etc.
import java.util.*;
import javax.swing.*; // For JPanel, etc.
import java.io.*;
import java.awt.*; // For Graphics, etc.
import java.lang.Object;
import java.util.Random;
public class hextopology extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("test");
}
public static void main(String[] args) throws Exception{
JFrame f = new JFrame();
f.add(new hextopology());
f.setSize(550,550);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When you are doing resizing the window you are actually changing the window's properties, so your view elements should be painted again. That's why paintComponent() is getting called every time and as you have a print statement inside the method, it is printing as expected.
You are calling
f.setSize(550,550);
which is a resize, after the panel is created for the first time.
paintComponent
is called twice, because of this.

Categories