B
B
Borislav Yanchenko2018-11-13 17:53:52
Java
Borislav Yanchenko, 2018-11-13 17:53:52

What is the reason for the program not working?

After calling the constructor, a black window is displayed. What am I doing wrong?

package Logic;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Frame {
  
  JPanel p;
  
  public Frame(String title) {
    p = new JPanel();
    p.setPreferredSize(new Dimension(854, 480));
    p.setBackground(new Color(0));
    
    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(false);
    f.setContentPane(p);
    f.pack();
    f.setLocationRelativeTo(null);
    
    p.setFocusable(true);
    p.requestFocus();
    
    f.setVisible(true);
    
    //p.setBackground(new Color(255, 0, 0)); << ЭТА СТРОКА НОРМАЛЬНО РАБОТАЕТ
    
    Graphics g = p.getGraphics();
    g.setColor(new Color(255, 255, 255));
    g.fillRect(0, 0, 1000, 1000);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-11-13
@FireName

The window and all components on it are constantly redrawn by the graphics subsystem. Therefore, you need to draw on the component in the redraw method:

p = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, 1000, 1000);  
    }    
};

A
Artem Kiryanov, 2018-11-13
@hacker342

p.setBackground(new Color(0));
//p.setBackground(new Color(255, 0, 0)); << THIS LINE WORKS NORMALLY is
commented out
so the black window

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question