我希望这个 SearchPanel 出现在我的三个标签中。
您不能这样做,因为组件只能添加到一个容器中。如果添加到多个容器中,则只有最近添加的内容可见且有效。
- 尝试使用静态字段永远不是这类问题的答案。
- 考虑将搜索面板从 JTabbedPane 持有的组件中拉出,以便它始终可见,很可能在显示 JTabbedPane 的同一容器中。
- 或者,如果您必须在某些但不是所有选项卡中具有此功能,那么您将不得不按照 MVC 重构代码,创建一个“模型”类来保存搜索窗格显示的数据模型(视图),然后创建此模型的一个实例并创建多个搜索窗格,每个搜索窗格再次通过 MVC 共享同一模型。
例如:
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class SharedPanelMain extends JPanel {
private static final int PANEL_COUNT = 5;
private SharedPanelModel sharedModel = new SharedPanelModel();
private SharedPanel[] panels = new SharedPanel[PANEL_COUNT];
public SharedPanelMain() {
JTabbedPane tabbedPane = new JTabbedPane();
for (int i = 0; i < panels.length; i++) {
panels[i] = new SharedPanel(sharedModel);
String title = "Panel " + (i + 1);
tabbedPane.add(title, panels[i]);
}
add(tabbedPane);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SharedPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SharedPanelMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class SharedPanelModel {
public static final String[] MODEL_DATA = { "one", "two", "three", "four",
"five" };
private DefaultListModel listModel = new DefaultListModel();
private PlainDocument textAreaDocument = new PlainDocument();
private ListSelectionModel listSelectionModel = new DefaultListSelectionModel();
public SharedPanelModel() {
for (String datum : MODEL_DATA) {
listModel.addElement(datum);
}
}
public ListModel getListModel() {
return this.listModel;
}
public Document getTextAreaDocument() {
return textAreaDocument;
}
public ListSelectionModel getListSelectionModel() {
return listSelectionModel;
}
}
@SuppressWarnings("serial")
class SharedPanel extends JPanel {
private SharedPanelModel model;
private JList list = new JList();
private JTextArea textArea = new JTextArea(20, 50);
public SharedPanel(SharedPanelModel model) {
this.model = model;
list.setModel(model.getListModel());
list.setSelectionModel(model.getListSelectionModel());
textArea.setDocument(model.getTextAreaDocument());
add(new JScrollPane(list));
add(new JScrollPane(textArea));
}
}