簡體   English   中英

添加到JFrame的JPanel沒有任何作用

[英]JPanel added to JFrame does nothing

我有以下代碼:

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添加到框架的方法,但是似乎沒有畫出預期的棋盤。

提前致謝,,

對我來說還不錯。 我只添加了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);
            }
        });
    }
}

如果要與其他組件一起添加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();

會做的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM