Answer the question
In order to leave comments, you need to log in
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
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);
}
};
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 questionAsk a Question
731 491 924 answers to any question