添加到JList时JRadioButton无效对齐

问题描述 投票:0回答:1

嗨我正在为航班预订系统制作一个gui,我必须确保用户在点击查询按钮时只在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]

我可以知道发生了什么以及如何解决这个问题吗? 谢谢。

java swing jlist jradiobutton
1个回答
1
投票

当我运行时,JList显示以下行:

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

我可以知道发生了什么以及如何解决这个问题吗?

发生这种情况是因为你的JList有一个DefaultListCellRenderer.正如你所看到的,这个类extends JLabel。方法DefaultListCellRenderer#getListCellRendererComponent()正在争论Object value。此值的类型等于JList的类型。

话虽如此,你的JListJRadioButton作为通用类型(JList< JRadioButton>),这意味着对象值arguemnt是JRadioButton

现在,DefaultListCellRenderer为了得到它的文本,它调用值的toString()方法,因此你在列表的单元格中得到这种文本。 (JRadioButton的toString()方法,返回其细节,坐标,大小等......)

解决方案:

这将是使用自定义ListCellRenderer。这样,您可以在getListCellRendererComponent()方法中呈现名为“value”i的参数的任何value-property。在您的情况下,您需要渲染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));
    }
}

预习:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.