当我点击单选按钮时,我正在尝试使组件可见。 RadioButton初始化隐藏在initComponents方法中。
我在单选按钮上放了一个mouseClickListener。如果我初始化radioButton隐藏它不起作用。如果我初始化它可见(默认):
我还尝试在初始化之前进行初始化。
这些是myListeners,txtMaas被隐藏初始化:
private void rbOgretmenMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
txtMaas.setVisible(true);
}
private void rbOgrenciMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
txtMaas.setVisible(false);
}
答案 0 :(得分:1)
revalidate()
和repaint()
,该容器包含您已更改其可见性的组件。重新验证允许容器的布局管理器重新布局其组件,重绘允许Graphics对象重新绘制容器及其所有组件。如,
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class RadioFun extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = 150;
private JRadioButton rbOgret = new JRadioButton("Ogret");
private JTextField txtMaas = new JTextField(10);
public RadioFun() {
setLayout(new FlowLayout(FlowLayout.LEADING));
add(rbOgret);
add(txtMaas);
txtMaas.setVisible(false);
rbOgret.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
rbOgretItemStateChanged(e);
}
});
}
// to make the GUI large enough
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private void rbOgretItemStateChanged(ItemEvent e) {
boolean visible = e.getStateChange() == ItemEvent.SELECTED;
txtMaas.setVisible(visible);
// call repaint and revalidate on the holding JPanel:
revalidate();
repaint();
}
// the two methods below are to create the GUI on the Swing event thread
private static void createAndShowGui() {
JFrame frame = new JFrame("RadioFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RadioFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}