Wednesday 27 December 2017

java - JPanel not showing up on JFrame

style="font-weight: bold;">

Answer



style="font-weight: bold;">

Answer





I'm trying to draw some filled
rectangles on a JPanel and add that panel to a JFrame but when I run the program all I
see is the JFrame. I added the JPanel using frame.add(new
RectanglePanel());
so I'm not sure why the panel is not showing
up.



Frame
class:



package
h02;

import javax.swing.*;


// frame
and its properties

public class RectangleFrame extends JFrame
{

public RectangleFrame() {

// JFrame
object

JFrame frame = new
JFrame();


// properties


frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // frame in
centre
frame.setTitle("Drawing rectangles");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new
RectanglePanel());

frame.setVisible(true);

}



public
static void main(String[] args) {
new RectangleFrame();


}

}



Panel
class:



package
h02;

import javax.swing.*;
import
java.awt.*;

public class RectanglePanel extends JPanel
{

// drawing the rectangles


public
void PaintComponent(Graphics g) {

super.paintComponent(g);

g.fillRect(110, 110, 20, 20);

g.fillRect(10, 10, 30, 120);
g.fillRect(60, 10, 60, 100);

g.fillRect(150, 10, 10, 20);
g.fillRect(240, 10, 10, 20);

g.fillRect(190, 30, 80, 30);

g.fillRect(210, 50, 60,
20);
g.fillRect(190, 70, 80, 50);
g.fillRect(300, 30, 50,
90);
g.fillRect(330, 10, 30, 20);

}

}


Answer




public void
PaintComponent(Graphics g)
{



should
be



@Override
protected
void paintComponent(Graphics g) {


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...