can't draw oval in java - java

I can't draw a oval, I can't understand where I'm wrong. I have already done research but I have not found answers, sorry for the trouble.
This is my simple code:
public class Ball extends JPanel{
public void paint(Graphics g) {
g.drawOval(100, 100, 50, 50);
}
public static void main(String[] args) {
JFrame game = new JFrame("Ball game!");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setResizable(false);
game.setLayout(null);
game.setSize(300, 550);
game.setLocation(400, 200);
Ball d = new Ball();
game.add(d);
game.setVisible(true);
}
}

The inner content of a JFrame is its contentpane. You can just set the frame's contentpane to the panel that you want to draw, with JFrame.setContentPane(). Then your panel will be shown.
public class Ball extends JPanel{
public void paint(Graphics g) {
g.drawOval(100, 100, 50, 50);
}
public static void main(String[] args) {
JFrame game = new JFrame("Ball game!");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setResizable(false);
game.setLayout(null);
game.setSize(300, 550);
game.setLocation(400, 200);
Ball d = new Ball();
game.setContentPane(d); // <- this line
game.setVisible(true);
}
}

The size of the added panel is (0, 0) since you are not using a Layout Manager (game.setLayout(null)) neither setting its size.
In that case you must set the position and size of any added Component:
Ball d = new Ball();
d.setLocation(0,0);
d.setSize(300, 500);
or just use a Layout Manager, e.g. the default one - BorderLayout for JFrame - and the added panel will occupy the whole area:
game.setResizable(false);
// game.setLayout(null);
game.setSize(300, 550);

Related

JFrame graphics ignores the first few renders

Here is a minimal code to see the bug:
import javax.swing.*;
import java.awt.*;
public class Main1 extends JFrame {
static Main1 main;
public Main1() {
super("app");
}
public static void main(String[] args) {
main = new Main1();
main.setBounds(300, 300, 800, 500);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Graphics g = main.getGraphics();
for(int i = 0; i < 100; i++){
g.setColor(new Color(255, 0, 0));
g.fillRect(0, 0, 800, 500);
}
}
}
If i use 100 in the "for" cycle, the frame appears not to be colored, but 200 loops is enough to color it.
I want to make an application where frames change rarely, but this feature ruins the quality of code because I have to make a number of dummy frames.
public static void main(String[] args) {
main = new Main1();
main.setBounds(300, 300, 800, 500);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Graphics g = main.getGraphics();
for(int i = 0; i < 100; i++){
g.setColor(new Color(255, 0, 0));
g.fillRect(0, 0, 800, 500);
}
}
This is not how you do Swing graphics. Getting a Graphics object by calling .getGraphics() on a component gives you a short-lived unstable and sometimes null object. For instance, it takes some time for the created JFrame to render, and if you call getGraphics() and try to use it prior to rendering, the object may be null, and certainly won't wokr.
Instead paint within a JPanel's paintComponent method using the Graphics object given by the JVM as per the tutorials:
public class MainPanel extends JPanel {
public MainPanel {
setPreferredSize(new Dimension(800, 500)));
setBackground(new Color(255, 0, 0)); // if you just want to set background
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// use g here do do your drawing
}
}
and then use it like so:
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
Tutorial: Lesson: Performing Custom Painting
And yes, if you want to drive a simple animation, use a Swing Timer to help drive it like so:
public class MainPanel extends JPanel {
private int x = 0;
private int y = 0;
public MainPanel {
setPreferredSize(new Dimension(800, 500)));
setBackground(new Color(255, 0, 0)); // if you just want to set background
// timer code:
int timerDelay = 15;
new Timer(timerDelay, ()-> {
x += 4;
y += 4;
repaint();
}).start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// use g here do do your drawing
g.setColor(Color.BLUE);
g.drawRect(x, y, 20, 20);
}
}

Change rectangle color in Java GUI

How to change the color of rectangle ? I want change it to yellow color. I added g.setColor(Color.YELLOW); inside rectDraw, but the color of the rectangle still remain the same. Can someone tell me what wrong I did please?
public class SelectSeat {
static JFrame frame;
public JPanel createContentPane() throws IOException
{
JPanel totalGUI = new JPanel();
RectDraw rect= new RectDraw();
rect.setPreferredSize(new Dimension(330,35)); //for size
totalGUI.setLayout(null);
totalGUI.setBackground(Color.WHITE);
totalGUI.add(rect);
Dimension d = rect.getPreferredSize();
rect.setBounds(100, 20, d.width, d.height); // for location
return totalGUI;
}
void setVisible(boolean b) {
// TODO Auto-generated method stub
}
static void createAndShowGUI() throws IOException
{
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Seat Selection");
//Create and set up the content pane.
SelectSeat demo = new SelectSeat();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(535, 520);
frame.setLocation(500,220);
frame.setVisible(true);
}
private static class RectDraw extends JPanel
{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawString("Movie Sceen", 130, 20);
}
}
}
How to change the color of rectangle ? I want change it to yellow color.
You need to set the color to yellow, followed by filling a rectangle the size of the component.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(0,0,getWidth(), getHeight());
g.setColor(Color.BLUE);
g.drawString("Movie Sceen", 130, 20);
}
And for what its worth:
totalGUI.setLayout(null);
I would recommend against using null Layouts. Use a LayoutManager appropriate to the task, and remember that you can nest layouts within the Component hierarchy.

Add drawing in layered plane java

i am new to swing in java. i am trying to add the drawing made by the paintComponent() method in my a frame through layeredPane but it is not showing in the JFrame
However if i place the code frame.getContentPane().add(drawing) and comment the Layered part the code works..
what i am doing wrong?
here is the code:
frame class
public class FrameTest extends JFrame {
static JFrame frame= new JFrame("Frame");
public static void main(String[] args) {
FrameTest test= new FrameTest ();
}
public FrameTest (){
this.openfrane();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void openframe(){
//window properties
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1000,600);
frame.setResizable(false);
//changing icon of window
ImageIcon image = new ImageIcon("assets/icon.png");
card.setIconImage(image.getImage());
//label picture background
JLabel background = new JLabel();
ImageIcon back = new ImageIcon("assets/background.jpg");
background.setIcon(back);
background.setLocation(0,-125);
background.setSize(1000,700);
//label for first
JLabel first = new JLabel("Sample text");
first.setForeground(Color.RED);
first.setSize(500,200);
first.setLocation(31, 150);
Draw drawing = new Draw();
JLayeredPane layers = new JLayeredPane();
layers.add(drawing, new Integer(3));
layers.add(first, new Integer(2));
layers.add(background,new Integer(1));
frame.setLayeredPane(layers);
}
}
draw class:
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
int startX = 00;
int startY = 00;
// First circle
Ellipse2D circle1 = new Ellipse2D.Double(startX, startY, 30, 30);
g2.setColor(Color.Black);
g2.draw(circle1);
g2.fill(circle1);
// Second circle
Ellipse2D circle2 = new Ellipse2D.Double(startX+20, startY, 30, 30);
g2.setColor(Color.Black);
g2.draw(circle2);
g2.fill(circle2);
}
}
i am trying to add the drawing made by the paintComponent() method in my a frame through layeredPane but it is not showing in the JFrame
Your DrawPanel does not have a size, so the size is (0, 0) and there is nothing to paint.
However if i place the code frame.getContentPane().add(drawing) and comment the Layered part the code works..
When you add the DrawPanel directly to the content pane then the panel is added to the "CENTER" and the panel size is automatically set to the space available in the frame by the layout manager.

JPanel won't move if it fills the screen

First of all, sorry for the vague title I don't know how to word the question in a sentence.
I have a simple programme that slides one JPanel into view as another gets pushed out, when a button is clicked.
If the first JPanel's width is set as getWidth() then the JPanel will not move when the button is clicked, however if I change the width to getWidth() - 1 it works perfectly fine!?!
A simple example is shown below
public class SlidingJPanel extends JFrame{
public JPanel panel = new JPanel();
public JPanel panel2 = new JPanel();
public JLabel label = new JLabel(" SUCCESS!!!!!!!");
public JButton button = new JButton("TESTING");
public class MyJPanel extends JPanel implements ActionListener{
public int x = 0;
public int delay = 70;
final Timer timer = new Timer(delay,this);
public MyJPanel(){};
public void paintComponent(Graphics g)
{
super.paintComponent(g);
button.setBounds(10, 20, 100, 50);
button.addActionListener(this);
panel.setBorder(BorderFactory.createLineBorder(Color.black));
panel.setBounds(x, 0, getWidth(), getHeight());
panel.add(button);
panel2.setBorder(BorderFactory.createLineBorder(Color.blue));
panel2.setBounds(x - getWidth(), 0, getWidth(), getHeight());
panel2.add(label);
add(panel);
add(panel2);
}
#Override
public void actionPerformed(ActionEvent arg0) {
timer.addActionListener(move);
timer.start();
}
ActionListener move = new ActionListener(){
public void actionPerformed(ActionEvent e){
repaint();
x++;
}
};
}
public static void main(String args [])
{
new SlidingJPanel();
}
SlidingJPanel()
{
Container container = getContentPane();
MyJPanel panel = new MyJPanel();
container.add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500,500);
setTitle("JPanel Draw Rect Animation");
setVisible(true);
}
}
ignore any coding conventions I may have ignored or missed this is just a rough draft.
Hope someone can help :)
The paintComponent() method is for painting only! There is no need for you to override this method.
You should NOT be:
updating the property of components (ie. bounds, border)
adding components to a container
If you want to animate a component then when the timer fires you can use setLocation(...) or setSize() or setBounds(). The component will automatically be repainted.
I don't know if fixing this will solve your problem, but the current approach is wrong.

Adding a JPanel to a JLayeredPane causes paints and resizes to have no effect

I am trying to add a JPanel (well, several) to a JLayeredPane. However, when I do so, the paint component method of the JPanel seems to have no effect. An example is included below:
import javax.swing.*;
import java.awt.*;
public class Example {
public static void main(String[] args) {
// This Works as expected
JFrame usingPanel = new JFrame();
JPanel p = new JPanel();
p.add(new BluePanel());
usingPanel.setContentPane(p);
usingPanel.pack();
usingPanel.setVisible(true);
// This makes the frame but does not paint the BluePanel
JFrame usingLayer = new JFrame();
JLayeredPane l = new JLayeredPane();
l.setPreferredSize(new Dimension(200,200));
l.add(new BluePanel(), JLayeredPane.DEFAULT_LAYER);
JPanel p2 = new JPanel();
p2.add(l);
usingLayer.setContentPane(p2);
usingLayer.pack();
usingLayer.setVisible(true);
}
static class BluePanel extends JPanel{
public BluePanel(){
setPreferredSize(new Dimension(200,200));
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 200, 200);
}
}
}
Why is this? and what are the possible solutions?
JLayeredPane does not have a LayoutManager, so you need to set the location and size of your panels yourself.
See the tutorial
you hardcoded the size on the screen and have to change from
g.fillRect(0, 0, 200, 200);
to
g.fillRect(0, 0, getWidth(), getHeight());
(a minor change) add the method
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
and then remove of code line setPreferredSize(new Dimension(200,200));

Categories

Resources