Reputation: 3
I have the following code:
public static void main(String[] args){
Table testtable= new Table();
testtable.setVisible(true);
and:
public class ChessPanel extends JPanel {
@Override
public void paintComponent(Graphics g){
// intitlialize background-color
super.paintComponent(g);
int squareWidth = this.getWidth()/8;
int squareHeight = this.getHeight()/8;
this.setBackground(Color.WHITE);
for(int i = 0; i<8; i++) {
for(int j = 0; j<8; j++) {
if(((i+j)%2) == 1) {
g.setColor(new Color(128, 64, 0));
g.fillRect(squareWidth*i, squareHeight*j, squareWidth, squareHeight);
}
}
}
}
}
and:
public class Table extends javax.swing.JFrame {
/**
* Creates new form Table
*/
public Table() {
initComponents();
ChessPanel jpc = new ChessPanel();
getContentPane().add(jpc);
pack();
setVisible(true);
}
when I add the JPanel to the JFrame nothing happens. It is supposed to draw a chessboard. I simply missed something I guess, but I can't find the solution.
I have tried multiple ways of adding my JPanel to the frame, but nothing seems to draw the expected chessboard.
Thanks in advance,,
Upvotes: 0
Views: 242
Reputation: 199
If you want to add JPanel along with other components then
ChessPanel jpc = new ChessPanel();
getContentPane().add(jpc);
validate(); //Add this line
pack();
setVisible(true);
Or, if you want to set JPanel's content as a whole in JFrame's contentPane then
ChessPanel jpc = new ChessPanel();
this.setContentPane(jpc);
validate();
would do the job.
Upvotes: 1
Reputation: 47608
Looks ok to me. I only added an override of getPreferredSize:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChessPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
// intitlialize background-color
super.paintComponent(g);
int squareWidth = this.getWidth() / 8;
int squareHeight = this.getHeight() / 8;
this.setBackground(Color.WHITE);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if ((i + j) % 2 == 1) {
g.setColor(new Color(128, 64, 0));
g.fillRect(squareWidth * i, squareHeight * j, squareWidth, squareHeight);
}
}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChessPanel jpc = new ChessPanel();
frame.getContentPane().add(jpc);
frame.pack();
frame.setVisible(true);
}
});
}
}
Upvotes: 1