centering a rectangle in JFrame - java

I am trying to create a rectangle in the center of a jframe. I tried with insets but i had not any luck. I have made the following class for the rectangle:
public class RectDraw extends JComponent{
Shape rect;
public void paint(Graphics g){
Graphics2D graph2 = (Graphics2D)g;
graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rect = new Rectangle2D.Float(50,50,15,15);
graph2.setPaint(Color.BLACK);
graph2.fill(rect);
graph2.draw(rect);
}
}
And the main:
public class TheMain{
public static void main(String[] args) {
Screen screen = new Screen();
RectDraw rect = new RectDraw();
screen.add(rect, BorderLayout.CENTER);
}
And this is the class screen:
public class Screen extends JFrame{
public Screen(){
this.setSize(500, 500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Testing");
this.getContentPane().setBackground(Color.GRAY);
this.setVisible(true);
}
}
So what i should change in order to put this rectangle in the center of the jframe?
Thanks!

You need to override your Screen's paintComponent method.
Such that your rectangle is width 50 height 100. Simply do some maths.
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D graph2 = (Graphics2D)g;
//To center the rectangle, we need to specify the center x,y points on the frame
//Divide width and height into two, and minus the width and height of the rectangle
graph2.drawRect(getWidth()/2 - 50/2, getHeight()/2 - 100/2, 50, 100);
}

Related

How come my image is not being drawn to the panel after I had made the image object using imageIcon().getImage()?

package notes.shape;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPanel extends JPanel implements ActionListener{
final int WIDTH=500;
final int HEIGHT=500;
Image bird;
Timer timer;
int x=0, y=0, xVel=7, yVel=5;
MyPanel(){
this.setPreferredSize(new Dimension(WIDTH, HEIGHT)); //makes panel 500x500
this.setBackground(Color.decode("#909599"));
bird=new ImageIcon("dvd.png").getImage(); //creates an image from dvd.png
System.out.println(bird.getHeight(null)); //tells the height and width of the image
System.out.println(bird.getWidth(null));
timer=new Timer(10, this); //initiates the timer
timer.start();
}
public void paint(Graphics g) {
super.paint(g); //makes the background a light gray
Graphics2D g2D=(Graphics2D) g; //cast g to Graphics2D
g2D.drawImage(bird, x, y, null); //draws the image on the panel
g2D.setColor(Color.decode("#ed1532")); //draws a red rectangle
g2D.fillRect(y, x, 50, 50);
}
#Override
public void actionPerformed(ActionEvent e) {
if(x>=WIDTH-bird.getWidth(null)||x<0) //switches the direction where the drawing is going on the x-axis
xVel*=-1;
x+=xVel;
if(y>=HEIGHT-bird.getHeight(null)||y<0) //switches the direction on the y-axis
yVel*=-1;
y+=yVel;
repaint(); //redraws at the new position
}
}
The purpose of this code is to draw a dvd image on a panel where it bounces off the walls; however, I having trouble drawing the image. I have a red square as a placeholder for right now, which is being drawn fine, but the problem with my image is that it is not being created in bird=new ImageIcon("dvd.png").getImage(); because it keeps showing the width and height as -1. Is there a reason why it's not being created such as using ImageIcon?

Remove or hide toolbar panel in Jpanel

When I work with Jpanel, I see that while Y is below 50 I don`t see objects, as they are hidden under top panel. I need a way to hide top panel or make it possible to not to add 50 to Y each time. In this example, top of the circle is hidden:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
class Draw extends JFrame{
public static int Framesize=1000;
public static void main(String []args){
Draw s=new Draw();
s.setVisible(true);
}
public Draw(){
JPanel panel=new JPanel();
setSize(Framesize,Framesize);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (int i=0;i<=1000;i+=50) {
g2.draw(new Line2D.Float(i, 0, i, Framesize));
g2.draw(new Line2D.Float(0, i, Framesize, i));
}
g2.setPaint(Color.RED);
g2.draw(new Ellipse2D.Float(0,0,200,200));
g2.drawString("Test", 100, 150);
}
}
First of all you have to use the JPanel variable you've created (because it's not a good practice to paint directly in the JFrame as you were doing just because It can cause the problem you were having). Here is an example of the panel class:
class panel extends JPanel{
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i <= 1000; i += 50) {
g2.draw(new Line2D.Float(i, 0, i, Draw.Framesize));
g2.draw(new Line2D.Float(0, i, Draw.Framesize, i));
}
g2.setPaint(Color.RED);
g2.draw(new Ellipse2D.Float(0, 0, 200, 200));
g2.drawString("Test", 100, 150);
}
}
Then add the panel class to the frame constructor
panel panel = new panel();
add(panel);
Finally remove the paint function from the main frame (because you have already defined it in the panel class).
However, there is no point in removing the upside bar (because, objects below 50 in Y axis will appear).
But if for some reason you still want to remove the upside bar then, in order to remove it you have to define in the constructor: setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
Finally remove the paint function from the main frame (because you have already defined it in the panel class).

How to create a Rectangle with the default x and y values at the top-left corner of the content pane, not the screen

I'm adding a function in my game that takes a screenshot and saves it to a new image. I have no problems with the filepath or anything of that sort, but rather the Rectangle through which the screenshot is taken. If I make a new Rectangle, like such:
new Rectangle(0, 0, 500, 500);
then it creates a 500 x 500 Rectangle at the top left of the computer screen, not at the top left of the content pane. The content pane to which I am referring is much smaller than the screen and located in the center. Thanks for reading, any help would be appreciated.
For any component (which can be a JPanel, Container, Window, or basically anything), you can use this to get the Rectangle that will represent its bounds on the screen:
Rectangle getBoundsOnScreen( Component component ) {
Point topLeft = component.getLocationOnScreen();
Dimension size = component.getSize();
return new Rectangle( topLeft, size );
}
So if you wanted just the content pane of a JFrame:
getBoundsOnScreen( frame.getContentPane() );
For stuff like an entire JFrame, you can just do this:
frame.getBounds();
Look at the example below. I first create a RectangleComponent class, which extends the Rectangle class:
import javax.swing.*;
import java.awt.*;
public class RectangleComponent extends JComponent
{
Rectangle rectangle;
public RectangleComponent(int xspace,int yspace, int width, int height)
{
rectangle = new Rectangle(xspace, yspace, width, height);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(rectangle);
}
}
Now we create a class that generates the main window, where you add the Rectangle component:
import javax.swing.*;
import java.awt.*;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
}
public static void main(String[] args) {
JFrame frame = new JFrame("Java Rulez");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100,100,600,600);
frame.getContentPane().setBackground(Color.YELLOW);
frame.add(new RectangleComponent(0, 0, 500, 500));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Java isn't displaying rectangle?

I'm trying it to display a rectangle at the specified location but it isn't showing up. The background is magenta but the rectangle is not there.
Also: How can I access more colors besides the "Color.(insert very few options here)"
import javax.swing.*;
import java.awt.*;
class Screensaver {
private final static int FRAME_HEIGHT = 600;
private final static int FRAME_WIDTH = 600;
public static void main(String[] args){
JFrame win;
Container contentPane;
Graphics g;
win = new JFrame();
win.setSize(FRAME_WIDTH, FRAME_HEIGHT);
win.setVisible(true);
contentPane = win.getContentPane();
contentPane.setBackground(Color.MAGENTA);
g = contentPane.getGraphics();
g.setColor(Color.BLACK);
g.fillRect(80, 350, 400, 250);
}
}
You shouldn't be painting in main(); it would be better to extend JPanel, change paintComponent(), and add the panel to the JFrame.
public class PaintPanel extends JPanel {
public PaintPanel() {
setBackground(Color.MAGENTA);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g); // This paints the background
g.setColor(Color.BLACK);
g.fillRect(80, 350, 400, 250);
}
}
And in main():
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new PaintPanel());
frame.setVisible(true);
}
If you want to make your own Colors, you can use the new Color(int red, int green, int blue) constructor.
If you're going to draw stuff create a class that inherits from a Swing container, JComponent, JPanel, etc. and override the paint(Graphics g) method. If you see the magenta background then contentPane must have been added. What's probably happening is its painting the magenta background over your rectangle, but that's just a guess. Try this...
public class ContentPane extends JComponent {
public ContentPane() {
}
#Override
public void paint(Graphics g) {
g.setColor(Color.MAGENTA);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.fillRect(80, 350, 400, 250);
}
}
Then in your main class instantiate an object of the ContentPane class and add it to your JFrame. The call to repaint() is probably unnecessary but that will make sure it gets painted. You can also try messing around with the paintComponent(Graphics g) method, there is a difference between the two, I believe its the order they're called from the update method but I'm probably wrong about that, however that should solve your problem.
As for colors, consult the API. You can pass RGB values into the Color constructor to create all sorts of colors. Color color = new Color(int red, int green, int blue). I think that is the easiest way to create custom colors but like I said its all in the API. Hope this helps.
Try this :
import javax.swing.*;
import java.awt.*;
class Screensaver {
private final static int FRAME_HEIGHT = 600;
private final static int FRAME_WIDTH = 600;
public static void main(String[] args) {
JFrame win;
Container contentPane;
win = new JFrame();
win.setSize(FRAME_WIDTH, FRAME_HEIGHT);
win.setVisible(true);
Component comp = new Component();
contentPane = (Container) win.getContentPane().add(comp);
}
}
class Component extends JComponent {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.magenta);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.fillRect(80, 350, 400, 250);
}
}
and about the color , you van create new Color and set the RED,GREEN,BLUE as you want , Try this :
g.setColor(new Color(red, green, blue));
The rectangle is drawn once, however every time the JFrames repaint() method is called it erases it and draws the basic Components. To add custom drawing in JFrames you have to override the paint method. Here I improved your code slightly to get you started down that path. As you can see you want to draw the box in the Paint method. I made a Container element that does your drawing and removed the background color, adding it to the paint method as well.
try this
import javax.swing.*;
import java.awt.*;
public class JavaApplication10 {
private final static int FRAME_HEIGHT = 600;
private final static int FRAME_WIDTH = 600;
public static void main(String[] args){
JFrame win = new JFrame();
win.setContentPane(new MyBoxContainer());
win.setSize(FRAME_WIDTH, FRAME_HEIGHT);
win.setVisible(true);
}
private static class MyBoxContainer extends Container {
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.MAGENTA);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.fillRect(80, 350, 400, 250);
}
}
}

Problems with setting JPanel's colour

Here's my canvas class extending JPanel:
package start;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Board extends JPanel
{
private static final long serialVersionUID = 1L;
public Board() {}
public void paintComponent(Graphics g)
{
int width = getWidth();
int height = getHeight();
this.setBackground(Color.green);
g.setColor(Color.black);
g.drawOval(0, 0, width, height);
}
}
Here's the method where I'm calling it:
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Hello");
frame.setPreferredSize(new Dimension(700, 700));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Board b = new Board();
frame.getContentPane().add(b);
frame.pack();
frame.setVisible(true);
}
But this shows the oval on the default colour. I also tried without the this., and then tried setting the colour of b, and setting the colour inside the constructor, but none of these worked. What's wrong?
EDIT: Sorry for not making thing clear, my goal was to display a thin black oval on a green background.
In the paintComponent method you do not have to use setBackground to change the colour of the JPanel. That should be done outside of paintComponent. paintComponent will probably use the colour of the background before you change it.
There are a number of things you can try. One, is to set the colour in the constructor and then call the super class' paintComponent first like this:
public Board() {
this.setBackground(Color.GREEN);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
g.setColor(Color.BLACK);
g.drawOval(0, 0, width, height);
}
Also note the color constants are all upper case. i.e. BLACK or GREEN.
If you want to change the background colour dynamically then you can do so in the event handler such as mouseEntered or actionPerformed etc.
While the code does not exactly make clear what's your intent i try to fix some issues:
If you want a green background, do as #vincent told you. YOu should see a black oval in green background. The "super.paintComponent" will fill its area with the components background automatically if the panel is opaque.
If you want a green oval on white background, maybe with black border
public void paintComponent(Graphics g)
{
int width = getWidth();
int height = getHeight();
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawOval(0, 0, width, height);
}
EDIT
i forgot super

Categories

Resources