我有以下代码:
public static void main(String[] args){
Table testtable= new Table();
testtable.setVisible(true);
和
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);
}
}
}
}
}
和
public class Table extends javax.swing.JFrame {
/**
* Creates new form Table
*/
public Table() {
initComponents();
ChessPanel jpc = new ChessPanel();
getContentPane().add(jpc);
pack();
setVisible(true);
}
当我将JPanel添加到JFrame时没有任何反应。它应该画一个棋盘。我只想错过一些东西,但我找不到解决办法。
我尝试了多种方法将我的JPanel添加到框架中,但似乎没有任何方法可以绘制预期的棋盘。
提前致谢,
答案 0 :(得分:1)
对我来说没问题。我只添加了一个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);
}
});
}
}
答案 1 :(得分:1)
如果您想将JPanel与其他组件一起添加
ChessPanel jpc = new ChessPanel();
getContentPane().add(jpc);
validate(); //Add this line
pack();
setVisible(true);
或者,如果你想在JFrame的contentPane中整体设置JPanel的内容,那么
ChessPanel jpc = new ChessPanel();
this.setContentPane(jpc);
validate();
可以胜任。