2015-07-10 101 views
1

我试图添加一个JPanel到我现有的JPanel,所以我可以有一个JTextField的小窗口顶部带有一个名称和一个可滚动的JTextArea下面有一些描述。我做了如下构造函数扩展JPanel类:将面板添加到面板

import javax.swing.*; 
import javax.swing.border.EtchedBorder; 
import javax.swing.border.TitledBorder; 
import java.awt.*; 

public class LocationWindow extends JPanel { 
    public JTextField name; 
    public JTextArea desc; 
    public JScrollPane scroll; 

    public LocationWindow(){ 
     super(); 
     setBorder (new TitledBorder(new EtchedBorder(), "Display Area")); 
     setLayout(new BorderLayout()); 
     setVisible(true); 
     setBounds(30, 40, 700, 290); 
     name = new JTextField(10); 
     name.setText("name"); 
     desc = new JTextArea(5,10); 
     scroll = new JScrollPane(desc); 
     scroll.setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
     desc.setEditable (true); 
     desc.setLineWrap(true); 
     desc.setText("random text"); 
     add(name); 
     add(desc); 
     add(scroll); 
     validate(); 
    } 
} 

它几乎适用,因为它给我的边框和滚动窗口,但无论是的JTextField和JTextArea中失踪。

+0

为了更好地帮助越早,张贴[MCVE(http://stackoverflow.com/help/mcve)(最小完备可验证例)或[SSCCE(HTTP:// WWW .sscce.org /)(简短,独立,正确的例子)。 'setBounds(30,40,700,290);'不要这样做。在GUI中使用布局填充和边框作为空白区域。 –

回答

1

当您使用BorderLayout对JPanel,

setLayout(new BorderLayout()); 

组件将始终被添加到中心。 add(scroll);是一样add(scroll,BorderLayout.CENTER);你要添加的所有通过添加,最后添加的成分仅是visible.Refer this as well

接下来是要添加的JTextArea seperately所以它会从ScrollPane.Just被删除滚动面板添加到面板无需添加的所有成分。[添加单独的母组件]

add(name,BorderLayout.NORTH); 
    //add(desc);Noo need to add desc as it is already added in JScrollPane 
    add(scroll,BorderLayout.CENTER); 

有没有需要调用setVisible为JPanel.JPanel需要嵌入在集装箱喜欢的JFrame可见

  //setVisible(true);Wont do anything 

所以这样调用

JFrame frame = new JFrame(); 
    frame.add(new LocationWindow()); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.pack(); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
+0

是的,谢谢!这非常有用,因为我的其他面板没有布局,所以我不知道这些细节。 – seMikel

+0

除非您专门将其他面板的布局设置为null,否则它*具有布局 - JPanel的默认布局,即FlowLayout。 – FredK

0

您可以使用下面的代码将面板添加到面板。如果你不指定位置

public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    LocationWindow loc = new LocationWindow(); 
    frame.add(loc); 
    frame.setSize(300, 200); 
    frame.setVisible(true); 
} 
+0

问题是当我需要添加该面板时,我无法访问我的框架。所以发生的一切都发生在我想添加这个的另一个面板上。 – seMikel