gpt4 book ai didi

java - 根据 JLabel 内容对面板进行排序

转载 作者:行者123 更新时间:2023-12-02 04:22:08 25 4
gpt4 key购买 nike

我有以下声明:

public JPanel compPanes[] = new JPanel[13];
public JPanel userPanes[] = new JPanel[13];
public int cNum = 0;

现在,我有一个方法,它将四个 JPanel 添加到另一个面板,直到它有四个面板(只是该方法的更短的替代版本):

public void addCompPanels(JPanel compPane)
{
Random rand = new Random();
cPanelNum = (int)(Math.round(Math.random() * 10 + 1));
compPanes[cNum] = new JPanel();
compPanes[cNum].setPreferredSize(new Dimension(80, 90));
compPanes[cNum].add(new JLabel());
JLabel label = (JLabel)compPanes[cNum].getComponent(0);
label.setFont(pickFont);
label.setText("" +cPanelNum);
compPanes[cNum].setBackground(color);
compPane.add(compPanes[cNum]);
compPane.revalidate();
cNum++;
}

总共添加四个面板后,我想根据其 JLabel 的整数值对面板进行排序。

我对如何对整数进行排序进行了一些实验,尝试它是否有效(因为我认为它可以在 JPanels 上工作)。但它似乎不适用,因为它返回空指针异常。

for(int i = 0; i < compPanes.length; i++){
for(int j = i+1; j < compPanes.length; j++){

JLabel lblOne = (JLabel)compPanes[i].getComponent(0);
JLabel lblTwo = (JLabel)compPanes[j].getComponent(0);

if((Integer.parseInt(lblOne.getText())) >(Integer.parseInt(lblTwo.getText())));
{
tempPanel = compPanes[i];
compPanes[i] = compPanes[j];
compPanes[j] = tempPanel;
compPane.add(compPanes[i]);
compPane.add(compPanes[j]);
compPane.revalidate();
compPane.repaint();
}
}
}

视觉表现:

交换前

enter image description here

交换后

enter image description here

谢谢。

最佳答案

既然您要求提供示例,我将添加一个简单的示例。请注意,它在某种程度上是伪代码,因此您必须根据您的需要对其进行调整(主要目的是教导不要提供易于使用的代码):

Collection<JPanel> panels = ...;
Collections.sort( panels, new Comparatory<JPanel>() {
public int compare( JPanel o1, JPanel o2) {
JLabel l1 = o1.getLabel();
JLabel l2 = o2.getLabel();

if( l1 != null && l2 != null ) {
//note that the text might be null as well, so handle this
//further note that if the text represents multi-digit numbers you might have to parse them first
return l1.getText().compareTo( l2.getText() );
}
else ... //decide how to handle null labels
}
};

如果您想直接对数组进行排序,请使用 Arrays.sort( array, comparator ) 。请注意,我不确定您是否会以这种方式干扰某些 Swing 组件内部(而且我现在无法深入研究 Swing 来检查这一点)。

关于java - 根据 JLabel 内容对面板进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32651306/

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