我正在为一个项目编写一个 IM 客户端 GUI。在窗口的左侧,我想要一个滚动窗格,其中包含每个活动用户的单选按钮,以便在按下新聊天按钮时,将与所选用户创建聊天。
我已经实现了一个带有 3 个给定用户的示例 GUI。我为每个创建一个 JRadioButton,设置一个 ActionCommand 和一个 ActionListener,将其添加到 ButtonGroup,然后将其添加到“this”,这是一个扩展 JScrollPane 的类。但是,当我运行代码时,我在左侧只看到一个空框架,没有按钮。谁能解释一下?相关代码如下。
package gui;
import javax.swing.*;
public class ActiveList extends JScrollPane implements ActionListener {
private ButtonGroup group;
private String selected;
public ActiveList() {
//TODO: will eventually need access to Server's list of active usernames
String[] usernames = {"User1", "User2", "User3"};
ButtonGroup group = new ButtonGroup();
this.group = group;
for (String name: usernames) {
JRadioButton button = new JRadioButton(name);
button.setActionCommand(name);
button.addActionListener(this);
this.group.add(button);
this.add(button);
}
}
public String getSelected() {
return this.selected;
}
@Override
public void actionPerformed(ActionEvent e) {
this.selected = e.getActionCommand();
System.out.println(e.getActionCommand());
}
}
我正在运行的主要方法来自另一个类 ChatGUI.java。ConversationsPane 容器是我的 GUI 中的另一个类,它工作正常。
package gui;
import javax.swing.*;
public class ChatGUI extends JFrame {
private ConversationsPane convos;
private ActiveList users;
public ChatGUI() {
ConversationsPane convos = new ConversationsPane();
this.convos = convos;
ActiveList users = new ActiveList();
this.users = users;
GroupLayout layout = new GroupLayout(this.getContentPane());
this.getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addComponent(users, 100, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(convos)
);
layout.setVerticalGroup(
layout.createParallelGroup()
.addComponent(users)
.addComponent(convos)
);
}
public static void main(String[] args) {
ChatGUI ui = new ChatGUI();
ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.setVisible(true);
ui.setSize(800,400);
ui.convos.newChat("Chat A");
}
}