使用JLabel和ArrayList中的java变量的新行



我创建了一个按钮,它将在一个单独的窗口中(如下图所示)显示数据库中所有用户的列表。

但是,它们都显示在一行中!即使我把/n-它就是不起作用。我的意思是,当我使用Sys.out时,它在控制台中工作,但当我转到窗口并将其放在那里时,它都在一行中:(

为了将所有用户一个接一个地显示,我应该更改什么。

public class ViewAll {
    private String listax = "";
        ViewAll() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
        ArrayList<String[]> allUsers = DbBroker.getArray("select * from user");
                for(String[] usr : allUsers)
                    listax += usr[0] + ")" + usr[1] + ", " + usr[2] + ", " + usr[3] + "n";
        }
    public void display() {
        JFrame lis = new JFrame("List of all users");
        lis.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        lis.setLayout(new FlowLayout(FlowLayout.LEFT));
        JPanel pane = new JPanel(new GridLayout(0,1));
        lis.add(pane);
        pane.add(new JLabel("This is the complete list of all users in my db: "));
        pane.add(new JLabel(listax));
        lis.pack();
        lis.setSize(500,400);
        lis.setVisible(true);
}}

我建议您不要使用JLabel,而是使用JList。它就是为了做这种事而建的。这里的关键是:为工作使用正确的工具。它还显示您正试图在对话框中使用JFrame,如果是这样,请不要使用JDialog,甚至使用JOptionPane:

public void display(List<String> userList) {
  DefaultListModel<String> listModel = new DefaultListModel<String>();
  for (String user : userList) {
    listModel.addElement(user);
  }
  JList<String> userLabel = new JList<String>(listModel);
  JScrollPane scrollPane = new JScrollPane(userLabel);
  String title = "This is the complete list of all users in my db:";
  // mainJFrame is the main JFrame for the GUI
  JOptionPane.showMessageOption(mainJFrame, scrollPane, title, 
       JOptionPane.PLAIN_MESSAGE);  
}

最新更新