Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 添加到JList时JRadioButton对齐无效_Java_Swing_Jlist_Jradiobutton - Fatal编程技术网

Java 添加到JList时JRadioButton对齐无效

Java 添加到JList时JRadioButton对齐无效,java,swing,jlist,jradiobutton,Java,Swing,Jlist,Jradiobutton,您好,我正在为航班预订系统制作一个gui,当单击查询按钮时,我必须确保用户只在JList中选择一个航班,因此我决定制作一个RadioButton的JList,如下所示: flightsList = new JList<JRadioButton>(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {

您好,我正在为航班预订系统制作一个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]
javax.swing.JRadioButton[,0,0,0x0,无效,alignmentX=0.0,alignmentY=0.5….
]

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

发生这种情况是因为您的
JList
具有一个属性,如您所见,此类
扩展了
JLabel
。方法
DefaultListCellRenderer#getListCellRenderComponent()
正在获取一个参数
对象值
。此值的类型等于
JList
的类型

话虽如此,您的
JList
JRadioButton
作为泛型类型(
JList
),这意味着对象值arguemnt是
JRadioButton

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

解决方案:

这将是一个习惯。通过这种方式,您可以在
getListCellRenderComponent()
方法中呈现名为“value”i的参数的任何value属性。在本例中,您需要呈现
JRadioButton

为了更好地理解这一点,我将在代码中分享一个带有注释的示例

导入java.awt.BorderLayout;
导入java.awt.Component;
导入java.util.List;
导入javax.swing.DefaultListModel;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JList;
导入javax.swing.JRadioButton;
导入javax.swing.ListCellRenderer;
导入javax.swing.SwingUtilities;
公共类JListJRadioButtonRenderer扩展了JFrame{
公共JListJRadioButtonRenderer(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addList();
设置大小(300300);
setLocationRelativeTo(空);
}
私有void addList(){
JList list=新JList();
DefaultListModel=新的DefaultListModel();
//添加自定义渲染器。
setCellRenderer(新的ListCellRenderer(){
@凌驾

公共组件GetListCellRenderComponent(JList)不要直接将组件添加到JList,您可以添加数据,然后使用渲染来渲染它们。“我必须确保用户在JList中只选择一个航班”
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));
    }
}