【发布时间】:2021-07-21 03:53:03
【问题描述】:
主类
public class Main {
public static void main(String[] args) {
new CredentialManager();
}
}
主窗口类
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CredentialManager extends JFrame implements ActionListener {
public CredentialManager() {
View.credentialManager.setSize(1200, 800);
View.credentialManager.setResizable(false);
View.credentialManager.setLayout(null);
View.credentialManager.setLocationRelativeTo(null);
View.credentialManager.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
View.credentialManager.setVisible(true);
View.btnCredentialManagerManageUser.setBounds(550, 50, 120, 30);
View.btnCredentialManagerSignOut.setBounds(50, 50, 95, 30);
View.listCredentials.setBounds(100,100, 75,75);
View.btnCredentialManagerManageUser.addActionListener(this);
View.btnCredentialManagerSignOut.addActionListener(this);
View.credentialManager.add(View.btnCredentialManagerManageUser);
View.credentialManager.add(View.btnCredentialManagerSignOut);
View.credentialManager.add(View.scrollPaneCredentials);
View.scrollPaneCredentials.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
View.listModelCredentials.addElement("Credential1");
View.listModelCredentials.addElement("Credential2");
View.listModelCredentials.addElement("Credential3");
View.listModelCredentials.addElement("Credential4");
View.listModelCredentials.addElement("Credential5");
View.listModelCredentials.addElement("Credential6");
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource().equals(View.btnCredentialManagerManageUser)) {
System.out.println("Manager");
} else if (actionEvent.getSource().equals(View.btnCredentialManagerSignOut)) {
System.out.println("Sign Out");
}
}
}
使用 Swing 元素查看类
import javax.swing.*;
public class View {
static JFrame credentialManager = new JFrame("Credential Manager");
static JButton btnCredentialManagerManageUser = new JButton("Manage User");
static JButton btnCredentialManagerSignOut = new JButton("Sign Out");
static DefaultListModel<String> listModelCredentials = new DefaultListModel<>();
static JList<String> listCredentials = new JList(listModelCredentials);
static JScrollPane scrollPaneCredentials = new JScrollPane(listCredentials);
}
当我执行主类时,列表不会出现。我希望主框架包含两个按钮(出现)和带有滚动条的列表,但它没有出现。我尝试了很多东西,但其中任何一个都有效。
【问题讨论】:
-
你的整个班级都应该重组。 1) 你不应该扩展 JFrame。 2)你不应该使用静态变量。 3)您不应该使用空布局。 4) 应该在 EDT 上创建 GUI。 5) 组件应在框架可见之前添加到框架中。首先阅读 How to Use Lists 上的 Swing 教程中的部分。下载“listDemo”示例并了解其工作原理,然后根据您的特定要求进行更改。
标签: java list swing jscrollpane jlist