在下面的代码中,XPos 不断更改值,而我的代码没有对其进行任何操作。
public class JTwinPreviewButtons {
static PreviewPanel previewPanel;
static EditorPanel editorPanel;
ArrayList<JTwinPreviewButtons> subButtons = new ArrayList<JTwinPreviewButtons>();
private static int overallYPos = 0;
Item item;
JButton plusButton;
JButton itemButton;
private boolean isPlus;
private boolean shown;
private int YPos;
private int XPos;
public JTwinPreviewButtons(Item someItem, int itemNum) {
plusButton = new JButton("-");
itemButton = new JButton(someItem.getName());
item = someItem;
isPlus = false;
shown = true;
System.out.println("Item Number: "+itemNum);
XPos = (itemNum * 15) + 25;
System.out.println(XPos); //XPos == 70
if (previewPanel!=null) {
if (itemNum == 0) {
previewPanel.addTopButton(this);
}
previewPanel.refresh(); //printed inside here XPos == 25
System.out.println(XPos); //XPos == 70
}
plusButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isPlus) {
for (JTwinPreviewButtons subs : subButtons) {
subs.setSubShown(true);
}
plusButton.setText("-");
isPlus = false;
previewPanel.refresh();
} else {
for (JTwinPreviewButtons subs : subButtons) {
subs.setSubShown(false);
}
plusButton.setText("+");
isPlus = true;
previewPanel.refresh();
}
}
});
itemButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//here XPos == 70
//after initialization method XPos == 25
}
}
private void updateYPos() {
YPos = overallYPos;
overallYPos += 25;
}
private void setBounds() {
updateYPos();
System.out.println(XPos); //25
plusButton.setBounds(XPos-20, YPos+2, 16, 16);
itemButton.setBounds(XPos, YPos, itemButton.getText().length()*7+15, 20);
}
public void display() {
if (shown) {
System.out.println(XPos); //25
setBounds();
previewPanel.add(plusButton);
previewPanel.add(itemButton);
}
}
因此,似乎 XPos 仅在初始化方法期间保留其值。没有其他地方可以设置 XPos 的值。真正让我感到困惑的是,无论我在初始化时将 XPos 设置为什么,它总是恢复为 25,但我已经搜索了我所有的代码,寻找我错误地执行“XPos = 25”的任何其他地方,它根本不存在我的代码......还有什么可以在这里工作?
编辑:
import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JPanel;
public class PreviewPanel {
ArrayList<JTwinPreviewButtons> topButtons = new ArrayList<JTwinPreviewButtons>();
JPanel panel = new JPanel(null);
public PreviewPanel() {
panel.setPreferredSize(new Dimension(600,750));
refresh();
}
public void addTopButton(JTwinPreviewButtons button) {
topButtons.add(button);
}
public void add(Component comp) {
panel.add(comp);
}
public void refresh() {
panel.removeAll();
recursiveRefresh(topButtons);
}
private void recursiveRefresh(ArrayList<JTwinPreviewButtons> list) {
for (JTwinPreviewButtons o : list) {
o.display();
recursiveRefresh(o.getSubButtons());
}
}
public JPanel getComponent() {
return panel;
}
}