我开发了一个模板GUI,我想重复使用,为此我添加了一个在模板中为空的面板,我想动态地加载它。所以假设下面的代码:
public class TempGUI extends JFrame{
public TempGUI(JPanel DynamicPanel){
InitComponents();
this.DynamicPanel = DynamicPanel;
}
...
}
这似乎不起作用,因为面板没有改变。我认为这应该是正常的,那么有没有办法获取动态面板的组件和表单中的SET THEM?
答案 0 :(得分:1)
所有this.DynamicPanel = DynamicPanel;
都是实例字段,this.DynamicPanel
现在指向参数DynamicPanel
。如果参数不在屏幕上,那么你将看不到任何东西。事实上,这不会影响this.DynamicPanel
指向的内容。
相反,请考虑将参数实际添加到容器中......
public class TempGUI extends JFrame{
public TempGUI(JPanel DynamicPanel){
InitComponents();
this.DynamicPanel.add(DynamicPanel);
}
...
}
但是你需要稍微改变一下,所以你会DynamicPanelContent
(它会取代this.DynamicPanel
),这样你就可以继续引用this.DynamicPanel
了会指出你传递给构造函数的东西......
public class TempGUI extends JFrame{
private JPanel dynamicPanel;
public TempGUI(JPanel dynamicPanel){
initComponents();
this.dynamicPanel = dynamicPanel;
this.dynamicPanelContent.add(this.dynamicPanel);
}
...
}
或者其他一些......
更新了示例
你尝试过吗?并且没有理由在此定义私有字段。它不起作用。
似乎对我工作正常......
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel myView = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("Hello!");
myView.add(label, gbc);
JButton btn = new JButton("Say good-bye");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Good bye");
}
});
gbc.gridy++;
myView.add(btn, gbc);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane(myView));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane<V extends JPanel> extends JPanel {
private V view;
public TestPane(V view) {
setLayout(new BorderLayout());
this.view = view;
JPanel viewContent = new JPanel(new BorderLayout());
viewContent.setBorder(new EmptyBorder(10, 10, 10, 10));
viewContent.add(view);
add(viewContent);
}
public V getView() {
return view;
}
}
}