我正在开发一个小型Java小程序,对于这个编程工具来说非常新。使用Java 1.6
我有一个类,可以创建多个JPanel
个复选框。目标是让用户选择一些固定数量的选项,然后将这些选项传递给其他方法
public class OptionSelector extends JPanel {
private JCheckBox[] optionCheckBoxes;
private int numberSelected;
private int goalNumber;
private ArrayList<String> selectedOptions = new ArrayList<String>();
private boolean rightAmountSelected;
private boolean isFinalChoice = false;
private DoneButton done = new DoneButton();
/**
* This method is used only for the purposes of initialization
*
*/
public OptionSelector()
{
this(1, "test", "test");
}
public OptionSelector(int howManyToSelect, String ... options)
{
super(new FlowLayout());
JCheckBox option;
optionCheckBoxes = new JCheckBox[options.length];
for (int i = 0; i < options.length; i++)
{
option = new JCheckBox(options[i]);
optionCheckBoxes[i] = option;
add(option);
}
add(done);
numberSelected = 0;
goalNumber = howManyToSelect;
rightAmountSelected = false;
}
public void setOptions(String ... options)
{
this.removeAll();
JCheckBox option;
optionCheckBoxes = new JCheckBox[options.length];
for (int i = 0; i < options.length; i++)
{
option = new JCheckBox(options[i]);
optionCheckBoxes[i] = option;
add(option);
System.out.println(option.getBounds());
}
add(done);
System.out.println(done.getBounds());
}
public void paintComponent(Graphics g)
{
g.clearRect(0,0,this.getWidth(), this.getHeight());
for (int i = 0; i < getComponentCount(); i++)
{
System.out.println(this.getComponents()[i].getBounds());
}
}
我用来测试它的applet位于
之下public class TestDisplay extends JApplet implements MouseListener{
OptionSelector s = new OptionSelector();
public void init()
{
setSize(640,480);
this.getContentPane().setLayout(null);
addMouseListener(this);
s.setBounds(10,10,200,200);
add(s);
s.repaint();
}
public void paint(Graphics g)
{
s.repaint();
}
public void mouseClicked(MouseEvent arg0)
{
s.setOptions("1","2");
repaint();
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
问题在于,当我测试applet时,单击鼠标会更改选项,但不会显示新的JCheckBoxes
。尝试在选择器中打印出每个组件的边界,表明JCheckBox
边界仍然停留在(0,0,0,0),而按钮的边界没有改变。我曾尝试多次重新绘制OptionSelector
和整个applet,但似乎没有任何效果。关于如何解决这个问题的任何想法?
答案 0 :(得分:5)
在删除和添加组件时,您似乎忘记在JPanel容器上调用revalidate()
:
public void mouseClicked(MouseEvent arg0) {
s.setOptions("1", "2");
s.revalidate();
repaint();
}
如果您希望容器(您的JPanel)适当地布置容器中的新组件,这是必不可少的。此外,这不是一件好事:
public void paint(Graphics g) {
s.repaint();
}
因为你没有充分的理由而没有调用super方法而覆盖了顶级组件的paint方法。只是摆脱那种方法。