Reputation: 1005
I'm new to the Java swing library and I'm currently having some trouble setting the background of my JFrame.
I have read jframe-setbackground-not-working-why and the link inside it, but it doesn't seem to fit here.
Here is my codes:
public class Board extends JPanel{
public enum pointType{
EMPTY,
CARRIER,
BALL;
}
private class Point{
int x;
int y;
pointType type;
public void paint (Graphics2D g2){
// color changes depends on pointType
g2.setColor(Color.WHITE);
g2.fillOval(x,y,25,25);
}
}
Point[][] myBoard;
public Board(){
//constructor, myBoard = 2d List of points
}
//.. other methods and class variables
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
for(int k =HEIGHT; k>=0; k--){
for(int i=WIDTH; i>=0; i--){
// call paint method for each points on board
myBoard[i][k].print(g2);
}
}
}
public static void main(String[] args){
Board board = new Board();
JFrame myFrame = new Jframe("Game");
myFrame.add(board);
board.setBackground(Color.YELLOW);
myFrame.setVisible(true);
mtFrane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
My code successfully prints all the points according to their pointType, but the board color is not set correctly (still default background).
So here are the questions:
1) How should I set the background correctly?
2) I feel that my code is not using JPanels/JFrames/Graphics together correctly, if that's the case, any suggestions on how I improve my code structures?
Upvotes: 1
Views: 428
Reputation: 8422
The default paintComponent()
method in JPanel
uses the background color stored in the JPanel
's instance variable; however, your overridden paintComponent()
method doesn't make use of the instance variable and so changing it with setBackground()
won't do anything.
If you want to stick with overriding the paintComponent()
method, you should draw a box filling the entire area of the JPanel
with the color which you want inside the paintComponent()
method.
The new paintComponent()
method for Board
would look like this:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.YELLOW);
g2.fillRect(0, 0, getWidth(), getHeight()); // Fill in background
// Do everything else
for(int k =HEIGHT; k>=0; k--){
for(int i=WIDTH; i>=0; i--){
// call paint method for each points on board
myBoard[i][k].print(g2);
}
}
}
Upvotes: 1
Reputation: 46861
Use paintComponent()
instead of paint()
public class Board extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
...
}
}
For more info have a look at below posts:
Upvotes: 2