gpt4 book ai didi

java - JTextArea append() 方法写入两次?

转载 作者:行者123 更新时间:2023-11-29 05:49:35 25 4
gpt4 key购买 nike

我遇到了一个小问题。
在我的 GUI 中,我在中心有一个文本区域 (BorderLayout)。然后我在西边有一个JList

当我单击列表中的歌曲名称时,文本区域应显示歌曲的名称、艺术家和价格。我一切正常,但问题是当我点击成员(member)时,标题、艺术家和价格显示两次。

这里是“valueChanged()”的代码和相关的部分代码。

      public void valueChanged(ListSelectionEvent e)
{
Object source = e.getSource();
int index = songList.getSelectedIndex();
Song selection = songCollection[index];

if(source == songList)
{
textArea.append(selection.getTitle() + " " + selection.getArtist() + " " + selection.getPrice() + "\n" );
}
}
private Song songCollection[] = new Song[5];
private String songTitle[] = new String[5];

//Fill song array
songCollection = getSongs();
songTitle = getSongTitle();

//Methods:
public Song[] getSongs()
{
Song[] array = new Song[5];
array[0] = new Song("Summer", "Mozart", 1.50);
array[1] = new Song("Winter", "Mozart", 1.25);
array[2] = new Song("Spring", "Mozart", 2.00);
array[3] = new Song("Baby", "Justin Bieber", 0.50);
array[4] = new Song("Firework", "Katy Perry", 1.00);

return array;
}

public String[] getSongTitle()
{
String[] names = new String[5];
for(int i = 0; i < 5; i++)
names[i] = songCollection[i].getTitle();

return names;
}

刚才我又在摆弄我的程序时,我注意到了一些事情。当我按下列表中的一个成员时,它仍然像以前一样打印两次。但是,我注意到当我按住鼠标时它会打印一次,而当我松开它时它会再次打印。因此,如果我在 1 个成员上按下鼠标,并将光标向上/向下拖动到其他成员,它们会打印一次,但当我松开鼠标时,它会再次打印我结束的那个。

最佳答案

JTextArea.append() 被您的 ListSelectionListener 调用了两次。

原因可以在How to Use Lists中找到:

Many list selection events can be generated from a single user action such as a mouse click. The getValueIsAdjusting method returns true if the user is still manipulating the selection. This particular program is interested only in the final result of the user's action, so the valueChanged method does something only if getValueIsAdjusting returns false.

您需要检查 JList 中的选择是否不再被操作。您可以用检查包围 append 方法:

if (!e.getValueIsAdjusting()) {
textArea.append(...);
}

关于java - JTextArea append() 方法写入两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444644/

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