JComboBox 下拉列表保持为空,即使我向它添加元素
JComboBox dropdown stays empty even when I add elements to it
在 class ChatFrame 的 BuildGUI 方法中,有一个名为 dropdown 的 JCombobox,我试图用 class 填充的数组列表填充它。但是每当我 运行 class 时,列表都会成功获取我想要添加到 JComboBox 的数据,但它不会将其添加到组合框。
组合框保持为空。我试图通过 dropdown.addItem("String");
向其中添加元素。它有效,但为什么当我使用来自另一个 class 或相同 class 的araylist使用for循环时它不起作用?
代码如下:
// Class to manage Client chat Box.
public class ChatClient {
/** Chat client access */
static class ChatAccess extends Observable {
private Socket socket;
private OutputStream outputStream;
@Override
public void notifyObservers(Object arg) {
super.setChanged();
super.notifyObservers(arg);
}
/** Create socket, and receiving thread */
public void InitSocket(String server, int port) throws IOException {
socket = new Socket(server, port);
outputStream = socket.getOutputStream();
Thread receivingThread = new Thread() {
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
notifyObservers(line);
} catch (IOException ex) {
notifyObservers(ex);
}
}
};
receivingThread.start();
}
private static final String CRLF = "\r\n"; // newline
/** Send a line of text */
public void send(String text) {
try {
outputStream.write((text + CRLF).getBytes());
outputStream.flush();
} catch (IOException ex) {
notifyObservers(ex);
}
}
/** Close the socket */
public void close() {
try {
socket.close();
} catch (IOException ex) {
notifyObservers(ex);
}
}
}
/** Chat client UI */
static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea;
private JTextField inputTextField;
private JButton sendButton;
private ChatAccess chatAccess;
private JList<String> list;
public DefaultComboBoxModel<String> mod;
private JScrollPane jscrollpane;
public static JComboBox<String> dropdown;
//clientThread ct=new clientThread();
public static ArrayList<String> usr=new ArrayList<String>();
public static String array[]=new String[usr.size()];
public ChatFrame(ChatAccess chatAccess) {
this.chatAccess = chatAccess;
chatAccess.addObserver(this);
buildGUI();
}
/** Builds the user interface */
private void buildGUI() {
for(int j =0;j<usr.size();j++){
array[j] = usr.get(j);
System.out.print("testing"+array[j]);
}
//usr=clientThread.acces();
//System.out.print("test"+usr);
mod = new DefaultComboBoxModel<String>();
list = new javax.swing.JList<>(mod);
list.setBounds(30, 30, 30, 30);
textArea = new JTextArea(20, 50);
textArea.setEditable(false);
textArea.setLineWrap(true);
add(new JScrollPane(textArea), BorderLayout.WEST);
jscrollpane=new JScrollPane();
jscrollpane.setViewportView(list);
add(new JScrollPane(list), BorderLayout.EAST);
Box box = Box.createHorizontalBox();
add(box, BorderLayout.SOUTH);
inputTextField = new JTextField();
dropdown=new JComboBox(array);
dropdown.setBounds(24, 138, 72, 20);
dropdown.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXX");
sendButton = new JButton("Send");
box.add(inputTextField);
box.add(sendButton);
box.add(dropdown);
box.add(populate.dl);
ActionListener sendListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = inputTextField.getText();
if (str != null && str.trim().length() > 0)
chatAccess.send(str);
inputTextField.selectAll();
inputTextField.requestFocus();
inputTextField.setText("");
}
};
inputTextField.addActionListener(sendListener);
sendButton.addActionListener(sendListener);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
chatAccess.close();
}
});
}
/** Updates the UI depending on the Object argument */
public void update(Observable o, Object arg) {
final Object finalArg = arg;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(finalArg.toString());
textArea.append("\n");
}
});
}
}
static class populate{
public static ArrayList<String> naam=new ArrayList<String>();
public static JComboBox<String> dl=new JComboBox<String>();
public void getarr(String name) {
naam.add(name);
System.out.print("populate"+naam);
dl=new JComboBox<String>();
dl.addItem(name);
//ChatFrame.usr.add(name);
//System.out.print("chatframeclass"+ChatFrame.usr);
}
}
public static void main(String[] args) {
String server = args[0];
int port =2222;
ChatAccess access = new ChatAccess();
JFrame frame = new ChatFrame(access);
frame.setTitle("MyChatApp - connected to " + server + ":" + port);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
try {
access.InitSocket(server,port);
} catch (IOException ex) {
System.out.println("Cannot connect to " + server + ":" + port);
ex.printStackTrace();
System.exit(0);
}
}
}
您的代码的问题在于,当您在以下行中将 array
添加到 dropdown
时,array
为空:
dropdown=new JComboBox(array);
您可以通过打印 array
来验证这一点,例如System.out.println(Arrays.toString(array));
在将其添加到 dropdown
.
之前
下面给出了 minimal reproducible example 如何将 String
数组添加到 JComboBox<String>
的工作原理:
String[]arr= {"Hello","Hi","Bye"};
dropdown = new JComboBox(arr);
在 GUI 中,您会看到 dropdown
已经填充了 arr[]
的元素。如果将上面的代码替换成如下
String[]arr= {};
dropdown = new JComboBox(arr);
你会发现dropdown
变成了空的。
在 class ChatFrame 的 BuildGUI 方法中,有一个名为 dropdown 的 JCombobox,我试图用 class 填充的数组列表填充它。但是每当我 运行 class 时,列表都会成功获取我想要添加到 JComboBox 的数据,但它不会将其添加到组合框。
组合框保持为空。我试图通过 dropdown.addItem("String");
向其中添加元素。它有效,但为什么当我使用来自另一个 class 或相同 class 的araylist使用for循环时它不起作用?
代码如下:
// Class to manage Client chat Box.
public class ChatClient {
/** Chat client access */
static class ChatAccess extends Observable {
private Socket socket;
private OutputStream outputStream;
@Override
public void notifyObservers(Object arg) {
super.setChanged();
super.notifyObservers(arg);
}
/** Create socket, and receiving thread */
public void InitSocket(String server, int port) throws IOException {
socket = new Socket(server, port);
outputStream = socket.getOutputStream();
Thread receivingThread = new Thread() {
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
notifyObservers(line);
} catch (IOException ex) {
notifyObservers(ex);
}
}
};
receivingThread.start();
}
private static final String CRLF = "\r\n"; // newline
/** Send a line of text */
public void send(String text) {
try {
outputStream.write((text + CRLF).getBytes());
outputStream.flush();
} catch (IOException ex) {
notifyObservers(ex);
}
}
/** Close the socket */
public void close() {
try {
socket.close();
} catch (IOException ex) {
notifyObservers(ex);
}
}
}
/** Chat client UI */
static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea;
private JTextField inputTextField;
private JButton sendButton;
private ChatAccess chatAccess;
private JList<String> list;
public DefaultComboBoxModel<String> mod;
private JScrollPane jscrollpane;
public static JComboBox<String> dropdown;
//clientThread ct=new clientThread();
public static ArrayList<String> usr=new ArrayList<String>();
public static String array[]=new String[usr.size()];
public ChatFrame(ChatAccess chatAccess) {
this.chatAccess = chatAccess;
chatAccess.addObserver(this);
buildGUI();
}
/** Builds the user interface */
private void buildGUI() {
for(int j =0;j<usr.size();j++){
array[j] = usr.get(j);
System.out.print("testing"+array[j]);
}
//usr=clientThread.acces();
//System.out.print("test"+usr);
mod = new DefaultComboBoxModel<String>();
list = new javax.swing.JList<>(mod);
list.setBounds(30, 30, 30, 30);
textArea = new JTextArea(20, 50);
textArea.setEditable(false);
textArea.setLineWrap(true);
add(new JScrollPane(textArea), BorderLayout.WEST);
jscrollpane=new JScrollPane();
jscrollpane.setViewportView(list);
add(new JScrollPane(list), BorderLayout.EAST);
Box box = Box.createHorizontalBox();
add(box, BorderLayout.SOUTH);
inputTextField = new JTextField();
dropdown=new JComboBox(array);
dropdown.setBounds(24, 138, 72, 20);
dropdown.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXX");
sendButton = new JButton("Send");
box.add(inputTextField);
box.add(sendButton);
box.add(dropdown);
box.add(populate.dl);
ActionListener sendListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = inputTextField.getText();
if (str != null && str.trim().length() > 0)
chatAccess.send(str);
inputTextField.selectAll();
inputTextField.requestFocus();
inputTextField.setText("");
}
};
inputTextField.addActionListener(sendListener);
sendButton.addActionListener(sendListener);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
chatAccess.close();
}
});
}
/** Updates the UI depending on the Object argument */
public void update(Observable o, Object arg) {
final Object finalArg = arg;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(finalArg.toString());
textArea.append("\n");
}
});
}
}
static class populate{
public static ArrayList<String> naam=new ArrayList<String>();
public static JComboBox<String> dl=new JComboBox<String>();
public void getarr(String name) {
naam.add(name);
System.out.print("populate"+naam);
dl=new JComboBox<String>();
dl.addItem(name);
//ChatFrame.usr.add(name);
//System.out.print("chatframeclass"+ChatFrame.usr);
}
}
public static void main(String[] args) {
String server = args[0];
int port =2222;
ChatAccess access = new ChatAccess();
JFrame frame = new ChatFrame(access);
frame.setTitle("MyChatApp - connected to " + server + ":" + port);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
try {
access.InitSocket(server,port);
} catch (IOException ex) {
System.out.println("Cannot connect to " + server + ":" + port);
ex.printStackTrace();
System.exit(0);
}
}
}
您的代码的问题在于,当您在以下行中将 array
添加到 dropdown
时,array
为空:
dropdown=new JComboBox(array);
您可以通过打印 array
来验证这一点,例如System.out.println(Arrays.toString(array));
在将其添加到 dropdown
.
下面给出了 minimal reproducible example 如何将 String
数组添加到 JComboBox<String>
的工作原理:
String[]arr= {"Hello","Hi","Bye"};
dropdown = new JComboBox(arr);
在 GUI 中,您会看到 dropdown
已经填充了 arr[]
的元素。如果将上面的代码替换成如下
String[]arr= {};
dropdown = new JComboBox(arr);
你会发现dropdown
变成了空的。