[英]How do I display an array of Buttons on to a JScrollPane?
我試圖創建一個按鈕數組,並將它們放在滾動框中,但是什么也沒有顯示。 另外,如何添加動作監聽器?
JPanel buttons4Contacts = new JPanel();
buttons4Contacts.setLayout(new GridLayout(5, 5));
for (User user: Network.usersList){ //Make a JButton for every contact.
JButton button = new JButton(user.getName());
button.setPreferredSize(new Dimension(100,100));
buttons4Contacts.add(button);
}
JPanel contactButtonHolder = new JPanel(new FlowLayout(FlowLayout.CENTER, 0,0));
contactButtonHolder.add(buttonsforContacts);
contacts = new JScrollPane(contactButtonHolder);
contacts.add(buttons4Contacts);
contacts.setPreferredSize(new Dimension(200,200));
rightPanelSouth.add(contacts);
正如其他朋友之前提到的,您可以創建一個面板,在面板中添加所有按鈕,最后將滾動條添加到面板中。
這是完成工作的簡單代碼:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ArrayOfButtons extends JFrame{
final static int numberOfButtons=5;
// Label to display the message indicating which button generated the event.
JLabel label=new JLabel();
// Panel to accomodate the labels
JPanel panel=new JPanel();
//We create an array of buttons whose number depends on our choice
JButton buttons[]=new JButton[numberOfButtons];
public ArrayOfButtons(){
super("Demo");
//We create an instance of the class ButtonHandler which implements the interface
//ActionListener. And this object "handler" is basically the object that handles
//the events.
ButtonHandler handler=new ButtonHandler();
//Using a for loop we create JButtons.
for(int i=0;i<numberOfButtons;i++){
buttons[i]=new JButton("Button"+i);
// here we register handler as the event listener for all the buttons.i.e if in
// case an event occurs in any of the buttons, the event listener (in our case
//the handler object) calls an appropriate method that handles the event.
buttons[i].addActionListener(handler);
// add each button to the panel
panel.add(buttons[i]);
}
// we add the label to the JFrame
add(label,BorderLayout.SOUTH);
// we add ScrollPane to the JFrame and in turn add Panel to the ScrollPane.
add(new JScrollPane(panel));
}
// This is an inner class that handles the events.(Look more on inner classes).
public class ButtonHandler implements ActionListener{
//This method is called in case an action event occurs.For example you click on the
//button
public void actionPerformed(ActionEvent event){
// gets the name of the button and displays in the label.
label.setText(event.getActionCommand());
}
}
}
添加您自己的main方法,該代碼將正常工作。 希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.