gpt4 book ai didi

Java 图形不显示更改

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:26 25 4
gpt4 key购买 nike

我正在开发一个小的 Java applet,对于这个编程来说是非常新的。使用 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());
}
}

下面是我用来测试的小程序

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

}

}

问题是,当我测试小程序时,单击鼠标可以很好地更改选项,但是新的 JCheckBoxes 不会显示。尝试打印出选择器中每个组件的边界表明 JCheckBox 边界仍然卡在 (0,0,0,0),而按钮的边界没有改变。我多次尝试重新绘制 OptionSelector 和整个小程序,但似乎没有任何效果。关于如何解决此问题的任何想法?

最佳答案

在删除和添加组件时,您似乎忘记在 JPanel 容器上调用 revalidate():

public void mouseClicked(MouseEvent arg0) {
s.setOptions("1", "2");
s.revalidate();
repaint();
}

如果您希望容器(您的 JPanel)在容器中适本地布置新组件,这是必不可少的。另外,这不是一件好事:

public void paint(Graphics g) {
s.repaint();
}

因为您无缘无故地覆盖了顶级组件的 paint 方法,也没有调用 super 方法。只需摆脱该方法即可。

关于Java 图形不显示更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9336916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com