我想將文本輸入到第四個JPanel中,並且每次按Enter鍵以更新帶有文本的第一個JPanel 。我爲返回鍵添加了一個keylistener,它在內部類AddSong中運行一個函數,該函數接受一個文本的數組列表,並返回一個字符串。我想在第一個quadrent中的JPanel上顯示該字符串,但它不起作用。現在我相信這是刪除第一個JPanel,而不是更新。我很困惑,因爲這是我第一次遇到關鍵事件,因爲我是編程新手。如何從我的內部類引用「顯示」變量,以在我的JLabel中使用外部類
下面的代碼:
public class MusicPlayer extends JFrame{
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private JLabel songList,songPlaying,c;
private JTextField enterSong;
private AddSong input;
public MusicPlayer(){
//Text box enterSong, input passed to actionListener
input = new AddSong();
enterSong = new JTextField(10);
enterSong.addActionListener(input);
//Numbers the quadrents
songList = new JLabel(input.printSongs(input.songList),SwingConstants.CENTER);
songPlaying = new JLabel("2",SwingConstants.CENTER);
c = new JLabel("c",SwingConstants.CENTER);
//Makes and sets size of pane
Container pane = getContentPane();
pane.setLayout(new GridLayout(2,2));
//Add JLabels to panes in the container
pane.add(songList);
pane.add(songPlaying);
pane.add(c);
pane.add(enterSong);
//KeyListener - return
addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent ke){}
@Override
public void keyReleased(KeyEvent ke){}
@Override
public void keyTyped(KeyEvent ke){
if(ke.getKeyCode()==KeyEvent.VK_ENTER){
input.printSongs(input.songList);
}
}
});
add(songList);
pack();
setTitle("Andrew's Music Player");
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class AddSong implements ActionListener{
//List of Songs
ArrayList<String> songList = new ArrayList<String>();
String display;
public AddSong(){
display = "";
}
public void actionPerformed(ActionEvent e){
String song;
//get the text
song = enterSong.getText();
//add current text string to list
songList.add(song);
//print songlist
System.out.print(printSongs(songList));
}
public String printSongs(ArrayList<String> songList){
display = "";
for(int i = 0; i < songList.size(); i++){
display += songList.get(i) + "\n";
}
return display;
}
}
public static void main(String args[]){
MusicPlayer boi = new MusicPlayer();
}
}
請告訴我們你得到的錯誤是哪一行。 (並且不要給我們一個行號,這不足以讓我們知道哪一行導致錯誤。) – ajb
我在讀取「songList = new JLabel(addSong。顯示,SwingConstants.CENTER);在音樂播放器類的音樂播放器功能 –