簡體   English   中英

從下一個類向JFrame添加組件

[英]Adding components to JFrame from next class

我有一個問題。 我有上課

public static void main(String[] args) {
    HomePanel game = new HomePanel();
    game.setVisible(true);
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

帶有游戲的主面板:

  public HomePanel() {

    setSize(1280, 720);
    setLayout(null);
    setTitle("MILLION");

    bNewGame = new JButton("New Game");
    bNewGame.setFont(new Font("Tahoma", Font.BOLD, 15));
    bNewGame.setBounds(550, 420, 180, 50);
    bNewGame.setToolTipText("Start a new adventure!");
    bNewGame.addActionListener(this);

使用動作偵聽器:

  public void actionPerformed(ActionEvent action) {
    source = action.getSource();

    if (source == bNewGame) {
        new Test().setVisible(true);

還有很多其他 當我啟動此窗口時,單擊“新游戲”后,我想打開組件-我的意思是添加按鈕和Test類的動作偵聽器,但我想在同一窗口中執行此操作,而無需打開新窗口(它實際上發生了)。

public class Test extends JFrame{
private JButton bCredits;

public Test() {
    setSize(1280, 720);
    setLayout(null);
    setTitle("TEST_TEST");

    bCredits = new JButton("Credits");
    bCredits.setBounds(550, 540, 180, 50);
    add(bCredits);
}

誰能幫我?

我的建議是使用一個名為GameFrameJFrame或類似的東西。 然后在HomePanel中添加gameFrame 確保homePanel擴展了JPanel或某些容器。 如果需要,只需從框架中刪除homePanel並添加另一個視圖。 就像是

remove(homePanel);
add(nextView);

還請確保nextView擴展了JPanel或某些容器。 使用布局管理器更好地定位

暫無
暫無

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

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