- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 2 个 JList,我只想选择其中一项。我仅使用复制错误所需的代码创建了一个单独的程序:主类:
public class Main {
public static void main(String[] args) {
new Staff("John", "D", 123456);
new Staff("Bob", "X", 123455);
Staff.lookup("John","D").setActive(true);
Staff.lookup("Bob","X").setActive(true);
new Staff("Jerry","Smith",384938);
new Staff("Bob","Hope",834802);
new InstructorGUI(1);
}
}
员工等级:
import java.util.ArrayList;
import java.util.List;
public class Staff{
private String fName;
private String lName;
private int emtID;
public static List<Staff> staffIndex = new ArrayList<>();
public static ArrayList<Staff> activeStaffIndex = new ArrayList<>();
Staff(String fName, String lName, int NJEMS) {
this.fName = fName;
this.lName = lName;
staffIndex.add(this);
emtID = NJEMS;
}
//Getters
public int getEmtID() {
return emtID;
}
public String getFirstName() {return fName; }
public String getLastName() {return lName; }
@Override
public String toString() {
return String.format("%s, %s", lName, fName);
}
//Lookups
public static Staff lookup(String fName, String lName) {
for (Staff s : staffIndex) {
if (s.getFirstName().equalsIgnoreCase(fName) && s.getLastName().equalsIgnoreCase(lName)) {
return s;
}
}
return null;
}
//Setters
public void setEmtID(int NJEMS) {
emtID = NJEMS;
}
public void setFirstName(String s) {
fName = s;
}
public void setLastName(String s) {
lName = s;
}
//Removers
public static void removeStaff(Staff s) {
staffIndex.remove(s);
activeStaffIndex.remove(s);
}
//Utilities
public boolean isActive() {
if(activeStaffIndex.contains(this)) {
return true;
} else {
return false;
}
}
public void setActive(Boolean b) {
if (b) {
if (!activeStaffIndex.contains(this)) {
activeStaffIndex.add(this);
}
} else {
if (activeStaffIndex.contains(this)) {
activeStaffIndex.remove(this);
}
}
}
}
InstructorGUI 类:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashSet;
public class InstructorGUI extends JFrame {
private static HashSet<InstructorGUI> instructorGUIIndex = new HashSet<>();
private int identifier;
private JList<Object> listSelected, selectedInstructors, unSelectedInstructors;
public InstructorGUI(int id) {
super("Instructor Editor");
setSize(550, 250);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
identifier = id;
boolean b = false;
for (InstructorGUI i : instructorGUIIndex) {
if (i.getIdentifier() == 1) {
b = true;
}
}
if (b) {
InstructorGUI.lookup(1).dispose();
instructorGUIIndex.remove(InstructorGUI.lookup(1));
}
instructorGUIIndex.add(this);
JPanel container = new JPanel();
JPanel middle = new JPanel();
JPanel inputPanel = new JPanel();
JPanel topButtons = new JPanel();
JPanel left = new JPanel();
JPanel centerButtons = new JPanel();
JPanel right = new JPanel();
JPanel footer = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
middle.setLayout(new BoxLayout(middle, BoxLayout.X_AXIS));
inputPanel.setLayout(new FlowLayout());
topButtons.setLayout(new FlowLayout());
left.setLayout(new FlowLayout());
centerButtons.setLayout(new BoxLayout(centerButtons, BoxLayout.Y_AXIS));
right.setLayout(new FlowLayout());
footer.setLayout(new FlowLayout());
JLabel lNameLabel = new JLabel("Last");
JLabel fNameLabel = new JLabel("First");
JLabel emsIdLabel = new JLabel("EMS ID");
JTextField lNameField = new JTextField(10);
JTextField fNameField = new JTextField(10);
JTextField emsIdField = new JTextField(10);
selectedInstructors = new JList<>();
unSelectedInstructors = new JList<>();
JButton addInstructor = new JButton("Add");
JButton editInstructor = new JButton("Edit");
JButton removeInstructor = new JButton("Remove");
JButton selectInstructor = new JButton("<-");
JButton unSelectInstructor = new JButton("->");
JButton selectAllInstructors = new JButton("<<--");
JButton unSelectAllInstructors = new JButton("-->>");
inputPanel.add(lNameLabel);
inputPanel.add(lNameField);
inputPanel.add(fNameLabel);
inputPanel.add(fNameField);
inputPanel.add(emsIdLabel);
inputPanel.add(emsIdField);
topButtons.add(addInstructor);
topButtons.add(editInstructor);
topButtons.add(removeInstructor);
left.add(selectedInstructors);
centerButtons.add(selectAllInstructors);
centerButtons.add(selectInstructor);
centerButtons.add(unSelectInstructor);
centerButtons.add(unSelectAllInstructors);
right.add(unSelectedInstructors);
footer.add(new JLabel(""));
JScrollPane x = new JScrollPane(selectedInstructors);
JScrollPane y = new JScrollPane(unSelectedInstructors);
x.setPreferredSize(new Dimension(100, 200));
y.setPreferredSize(new Dimension(100, 200));
middle.add(new JLabel(""));
middle.add(x);
middle.add(centerButtons);
middle.add(y);
middle.add(new JLabel(""));
container.add(inputPanel);
container.add(topButtons);
container.add(middle);
container.add(footer);
update();
selectedInstructors.addListSelectionListener(e -> {
unSelectedInstructors.clearSelection();
if(selectedInstructors.getSelectedValue() != null) {
Staff s = Staff.lookup(selectedInstructors.getSelectedValue().toString().split(", ")[1], selectedInstructors.getSelectedValue().toString().split(", ")[0]);
lNameField.setText(s.getLastName());
fNameField.setText(s.getFirstName());
emsIdField.setText(String.format("%s", s.getEmtID()));
listSelected = selectedInstructors;
}
});
unSelectedInstructors.addListSelectionListener(e -> {
selectedInstructors.clearSelection();
if (unSelectedInstructors.getSelectedValue() != null) {
Staff s = Staff.lookup(unSelectedInstructors.getSelectedValue().toString().split(", ")[1], unSelectedInstructors.getSelectedValue().toString().split(", ")[0]);
lNameField.setText(s.getLastName());
fNameField.setText(s.getFirstName());
emsIdField.setText(String.format("%s", s.getEmtID()));
listSelected = unSelectedInstructors;
}
});
setContentPane(container);
setVisible(true);
addInstructor.addActionListener(e -> {
if(lNameField.getText().equalsIgnoreCase("") || fNameField.getText().equalsIgnoreCase("") || emsIdField.getText().equalsIgnoreCase("")) {
return;
}
if(Integer.parseInt(emsIdField.getText()) < 300000 || Integer.parseInt(emsIdField.getText()) > 900000) {
JOptionPane.showMessageDialog(null,"Please choose an EMS ID between 300000 and 900000.");
return;
}
for(Staff s : Staff.staffIndex) {
if(Integer.parseInt(emsIdField.getText()) == s.getEmtID()) {
JOptionPane.showMessageDialog(null, "EMS ID already taken.");
return;
}
}
new Staff(fNameField.getText(),lNameField.getText(),Integer.parseInt(emsIdField.getText()));
update();
});
editInstructor.addActionListener(e -> {
if(lNameField.getText().equalsIgnoreCase("") || fNameField.getText().equalsIgnoreCase("") || emsIdField.getText().equalsIgnoreCase("")) {
return;
}
if(Integer.parseInt(emsIdField.getText()) < 300000 || Integer.parseInt(emsIdField.getText()) > 900000) {
JOptionPane.showMessageDialog(null,"Please choose an EMS ID between 300000 and 900000.");
return;
}
for(Staff s : Staff.staffIndex) {
if(Integer.parseInt(emsIdField.getText()) == s.getEmtID()) {
JOptionPane.showMessageDialog(null, "EMS ID already taken.");
return;
}
}
Staff s = Staff.lookup(listSelected.getSelectedValue().toString().split(", ")[1],listSelected.getSelectedValue().toString().split(", ")[0]);
if(!s.getFirstName().equalsIgnoreCase(fNameField.getText()) || !s.getLastName().equalsIgnoreCase(lNameField.getText()) || s.getEmtID() != Integer.parseInt(emsIdField.getText())) {
s.setFirstName(fNameField.getText());
s.setLastName(lNameField.getText());
s.setEmtID(Integer.parseInt(emsIdField.getText()));
update();
}
});
removeInstructor.addActionListener(e -> {
if(listSelected.getSelectedValue() != null) {
Staff s = Staff.lookup(listSelected.getSelectedValue().toString().split(", ")[1],listSelected.getSelectedValue().toString().split(", ")[0]);
Staff.removeStaff(s);
update();
}
});
selectInstructor.addActionListener(e -> {
if(unSelectedInstructors.getSelectedValue() != null) {
Staff s = Staff.lookup(unSelectedInstructors.getSelectedValue().toString().split(", ")[1], unSelectedInstructors.getSelectedValue().toString().split(", ")[0]);
s.setActive(true);
update();
}
});
unSelectInstructor.addActionListener(e -> {
if(selectedInstructors.getSelectedValue() != null) {
Staff s = Staff.lookup(selectedInstructors.getSelectedValue().toString().split(", ")[1], selectedInstructors.getSelectedValue().toString().split(", ")[0]);
s.setActive(false);
update();
}
});
selectAllInstructors.addActionListener(e -> {
for(Staff s : Staff.staffIndex) {
s.setActive(true);
}
update();
});
unSelectAllInstructors.addActionListener(e -> {
for(Staff s : Staff.staffIndex) {
s.setActive(false);
}
update();
});
}
public int getIdentifier() {
return identifier;
}
public static InstructorGUI lookup(int id) {
for (InstructorGUI i : instructorGUIIndex) {
if (i.getIdentifier() == id) {
return i;
}
}
return null;
}
public void update() {
ArrayList<Staff> selected = new ArrayList<>();
ArrayList<Staff> notSelected = new ArrayList<>();
for (Staff s : Staff.staffIndex) {
if (s.isActive()) {
selected.add(s);
} else {
notSelected.add(s);
}
}
selectedInstructors.removeAll();
unSelectedInstructors.removeAll();
selectedInstructors.setListData(selected.toArray());
unSelectedInstructors.setListData(notSelected.toArray());
}
}
然而,我注意到,有时当我在列表之间切换时,而不是选择该项目,选项周围会出现一个蓝色框。发生这种情况时,我尝试调用 getSelectionIndex(),但它返回 -1。如何让它在每次单击某个项目时都选择?
最佳答案
您的问题出在您的 ListSelectionListener 中。首先,让我们创建一个更好、更简单的 MCVE ,将代码简化为仅重现问题所需的要点:
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
@SuppressWarnings("serial")
public class Main2 extends JPanel {
private JList<String> list1 = new JList<>(new String[] { "one", "two", "three" });
private JList<String> list2 = new JList<>(new String[] { "hello", "goodbye", "yes" });
public Main2() {
list1.setName("list 1");
list2.setName("list 2");
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list1.addListSelectionListener(new MySelectionListener(list2));
list2.addListSelectionListener(new MySelectionListener(list1));
setLayout(new GridLayout(1, 0));
add(new JScrollPane(list1));
add(new JScrollPane(list2));
}
private class MySelectionListener implements ListSelectionListener {
private JList<String> otherList;
public MySelectionListener(JList<String> otherList) {
this.otherList = otherList;
}
@Override
public void valueChanged(ListSelectionEvent e) {
otherList.clearSelection();
}
}
private static void createAndShowGui() {
Main2 mainPanel = new Main2();
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
运行此命令,您将看到问题重现 - 新选择的项目未正确选择所选项目。此外,如果您注释掉该行, otherList.clearSelection();
,您会看到新选择的列表将很好地显示新的选择,因此这一行错误地扰乱了您想要的行为。
可以通过限制何时清除其他列表以仅在调整所选值时来解决此问题:
@Override
public void valueChanged(ListSelectionEvent e) {
// otherList.clearSelection();
if (e.getValueIsAdjusting()) {
otherList.clearSelection();
}
}
为什么这有效?老实说,我不能肯定地说,但我确实知道这将在选择新列表的项目之前清除其他列表的选择,因此它可以工作。此外,您只需要在值未调整时提取所选值,因此需要一个 if/else block ,如下所示:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
@SuppressWarnings("serial")
public class Main2 extends JPanel {
private JList<String> list1 = new JList<>(new String[] { "one", "two", "three" });
private JList<String> list2 = new JList<>(new String[] { "hello", "goodbye", "yes" });
private JTextField selectedItemTxtFld = new JTextField(10);
public Main2() {
list1.setName("list 1");
list2.setName("list 2");
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list1.addListSelectionListener(new MySelectionListener(list2));
list2.addListSelectionListener(new MySelectionListener(list1));
JPanel listPanel = new JPanel(new GridLayout(1, 0));
listPanel.add(new JScrollPane(list1));
listPanel.add(new JScrollPane(list2));
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Selection:"));
topPanel.add(selectedItemTxtFld);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(listPanel, BorderLayout.CENTER);
}
private class MySelectionListener implements ListSelectionListener {
private JList<String> otherList;
public MySelectionListener(JList<String> otherList) {
this.otherList = otherList;
}
@Override
public void valueChanged(ListSelectionEvent e) {
// otherList.clearSelection();
if (e.getValueIsAdjusting()) {
otherList.clearSelection();
} else {
JList<String> thisList = (JList<String>) e.getSource();
if (!thisList.isSelectionEmpty()) {
String selectedText = thisList.getSelectedValue().toString();
selectedItemTxtFld.setText(selectedText);
}
}
}
}
private static void createAndShowGui() {
Main2 mainPanel = new Main2();
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
关于java - JList getSelectionValue 清除后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45109870/
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
在编码时,我问了自己这个问题: 这样更快吗: if(false) return true; else return false; 比这个? if(false) return true; return
如何在逻辑条件下进行“返回”? 在这样的情况下这会很有用 checkConfig() || return false; var iNeedThis=doSomething() || return fa
这是我的正则表达式 demo 如问题所述: 如果第一个数字是 1 则返回 1 但如果是 145 则返回 145 但如果是 133 则返回 133 样本数据a: K'8134567 K'81345678
在代码高尔夫问答部分查看谜题和答案时,我遇到了 this solution返回 1 的最长和最晦涩的方法 引用答案, int foo(void) { return! 0; } int bar(
我想在下面返回 JSON。 { "name": "jackie" } postman 给我错误。说明 Unexpected 'n' 这里是 Spring Boot 的新手。 1日龄。有没有正确的方法来
只要“is”返回 True,“==”不应该返回 True 吗? In [101]: np.NAN is np.nan is np.NaN Out[101]: True In [102]: np.NAN
我需要获取所有在 6 号或 7 号房间或根本不在任何房间的学生的详细信息。如果他们在其他房间,简单地说,我不希望有那个记录。 我的架构是: students(roll_no, name,class,.
我有一个表单,我将它发送到 php 以通过 ajax 插入到 mysql 数据库中。一切顺利,php 返回 "true" 值,但在 ajax 中它显示 false 消息。 在这里你可以查看php代码:
我在 Kotlin 中遇到了一个非常奇怪的无法解释的值比较问题,以下代码打印 假 data class Foo ( val a: Byte ) fun main() { val NUM
请注意,这并非特定于 Protractor。问题在于 Angular 2 的内置 Testability service Protractor 碰巧使用。 Protractor 调用 Testabil
在调试窗口中,以下表达式均返回 1。 Application.WorksheetFunction.CountA(Cells(4 + (i - 1) * rows_per_record, 28) & "
我在本地使用 jsonplaceholder ( http://jsonplaceholder.typicode.com/)。我正在通过 extjs rest 代理测试我的 GET 和 POST 调用
这是 Postman 为成功调用我的页面而提供的(修改后的)代码段。 var client = new RestClient("http://sub.example.com/wp-json/wp/v2
这个问题在这里已经有了答案: What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must
我想我对 C 命令行参数有点生疏。我查看了我的一些旧代码,但无论这个版本是什么,都会出现段错误。 运行方式是 ./foo -n num(其中 num 是用户在命令行中输入的数字) 但不知何故它不起作用
我已经编写了一个类来处理命名管道连接,如果我创建了一个实例,关闭它,然后尝试创建另一个实例,调用 CreateFile() 返回 INVALID_HANDLE_VALUE,并且 GetLastErro
即使 is_writable() 返回 true,我也无法写入文件。当然,该文件存在并且显然是可读的。这是代码: $file = "data"; echo file_get_contents($fil
下面代码中的变量 $response 为 NULL,尽管它应该是 SOAP 请求的值。 (潮汐列表)。当我调用 $client->__getLastResponse() 时,我从 SOAP 服务获得了
我一直在网上的不同论坛上搜索答案,但似乎没有与我的情况相符的... 我正在使用 Windows 7,VS2010。 我有一个使用定时器来调用任务栏刷新功能的应用程序。在该任务栏函数中包含对 LoadI
我是一名优秀的程序员,十分优秀!