簡體   English   中英

Java GUI似乎是空白的(swing + awt)

[英]Java GUI appears to be blank (swing + awt)

我無法讓我的GUI包含任何JButtons或JTextField。 我有兩個類一個“SnowballFight”類,它包含我的main方法和框架構造函數。 然后我也有“GameBoard”來設置我的GUI。 我的問題是我的GUI出現了,但顯示為空。

“SnowballFight”課程:

package snowballfight;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SnowballFight extends JFrame implements ActionListener{
    public SnowballFight(){
        setLayout(new BorderLayout(1,2));
    }
    public static void main(String[] args) {
        SnowballFight frame = new SnowballFight();
        GameBoard game = new GameBoard(frame);
    }
    public void actionPerformed(ActionEvent event) {
    }
}

“GameBoard”課程:

package snowballfight;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GameBoard extends JFrame implements ActionListener{
    private JButton[][] game = new JButton[10][10];
    private JTextField display = new JTextField("Welcome to the SnowBall fight!");
    private Opponent[] opponents = new Opponent[4];
    public GameBoard(SnowballFight frame){
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout( 10, 10));
        for (int row = 0; row < game.length; row++) {
            for (int col = 0; col < game[row].length; col++) {
                game[row][col] = new JButton();
                game[row][col].setBackground(Color.gray);
                game[row][col].addActionListener(this);
                panel.add(game[row][col]);
            }
        }
        add(display, BorderLayout.NORTH);
        add(panel, BorderLayout.SOUTH);
        frame.setTitle("Snowball Fight");
        frame.setSize(200, 150);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    public boolean isGameOver(){
        for (int opponent = 0; opponent < opponents.length; opponent++) {
            if(opponents[opponent].isSoaked() == false ){
                return false;
            }
        }
        return true;
    }
    public void actionPerformed(ActionEvent event) {
    }
}

你永遠不會讓GameBoard JFrame可見

game.setVisible(true);

一些說明:

不知道為什么有兩個幀,但我認為你將displaypanel添加到錯誤的幀。

嘗試改變:

    add(display, BorderLayout.NORTH);
    add(panel, BorderLayout.SOUTH);

至:

    frame.add(display, BorderLayout.NORTH);
    frame.add(panel, BorderLayout.SOUTH);

暫無
暫無

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

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