我有一個問題,當我創建一個面板的滾動面板是對象我想爲每個面板添加一個按鈕,當我點擊它時,它將返回產品並將其放入一個變量中。問題在於它只是滾動窗格中最後一個連接到Action Listener的對象面板。這裏是滾動面板和個別面板的代碼:創建實際的面板ActionListener不適用於所有的對象
try{
System.out.println(sql);
ResultSet rs = data.SQL.executeQuery(sql);
String list = "";
int count=0;
while (rs.next()){
count++;
}
ResultSet result = data.SQL.executeQuery(sql);
ProductDisplayPanel.removeAll();
JPanel addPanel = new JPanel();
addPanel.setLayout(new GridLayout (count, 1));
JScrollPane scroll = new JScrollPane();
while (result.next()) {
searchDisplay = new SearchDisplay (result);
scroll.add(searchDisplay);
addPanel.add(searchDisplay);
}
scroll.setPreferredSize(new Dimension(425,390));
scroll.setViewportView(addPanel);
ProductDisplayPanel.add(scroll);
ProductDisplayPanel.revalidate();
ProductDisplayPanel.repaint();
System.out.println(list);
SearchDisplay.AddToCart.addActionListener(action);
frame.add(SearchDisplay.AddToCart);
} catch (Exception ae){
ae.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
類:
public SearchDisplay(ResultSet result) throws Exception{
setPreferredSize(new Dimension(500, 156));
setVisible(true);
String link = result.getString("image");
System.out.println(link);
BufferedImage icecream = ImageIO.read(new URL("file:///"+link));
JLabel lblImage = new JLabel(new ImageIcon (icecream));
name = result.getString("Name");
JLabel lblName = new JLabel(name);
String category = result.getString("Pieces");
JLabel lblFlavour = new JLabel("Pieces: "+category);
String productID = result.getString("ProductID");
JLabel lblPrice = new JLabel("Product ID: " + productID);
String price = result.getString("Price");
JLabel lblType = new JLabel("Price: "+ price +" kr");
String age= result.getString("Age");
JLabel lblBrand = new JLabel("Age: "+age);
AddToCart = new JButton("Add to cart");
不要使用'JScrollPane的#add',這是而不是你如何設置滾動窗格的視圖。而是使用'JScrollPane#setViewportView'。查看[如何使用滾動窗格](http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html)瞭解更多詳情。請記住,滾動窗格只能有一個視圖 – MadProgrammer
所有面板都很好地顯示,這不是問題。我添加一個JButton到每個面板和一個監聽器到這個按鈕。問題是,它只適用於其中一個面板,而不是所有當你點擊它 –
恥辱,你沒有提供的代碼,演示如何動作監聽器註冊或工作...(另外,它實際上是一個系列是小的意外,實際上讓滾動窗格工作) – MadProgrammer