我有一些顯示JOptionPane
中的文本字段的視圖。還有一個按鈕「其他」。點擊它後,我需要JOptionPane
重繪本身並顯示一些隱藏的文本字段。重新繪製JOptionPane中的組件
我對我的文本字段使用GridLayout。我在按鈕偵聽器中嘗試了revalidate()
和repaint()
方法,但它們沒有做任何更改。
validate()
方法工作,但所有組件的大小太小。似乎在網格面板中調整大小錯誤。在我原來的代碼中,一些組件只是隱藏起來。我沒有setPrefferedSize()
或getPrefferedSize()
,因爲我讀它是錯誤的,但無法弄清楚如何做出正確的大小調整後。
我拿我的代碼,盡我所能,只是視圖的一部分。
public class AddView {
private JFrame parentFrame;
private JPanel addPanel;
private JPanel gd;
private JLabel nameLabel;
private JLabel surName;
private JLabel skype;
private JTextField nameTField;
private JTextField surNameTField;
private JTextField skypeTField;
private JButton otherButton;
public AddView(JFrame parent) {
this.parentFrame = parent;
initComponents();
}
private void initComponents() {
addPanel = new JPanel(new BorderLayout());
gd = new JPanel(new GridLayout(2, 2, 0, 5));
nameLabel = new JLabel("Name");
surName = new JLabel("Surname");
skype = new JLabel("Skype");
nameTField = new JTextField();
surNameTField = new JTextField();
skypeTField = new JTextField();
otherButton = new JButton("Other");
gd.add(nameLabel);
gd.add(nameTField);
gd.add(surName);
gd.add(surNameTField);
addPanel.add(gd, BorderLayout.CENTER);
addPanel.add(otherButton, BorderLayout.SOUTH);
otherButton.addActionListener(new OtherFieldsAction());
}
public int showAddPane() {
return JOptionPane.showConfirmDialog(parentFrame, addPanel, "Add Contact", JOptionPane.OK_CANCEL_OPTION);
}
private class OtherFieldsAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
gd.setLayout(new GridLayout(3, 2, 0, 5));
gd.add(skype);
gd.add(skypeTField);
// gd.revalidate(); not work
// gd.repaint();
gd.validate();
}
}
}
這是JOptionPane的
當我點擊 「其他」 按鈕,我有這樣的結果
但我需要得到它的權利調整這樣的
你能給出一個關於如何進行正確重繪的建議。
在這種情況下,直到他們有關它可能是最好禁用的組件。 –
@Andrew Thompson你的意思是使用'JComponent.disable()'?不知道我是否理解正確。 – dimads
*「你的意思是使用'JComponent.disable()'?」*那麼,鑑於該方法已被棄用,因爲** Java 1.1,**沒有。嘗試改爲['setEnabled(boolean)'](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#setEnabled-boolean-)。 –