Java JTextArea append()方法写入两次?
我遇到了一个小问题。Java JTextArea append()方法写入两次?,java,swing,jlist,jtextarea,Java,Swing,Jlist,Jtextarea,我遇到了一个小问题。 在我的GUI中,我在中心有一个文本区域(BorderLayout)。然后我在西边有一个JList 当我点击列表中的歌曲标题时,文本区域应显示歌曲的标题、艺术家和价格。 我所有的东西都在工作,但问题是当我点击一个成员时,标题、艺术家和价格会显示两次 以下是“valueChanged()”的代码以及相关代码的部分 public void valueChanged(ListSelectionEvent e) { Object source
在我的GUI中,我在中心有一个文本区域(
BorderLayout
)。然后我在西边有一个JList
当我点击列表中的歌曲标题时,文本区域应显示歌曲的标题、艺术家和价格。
我所有的东西都在工作,但问题是当我点击一个成员时,标题、艺术家和价格会显示两次
以下是“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;
}
public void值已更改(ListSelectionEvent e)
{
对象源=e.getSource();
int index=songList.getSelectedIndex();
歌曲选择=歌曲集[索引];
如果(源==歌曲列表)
{
textArea.append(selection.getTitle()+“”+selection.getArtist()+“”+selection.getPrice()+“\n”);
}
}
私人歌曲集[]=新歌[5];
私有字符串songTitle[]=新字符串[5];
//填充歌曲数组
songCollection=getSongs();
songTitle=getSongTitle();
//方法:
公共歌曲[]获取歌曲()
{
歌曲[]数组=新歌[5];
数组[0]=新歌(“夏天”,“莫扎特”,1.50);
数组[1]=新歌(“冬天”,“莫扎特”,1.25);
数组[2]=新歌(“春天”,“莫扎特”,2.00);
数组[3]=新歌(“宝贝”,“贾斯汀·比伯”,0.50);
数组[4]=新歌(“烟花”,“凯蒂·佩里”,1.00);
返回数组;
}
公共字符串[]getSongTitle()
{
字符串[]名称=新字符串[5];
对于(int i=0;i<5;i++)
name[i]=songCollection[i].getTitle();
返回姓名;
}
当我再次摆弄我的程序时,我注意到了一些事情。当我按下列表中的成员时,它仍然像以前一样打印两次。然而,我注意到,当我按住鼠标时,它会打印一次,当我放开鼠标时,它会再次打印。因此,如果我在一个成员上按鼠标,并将光标向上/向下拖动到其他成员上,他们会打印一次,但当我放开鼠标时,它会再次打印我结束的成员。JTextArea.append()
会从列表选择侦听器中调用两次
原因可在中找到:
许多列表选择事件可以通过单个用户操作(如鼠标单击)生成。如果用户仍在操作选择,则getValueIsAdjusting方法返回true。这个特定的程序只对用户操作的最终结果感兴趣,因此valueChanged方法只有在getValueIsAdjusting返回false时才会执行某些操作
您需要检查JList
中的选择是否不再被操纵。您可以在append
方法周围加上复选框:
if (!e.getValueIsAdjusting()) {
textArea.append(...);
}
请不要在标题中使用标签。您希望一次最多显示一首歌曲还是可以显示更多?一次应显示多首歌曲(文本区域应为购物车)。这就是为什么我使用append()而不是setText()if(e.getValueIsAdjusting()==false)
应该简单地编写if(!e.getValueIsAdjusting())
是的,这很有效(尽管在你告诉我之前我已经弄明白了:d)谢谢你!没问题。因为你是SO新手,任何你觉得有用的答案都不要忘记接受。看到这个了吗