添加到 JList 时 JRadioButton 无效对齐

JRadioButton invalid alignment when add to JList

您好,我正在为航班预订系统制作一个图形用户界面,我必须确保用户在单击查询按钮时只在 JList 中选择一个航班,所以我决定制作一个 RadioButton 的 JList,如下所示:

  flightsList = new JList<JRadioButton>();

  button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      //user inputs
      String takeoff = (String) from.getSelectedItem();
      String destina = (String) to.getSelectedItem();
      String flyDate = (String) date.getText();

      try {
        //get all available flights
        Flight[] flights = manager.getFlights(takeoff, destina, flyDate);
        //model for list
        DefaultListModel<JRadioButton> model =
                                      new DefaultListModel<JRadioButton>();
        //fill model with flights found
        for(int flightNum = 0; flightNum < flights.length; flightNum++) {
          model.addElement(new JRadioButton(flights[flightNum].toString()));
        }//for

        //put model into jlist
        flightsList.setModel(model);

      } catch (BadQueryException bqe) {
        JRadioButton[] errorMessage = {
                      new JRadioButton("Error: " +  bqe.getMessage()) };
        //put error message into list
        flightsList.setListData(errorMessage);
      }//try catch

    }//actionPerformed
  });

当我运行时,JList 显示行:

javax.swing.JRadioButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@78092fac,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=false,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=BA002 | London >> Manchester | Tue, 01/10/2019 06:30]

请问这是怎么回事,怎么解决?
谢谢。

When I run, the JList shows lines of:

javax.swing.JRadioButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5....]

May I know what happened and how to solve this?

发生这种情况是因为您的 JList 有一个 DefaultListCellRenderer.,如您所见,这个 class extends JLabel。方法 DefaultListCellRenderer#getListCellRendererComponent() 正在获取参数 Object value。此值的类型等于您的 JList.

的类型

话虽如此,您的 JList 具有 JRadioButton 作为通用类型 (JList< JRadioButton>),这意味着对象值参数是 JRadioButton

现在,DefaultListCellRenderer 为了获取其文本,它调用值的 toString() 方法,因此您可以在列表的单元格中获取此类文本。 (JRadioButton 的 toString() 方法,returns 它的详细信息、坐标、大小等...)

解决方法:

这将是使用自定义 ListCellRenderer。通过这种方式,您可以在 getListCellRendererComponent() 方法中呈现名为 "value"i 的参数的任何值-属性。在您的情况下,您需要渲染 JRadioButton.

我将分享一个示例 ,代码中包含注释 以便更好地理解这一点。

SSCCE:

import java.awt.BorderLayout;
import java.awt.Component;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;

public class JListJRadioButtonRenderer extends JFrame {
    public JListJRadioButtonRenderer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addList();
        setSize(300, 300);
        setLocationRelativeTo(null);
    }

    private void addList() {
        JList<JRadioButton> list = new JList<>();
        DefaultListModel<JRadioButton> model = new DefaultListModel<>();
        // Add the custom renderer.
        list.setCellRenderer(new ListCellRenderer<JRadioButton>() {

            @Override
            public Component getListCellRendererComponent(JList<? extends JRadioButton> list, JRadioButton value,
                    int index, boolean isSelected, boolean cellHasFocus) {
                // Fix background for selected cells.
                value.setBackground(isSelected ? list.getSelectionBackground() : null);
                // Select the JRadioButton too since it is selected in the list.
                value.setSelected(isSelected);
                return value;
            }
        });
        list.setModel(model);
        JRadioButton stackButton = new JRadioButton("Hello Stack");
        JRadioButton overButton = new JRadioButton("Hello Over");
        JRadioButton flowButton = new JRadioButton("Hello Flow");
        model.addElement(stackButton);
        model.addElement(overButton);
        model.addElement(flowButton);
        getContentPane().add(list);

        JButton printSelected = new JButton("Print selected");
        printSelected.addActionListener(e -> {
            List<JRadioButton> selectedButtons = list.getSelectedValuesList();
            for (JRadioButton r : selectedButtons)
                System.out.println(r.getText());
        });
        getContentPane().add(printSelected, BorderLayout.PAGE_END);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JListJRadioButtonRenderer().setVisible(true));
    }
}

预览: