【发布时间】:2015-03-12 21:24:18
【问题描述】:
我有以下代码:
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 添加到框架中,但似乎没有绘制出预期的棋盘。
提前致谢,
【问题讨论】:
-
对我来说很好用(
paintComponent方法)。考虑提供一个runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将导致更少的混乱和更好的响应 -
无法重现。框架以零大小开始,但在调整大小后,棋盘显示正常。也许您只需要为您的自定义面板提供一个
getPreferredSize方法?
标签: java swing graphics jframe jpanel