Java 选择JRadioButton时如何刷新JPanel?
Java 选择JRadioButton时如何刷新JPanel?,java,swing,actionlistener,jradiobutton,Java,Swing,Actionlistener,Jradiobutton,我有这门课: public class TF extends JPanel implements ActionListener { private ButtonGroup buttonGroup = new ButtonGroup(); private JRadioButton rdbtnFilm; private JRadioButton rdbtnSerieTv; private JPanel pnlGeneral; private JPanel pn
我有这门课:
public class TF extends JPanel implements ActionListener
{
private ButtonGroup buttonGroup = new ButtonGroup();
private JRadioButton rdbtnFilm;
private JRadioButton rdbtnSerieTv;
private JPanel pnlGeneral;
private JPanel pnlRadioButton;
private JLabel lblTitolo;
private JTextField tfTitolo;
public TF()
{
pnlGeneral = new JPanel();
pnlRadioButton = new JPanel();
rdbtnFilm = new JRadioButton("Film");
rdbtnFilm.addActionListener(this);
pnlRadioButton.add(rdbtnFilm);
buttonGroup.add(rdbtnFilm);
rdbtnSerieTv = new JRadioButton("Serie Tv");
rdbtnSerieTv.addActionListener(this);
pnlRadioButton.add(rdbtnSerieTv);
buttonGroup.add(rdbtnSerieTv);
pnlGeneral.add(pnlRadioButton, gbc_panel_1);
this.add(pnlGeneral);
}
public void actionPerformed(ActionEvent e)
{
if(rdbtnFilm.isSelected())
{
lblTitolo = new JLabel("Titolo");
pnlGeneral.add(lblTitolo, gbc_lblTitolo);
tfTitolo = new JTextField();
tfTitolo.setColumns(10);
tfTitolo.setText("1");
pnlGeneral.add(tfTitolo, gbc_tfTitolo);
}
if(rdbtnSerieTv.isSelected())
{
lblTitolo = new JLabel("Titolo");
pnlGeneral.add(lblTitolo, gbc_lblTitolo);
tfTitolo = new JTextField();
tfTitolo.setColumns(10);
tfTitolo.setText("1");
pnlGeneral.add(tfTitolo, gbc_tfTitolo);
}
}
}
但当我选择一个单选按钮时,有时JPanel会显示JLabel和JTextfield。我不知道是否需要使用revalidate()、repaint()或其他方法来刷新JPanel。
这是因为Swing不是线程安全的
更新
这是因为Swing不是线程安全的
否,发生这种情况是因为您正在将组件添加到已显示的容器中,从而导致组件层次结构无效。见文件
我不知道是否需要使用revalidate()
,repaint()
或其他方法来刷新JPanel
是的,按照上一点。这种情况下的典型顺序是:
panel.add(someComponent);
panel.revalidate();
panel.repaint();
有没有其他方法可以做到这一点? 是的。正如我在报告中所说,IMHO是正确的方式。请参见教程 简言之:
- 保持面板上有单选按钮李>
- 有两个不同的面板:一个用于电影,另一个用于电视剧
- 使用
创建另一个CardLayout
JPanel
- 将这两个面板(或根据需要添加多个)添加为卡
- 在单选按钮更改上,只需切换卡布局面板的右侧“卡”
panel.add(someComponent);
panel.revalidate();
panel.repaint();