我想将 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 都丢失了。
最佳答案
由于您对 JPanel 使用 BorderLayout,
setLayout(new BorderLayout());
如果不指定位置,组件将始终添加到中心。 add(scroll);
与 add(scroll,BorderLayout.CENTER);
相同,因为您通过添加添加的所有组件仅最后添加的组件可见。请参阅 this as well
接下来是单独添加 JTextArea,这样它将从 ScrollPane 中删除。只需将滚动 Pane 添加到 Panel 中,无需添加所有组件。[单独添加父组件]
add(name,BorderLayout.NORTH);
//add(desc);Noo need to add desc as it is already added in JScrollPane
add(scroll,BorderLayout.CENTER);
JPanel不需要setVisible。JPanel需要像JFrame一样嵌入到Container中才可见
//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);
关于java - 添加面板到面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31338306/