Cannot get this blasted rectangle to draw!! (java swing) - java

Class one:
public class Bar extends JComponent {
// instance variables - replace the example below with your own
private static boolean litUp = false;
private static boolean vertical = true;
private static int positionX;
private static int positionY;
private static int sizeX;
private static int sizeY;
private static Color color;
public void paintComponent(Graphics g) {
System.out.println("I am being called");
positionX = 50;
positionY = 30;
vertical = true;
if(vertical == true) {
sizeX = 10;
sizeY = 30;
if(litUp == true)
{
color = Color.red;
}
else
{
color = Color.black;
}
} else{
sizeX = 30;
sizeY = 10;
if(litUp == true)
{
color = Color.red;
}
else
{
color = Color.black;
}
}
g.fillRect(positionX, positionY, sizeX, sizeY);
g.setColor(color);
super.paintComponent(g);
}
}
Class Two:
public class TestingBar {
public static void main(String[] args) {
final int FRAME_WIDTH = 317;
final int FRAME_HEIGHT = 415;
//created frame and panel. Panel layout is taken away from the flow layout.
final JFrame myFrame = new JFrame();
myFrame.setTitle("Tester Window (v2)");
myFrame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
final JPanel myPanel = new JPanel();
myPanel.setLayout(null);
final Bar testBar = new Bar();
//myPanel.add(testBar);
myFrame.getContentPane().add(testBar);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myPanel.add(testBar);
}
}
This is just giving me an empty JFrame. And the print statement is never being utilized in the paintComponent method. I am seriously stumped.
PS: They won't let me post this without typing more, so I will talk about turtles. I don't understand how they survive out in the wild. They can't run, their shells really aren't that hard, they can only attack from the front, and if they are flipped over they are crippled for an indefinite amount of time. You think that natural selection would have worn them out of the pool by now.
Maybe they survived by being so darn adorable. I mean, just watch youtube videos of a baby turtle trying to eat a cherry tomato. It is the epitome of cute.

I think you should call super.paintComponent(g); at the beggining of the function. It probably paints over your rectangle.

You are adding testBar to your frame then again to your myPanel which removes it from the frame (a component can only have one parent). But since myPanel is not added to anything, it never gets called.
Commenting out this line will fix it, but you probably are intending to do something meaningful with your myPanel, so check your design.
//myPanel.add(testBar);

I turned your Bar class into a JPanel and ovrrode the paint method instead and it worked but the other comments are correct, you're not adding the panel to the frame, just the bar object:
//created frame and panel. Panel layout is taken away from the flow layout.
final JFrame myFrame = new JFrame();
myFrame.setTitle("Tester Window (v2)");
myFrame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
final Bar testBar = new Bar();
myFrame.getContentPane().add(testBar);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
and in bar:
public class Bar extends JPanel
{
//....
public void paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(20,20,20,20);
}
}

Call super.paintComponents first thing. You probably want to cast g to a Graphics2D object, too.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Wrong order -- set the color, then draw the rectangle (using g2):
g2.setColor(color);
g2.fillRect(positionX, positionY, sizeX, sizeY);

Related

JFrame not displaying anything

I cannot seem to get a rectangle to be displayed in the JFrame. Per the parameters of this project, I have to have this class implement the Icon interface. When I run the code as is, I get the JFrame, but nothing shows up inside. It should display a black square. I'm assuming the problem has something to do with how I am initializing the graphics instance variable. I don't have much experience working with GUI graphics, so I'm not entirely clear on how to do this correctly.
And yes, I do know that the getIconWidth and getIconHeight methods are redundant since I am using constants, but I have to have these methods in order to implement the interface.
public class MugDisplay extends JFrame implements Icon {
private int width;
private int height;
private JPanel panel;
private Graphics graphics;
private static final int ICON_WIDTH = 100;
private static final int ICON_HEIGHT = 100;
public MugDisplay() {
this.configureGui();
this.panel = new JPanel();
this.panel.setLayout(new BorderLayout());
this.add(this.panel, BorderLayout.CENTER);
this.graphics = this.getGraphics();
int xPos = (this.panel.getWidth() - this.getIconWidth()) / 2;
int yPos = (this.panel.getHeight() - this.getIconHeight()) / 2;
this.paintIcon(this.panel, this.graphics, xPos, yPos);
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
}
#Override
public int getIconWidth() {
return ICON_WIDTH;
}
#Override
public int getIconHeight() {
return ICON_HEIGHT;
}
private void configureGui() {
this.setPreferredSize(new Dimension(600, 600));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());
this.pack();
this.setVisible(true);
}
}
In the interest of having a MCVE, here is the driver class that calls this class.
public class Main {
public static void main(String[] args) {
MugDisplay md = new MugDisplay();
md.setVisible(true);
}
}
this.graphics = this.getGraphics() is not how custom painting works in Swing. What you should do is create a panel, override its paintComponent method, make the call to super, and then do your painting. For instance:
panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int xPos = ...
paintIcon(this, g, xPos, yPos);
}
}
Calling getGraphics will provide you with a short-lived Graphics object that can soon become invalid, which is why you should opt for overriding paintComponent instead, which will always give you a usable Graphics object. See Performing Custom Painting.
On a separate note, it looks like you're calling setVisible(true) before you're finished adding the necessary components to the JFrame. To ensure that your components show up, call setVisible(true) after adding them all to the frame.

Java - Learning inheritance, using Graphics2D, object is redrawn when resizing the frame

I am working on a lab to practice inheritance, in which we are to create a horizontal ellipse as "Shape1" and then create a "Shape2" which extends Shape1 which draws it's superclass Shape1, and then draws a vertical ellipse over top to create a new looking shape. The shape is displaying fine in terms of inheritance and looks (color/location etc) however when running the program, the frame width is set to 1000, and the height is set to 700, but If I drag the frame by the corner to enlarge it, the shape is drawn over and over again as I keep dragging the frame larger. Ideally the shape should just stay where it is relative to the frame size. I think this is happening because while I drag the frame larger, the draw method is being called over and over again by the system, but I am not sure where this is happening or how to fix it. Any suggestions?
All classes are displayed below:
Shape1:
public class Shape1 {
private double x, y, r;
protected Color col;
private Random randGen = new Random();
public Shape1(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
this.col = new Color(randGen.nextFloat(), randGen.nextFloat(), randGen.nextFloat());
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getR() {
return this.r;
}
public void draw(Graphics2D g2){
//Create a horizontal ellipse
Ellipse2D horizontalEllipse = new Ellipse2D.Double(x - 2*r, y - r, 4 * r, 2 * r);
g2.setPaint(col);
g2.fill(horizontalEllipse);
}
}
Shape2:
public class Shape2 extends Shape1 {
public Shape2(double x, double y, double r) {
super(x, y, r);
}
public void draw(Graphics2D g2) {
//Create a horizontal ellipse
Ellipse2D verticalEllipse = new Ellipse2D.Double(super.getX() - super.getR(),
super.getY() - 2*super.getR(),
2 * super.getR(), 4 * super.getR());
super.draw(g2);
g2.fill(verticalEllipse);
}
}
ShapeComponent:
public class ShapeComponent extends JComponent {
//Instance variables here
private Random coordGen = new Random();
private final int FRAME_WIDTH = 1000;
private final int FRAME_HEIGHT = 700;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Shape2 myShape = new Shape2(1 + coordGen.nextInt(FRAME_WIDTH), 1 + coordGen.nextInt(FRAME_HEIGHT), 20);
//Draw shape here
myShape.draw(g2);
}
}
ShapeViewer(Where the JFrame is created):
public class ShapeViewer {
public static void main(String[] args) {
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 700;
//A new frame
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Lab 5");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ShapeComponent component = new ShapeComponent();
frame.add(component);
//We can see it!
frame.setVisible(true);
}
}
because while I drag the frame larger, the draw method is being called over and over again by the system,
Correct, all components are repainted when the frame is resized.
Any suggestions?
Painting code should be based on properties of your class. If you want the painting to be a fixed size then you define the properties that control the painting and set these properties outside the painting method.
For example, you would never invoke Random.nextInt(...) in the painting method. This means the value will change every time the component is repainted.
So the Shape should be created in the constructor of your class and its size would be defined there, not each time you paint it.

How to get JPanel to fill parent JFrame

I am trying to draw a circle in the center of a window, and I can't seem to get it right, should be really easy! My understanding is that if you set a JPanel as the content pane of a JFrame, the default layout is a flowLayout and that drawing should start from the top left of the screen as 0,0. To try and figure out what's going on I drew a blue background filling the JPanel, but it seems to have a margin like so:
When the window gets smaller than the blue rectangle, the drawing starts to get clipped from the opposite side:
What's going on! Here is my code:
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public static void main(String args[])
{
Test test = new Test();
test.Start();
}
public void Start()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
CirclePanel circlePanel = new CirclePanel();
this.setContentPane(circlePanel);
this.setVisible(true);
}
public class CirclePanel extends JPanel
{
private int radius = 200;
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.red);
int diameter = radius * 2;
g.fillOval(getX(), getY(), diameter, diameter);
}
public int getX()
{
return (this.getWidth()/2) - radius;
}
public int getY()
{
return (this.getHeight()/2) - radius;
}
}
}
One big issue, you're unknowingly overriding two critical methods used by the layout managers to position components, the getX() and getY() methods, and thereby you're messing with the JPanel's placement.
So first and foremost, rename these methods so you don't accidentally move the JPanel.
Also, don't forget to call the super's paintComponent method, and avoid calling setSize(). Instead override getPreferredSize on your JPanel, and pack your JFrame.
e.g.,
public int getMyX() {
return myX;
}
public int getMyY() {
return myY;
}
For example
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public static void main(String args[]) {
//!!
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Test test = new Test();
test.Start();
}
});
}
public void Start() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// this.setSize(500, 500);
CirclePanel circlePanel = new CirclePanel();
setContentPane(circlePanel);
pack();
setVisible(true);
}
public class CirclePanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private int radius = 200;
public void paintComponent(Graphics g) {
super.paintComponent(g); //!!
g.setColor(Color.blue);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.red);
int diameter = radius * 2;
g.fillOval(getMyX(), getMyY(), diameter, diameter);
}
//!!
public int getMyX() {
return (this.getWidth() / 2) - radius;
}
//!!
public int getMyY() {
return (this.getHeight() / 2) - radius;
}
//!!
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
}
The problem is that you're overriding getX() and getY(). Rename those to something else, and your code will work as expected. Also, it's a good idea to turn on compiler warnings for missing #Override annotations, and heed those warnings. (That would have notified the methods override superclass methods).
Try using this.add(circlePanel) instead if this.setContentPane(circlePanel) and set the size of the JPanel to be the same size as the JFrame

Adding multiple graphic objects to one JFrame

Here is my code it is a guy and a background but only one thing shows up at a time or sometimes nothing at all.
I have a brain class, a frame class, a redPlayer class, and a background class.
The way it works is the brain makes a player and a brain and adds it to the frame.
I think it has something to do with layouts but I tried everything but nothing works.
Please Help!!!
Thanks in advance.
here is the brain:
public class Brain
{
private Frame frame;
private static RedPlayer redPlayer;
private Background background;
private SensorKeys sensor;
public Brain()
{
frame = new Frame();
redPlayer = new RedPlayer();
background = new Background();
sensor = new SensorKeys();
frame.addComponent(redPlayer);
frame.addComponent(background);
frame.addKeySensor(sensor);
redPlayer.revalidate();
}
public static void setRedPlayerVelX(double vx)
{
redPlayer.setVelX(vx);
}
public static void setRedPlayerVelY(double vy)
{
redPlayer.setVelY(vy);
}
public static void makeRedPlayerBullet()
{
}
}
`
here is the frame class
public class Frame
{
private JFrame jf;
public Frame()
{
drawFrame();
}
public void drawFrame()
{
jf = new JFrame();
jf.setSize(800, 600);
jf.setLocation(10, 10);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setBackground(Color.WHITE);
jf.setLayout(null);
}
public void addComponent(JComponent jc)
{
jc.setBounds(jc.getX(), jc.getY(), 100, 100);
jf.add(jc);
}
public void addPanel(JPanel jp)
{
jf.add(jp);
}
public void addKeySensor(KeyListener kl)
{
jf.addKeyListener(kl);
}
}
here is the player class:
public class RedPlayer extends JComponent implements ActionListener
{
private int x,y;
private double velX = 0, velY = 0;
private Timer timer = new Timer(2,this);
private Image redplayer;
public RedPlayer()
{
x = 100;
y = 100;
ImageIcon II = new ImageIcon("redPlayerRight.png");
redplayer = II.getImage();
revalidate();
timer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
graphics.drawImage(redplayer, x,y, null);
}
public void actionPerformed(ActionEvent arg0)
{
x += velX;
y += velY;
repaint();
revalidate();
}
public void setVelX(double vx)
{
velX = vx;
}
public void setVelY(double vy)
{
velY = vy;
}
}
And Lastly here is the background class:
public class Background extends JComponent
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
graphics.setColor(Color.green);
graphics.fillRect(0, 400, 500, 200);
}
}
I think it has something to do with layouts
Yes, you should read the Swing tutorial on Using Layout Managers to better understand how they work and for examples.
The default layout manager for a JFrame is a BorderLayout. You can't just add 3 components to the same area of the BorderLayout.
I don't know what you are trying to accomplish but start simple. Since you have a background the basic code should be something like:
redPlayer = new RedPlayer();
background = new Background();
background.add( redPlayer );
frame.addComponent(background);
So the red player should display on top of the background. And the background is added to the frame.
Of course you must use a proper layout manager for the background. And you must make sure you override the getPreferredSize() method when you do custom painting so the layout manager knows what the size of every component should be.
Get those two components working first, then move on to the 3rd component.

Best to handle 2 overlaying live updated panels?

In very basic terms I have a panel that is drawing a line pixel by pixel and is being updated in real time. On top of this I want another panel that draws a box around the current pixel but clears itself later. Both are in real time
My current situation is a wrapper JPanel that has an OverlayLayout. The bottom panel has the line that is drawn with the Graphics2D object fetched from its JPanel. The top panel the box that follows around that is also drawn with the Graphics2D object fetched from its JPanel.
The issues in this system are many. Since I'm just drawing on the Graphics2D object separately and not overriding the JPanel's paint() not only is all the lines lost when the panel needs to repaint, I think I'm going against Swing's threading model by only having a single thread update the screen. I have also not gotten the top panel to work correctly, it just keeps clearing the screen and won't let the bottom panel draw a line.
What would be the best way to approach this situation? I have little experience with image processing and the low-level displaying of images in Swing, I just know the basics. I've heard of BufferedImage, but not knowing where to put that image, if it will be updated when changed later, the efficiency of doing that, and the fact that its buffered scare me off. I'm not sure what to use
Can someone point me in the right direction of what I need to use to accomplish this?
You can accumulate your points in a suitable Shape, such as GeneralPath, as shown in LissajousPanel. Use a javax.swing.Timer to cause periodic updates, and highlight the most recently added point with a surrounding rectangle.
I suggest
that you do not get your JPanel's Graphics or Graphics2D object via getGraphics as this object is not meant to be stable and will not work once the component has been repainted for any reason.
that you instead do all your drawing in a single JPanel's paintComponent method, but first in that method call the super's method.
that you again draw in only one JPanel, not two,
that you draw your line in a BufferedImage, since that is a more permanent part of your image.
That you get the BufferedImage's Graphics2D object via its createGraphics method
That you properly dispose of the BufferedImage's Graphics object when done using it so as to conserve resources.
that you display your BufferedImage in the paintComponent method of your JPanel (after calling the super method first)
that you draw your box, the more fleeting portion of the image, directly in the paintComponent using int class variables to tell paintComponent where to draw and perhaps a class boolean variable to tell if to draw.
and that most important, you review the tutorials on Swing graphics as to do this properly, you'll have to throw all old assumptions out and learn the correct way from the ground up (as we all had to do).
For example:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class BufferedImageEg extends JPanel {
private static final int BI_WIDTH = 700;
private static final int BI_HEIGHT = 500;
private static final Color BACKGROUND = new Color(255, 255, 240);
private static final int THIS_PT_WIDTH = 12;
private static final int THIS_PT_HEIGHT = THIS_PT_WIDTH;
private static final float THIS_PT_STROKE_WIDTH = 2f;
private static final Color THIS_PT_BORDER_COLOR = Color.red;
private static final Color THIS_PT_FILL_COLOR = new Color(250, 250, 0, 125);
private static final int TIMER_DELAY = 30;
private static final int X_MIN = 0;
private static final int X_MAX = 100;
private static final double X_STEP = 0.1;
private static final double X_SCALE = (double) BI_WIDTH
/ ((double) X_MAX - X_MIN);
private static final double Y_SCALE = 8;
private static final float LINE_WIDTH = 4;
private static final Color LINE_COLOR = Color.blue;
private Point lastPoint = null;
private Point thisPoint = null;
private BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT,
BufferedImage.TYPE_INT_RGB);
private double xValue = X_MIN;
public BufferedImageEg() {
Graphics biG = bImage.getGraphics();
biG.setColor(BACKGROUND);
biG.fillRect(0, 0, BI_WIDTH, BI_HEIGHT);
setBackground(BACKGROUND);
new Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
timerActionPerformed(e);
}
}).start();
}
private void timerActionPerformed(ActionEvent e) {
if (xValue <= X_MAX) {
lastPoint = thisPoint;
double tempX = xValue;
double yValue = function(xValue);
tempX *= X_SCALE;
yValue *= Y_SCALE;
yValue = BI_HEIGHT / 2.0 - yValue;
thisPoint = new Point((int) tempX, (int) yValue);
if (lastPoint != null) {
drawInBufferedImage();
}
xValue += X_STEP;
} else {
((Timer) e.getSource()).stop();
thisPoint = null;
}
repaint();
}
private void drawInBufferedImage() {
Graphics2D g2 = bImage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(LINE_WIDTH, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
g2.setColor(LINE_COLOR);
int x1 = lastPoint.x;
int y1 = lastPoint.y;
int x2 = thisPoint.x;
int y2 = thisPoint.y;
g2.drawLine(x1, y1, x2, y2);
g2.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(BI_WIDTH, BI_HEIGHT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bImage, 0, 0, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (thisPoint != null) {
drawThisPoint(g2);
}
}
private void drawThisPoint(Graphics2D g2) {
int x = thisPoint.x - THIS_PT_WIDTH / 2;
int y = thisPoint.y - THIS_PT_HEIGHT / 2;
Graphics2D g2b = (Graphics2D) g2.create();
g2b.setStroke(new BasicStroke(THIS_PT_STROKE_WIDTH));
g2b.setColor(THIS_PT_FILL_COLOR);
g2b.fillOval(x, y, THIS_PT_WIDTH, THIS_PT_HEIGHT);
g2b.setColor(THIS_PT_BORDER_COLOR);
g2b.drawOval(x, y, THIS_PT_WIDTH, THIS_PT_HEIGHT);
g2b.dispose();
}
private double function(double x) {
return 24 * Math.sin(x / 12.0) * Math.sin(x);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("BufferedImage Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BufferedImageEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories

Resources