2014-01-09 156 views
1

所以我剛剛找到了在線教程中引用的Netbeans JFrame表單來幫助佈局(我的教科書在GUI部分中沒有提及它,至少我見過!)因爲我有困難(我無法讓文本區域自身行爲並留在窗口的中心而不是佔據整個窗口!)我認爲視覺輔助可能會有所幫助,然而,正如你可能已經猜到,我已經有大量的代碼沉入這個程序。是否有可能將新的JFrame表單與現有類連接起來?如果是這樣,我該如何去做呢?如果您需要它,我可以提供我的代碼,但我們只是在三個主要類中的一箇中講500行代碼。是否可以將jframe表單添加到現有類中?

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package theproblem; 

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.TextArea; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 

/** 
* 
* @author Heather 
*/ 
public class TheProblem { 

/** 
* @param args the command line arguments 
*/ 

public static void main(String[] args) { 

    JFrame window2 = new JFrame(); 
    TextArea battleLogging = new TextArea(3,10); 
    JScrollPane logScrollPane = new JScrollPane(battleLogging); 
    JLabel BattleLog = new JLabel(); 
    JLabel p1HPLabel= new JLabel(); 
    JLabel p2HPLabel= new JLabel(); 
    String attack1ButtonContents = "Just an attack"; 
    String attack2ButtonContents = "Just another attack"; 
    JButton attack1=new JButton(attack1ButtonContents); 
    JButton attack2=new JButton(attack2ButtonContents); 


    window2.setLayout(new BorderLayout()); 
    window2.setSize(400,400); 
    JPanel attackPanel = new JPanel(); 
    attackPanel.add(attack1); 
    attackPanel.add(attack2); 
//  attack1 = new JButton(p1A1); 
//  attack2 = new JButton(p1A2); 
//  attack1.addActionListener(new Attack1()); 
//  attack2.addActionListener(new Attack2()); 
    //window2.add(attackPanel, BorderLayout.CENTER); 
    window2.add(battleLogging, BorderLayout.CENTER); 
    battleLogging.setEditable(false); 
    logScrollPane.setVerticalScrollBarPolicy(
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
    logScrollPane.setPreferredSize(new Dimension(50, 50)); 
    //battleLogging.setLineWrap(true); 
    //battleLogging.setWrapStyleWord(true); 
    window2.add(BattleLog, BorderLayout.NORTH); 
    window2.add(p1HPLabel, BorderLayout.WEST); 
    window2.add(p2HPLabel, BorderLayout.EAST); 
    window2.setVisible(true); 
    window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 


} 
+0

試圖用現有的代碼使用gui builder將會比它的價值更麻煩,恕我直言。你爲什麼不自己寫代碼? –

+0

製作[SSCCE](http://sscce.org)來展示您的問題。 – nachokk

+0

我做了,然後嘗試添加一個JTextArea以包含窗口中可見事件的日誌,並且它不保留在我指定的BorderLayout的中心。它佔據了整個窗口,無法看到任何按鈕,也無法看到頂部的JLabel –

回答

2

直接回答你的問題,你可以創建(實際上是一個自定義類擴展JFrame的)一個JFrame,並在NetBeans可視化設計器設計它,然後在現有的類實例化。您可以使用組合(http://en.wikipedia.org/wiki/Object_composition)並將JFrame引用爲現有類中的字段。您可以在JFrame中提供其他方法以將數據傳遞給它。

相關問題