我试图对一些不支持swing的旧java代码做一些小补充。我需要添加一个包含一个面板的小对话框,该面板有一个复选框和几个文本字段。当用户点击我要禁用的复选框或启用复选框时。这部分似乎运行良好,但文本字段没有正确重绘。当我单击复选框时,字段似乎没有启用但是如果我然后单击面板或文本字段,您会看到它们已启用(反之亦然,当我取消选中复选框时,字段仍然显示为启用直到你尝试点击它们并且它们变成鬼影并且不被选中)。我使用setEnabled(boolean)来设置字段的状态。在更改状态后,我尝试在字段和面板上调用重绘和验证,但这似乎不起作用。我也试图让字段请求焦点,这不起作用。有没有其他想法?
//The class that contains all of this is of type Window
//Declaration of the components
private Panel _inputPanel;
private TextField min , max;
//This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
}
//listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
答案 0 :(得分:1)
在调用setEnabled(boolean)之后,您需要在Panel上调用update(Graphics g)。
我尝试使用以下代码(根据您提供的代码构建),其工作正常。
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class CheckUI extends Dialog implements ItemListener {
// The class that contains all of this is of type Window
// Declaration of the components
private Panel _inputPanel;
private TextField min, max;
private Checkbox cb;
public CheckUI(Frame owner, boolean modal) {
super(owner, modal);
_inputPanel = new Panel();
this.add(_inputPanel);
addMinMaxtextFields("min", "max");
}
// This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
cb = new Checkbox();
cb.addItemListener(this);
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
_inputPanel.add(cb);
}
// listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
/**
* @param args
*/
public static void main(String[] args) {
Frame parent = new Frame();
parent.setVisible(true);
parent.setExtendedState(Frame.MAXIMIZED_BOTH);
parent.pack();
CheckUI ui = new CheckUI(parent, true);
ui.pack();
ui.setVisible(true);
}
}