如何将JButton放在JComboBox中

时间:2023-01-27 21:48:19

I would like to put a JButton inside a JComboBox. This button lets users browse for files. The file the user selects gets added to the JComboBox list. How do I do this? Do I use some kind of a Renderer? Thank you.

我想把一个JButton放在一个JComboBox中。此按钮允许用户浏览文件。用户选择的文件将添加到JComboBox列表中。我该怎么做呢?我是否使用某种渲染器?谢谢。

EDIT: After reading more about ListCellRenderer I tried the following code:

编辑:在阅读了有关ListCellRenderer的更多信息后,我尝试了以下代码:

JComboBox comboBox = new JComboBox(new String[]{"", "Item1", "Item2"});
ComboBoxRenderer renderer = new ComboBoxRenderer();
comboBox.setRenderer(renderer);

class ComboBoxRenderer implements ListCellRenderer {

    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {

        JButton jbutton = new JButton("Browse");

        return jbutton;
    }
}

The problem with the above is that the Button "Browse" will be added 3 times and I want it to display only once and below it to display Item1 and Item2 as normal/regular combobox selection objects.

上面的问题是按钮“浏览”将被添加3次,我希望它只显示一次和低于它,以显示Item1和Item2作为普通/常规组合框选择对象。

4 个解决方案

#1


3  

I would avoid the JButton. It is perfectly possible to get the image of a JButton inside your combobox, but it will not behave itself as a button. You cannot click it, it never gets visually 'pressed' nor 'released', ... . In short, your combobox will contain an item which behaves unfamiliar to your users.

我会避免JButton。完全有可能在组合框中获得JButton的图像,但它不会像按钮那样表现自己。你不能点击它,它永远不会被视觉上“按下”或“释放”,....简而言之,您的组合框将包含一个您的用户不熟悉的项目。

The reason for this is that the components you return in the getListCellRendererComponent method are not contained in the JCombobox. They are only used as a stamp. That also explains why you can (and should) reuse the Component you return in that method, and not create new components the whole time. This is all explained in the JTable tutorial in the part about Renderers and Editors (explained for a JTable but valid for all other Swing components which use renderers and editors).

原因是您在getListCellRendererComponent方法中返回的组件不包含在JCombobox中。它们仅用作邮票。这也解释了为什么你可以(并且应该)重用在该方法中返回的Component,而不是一直创建新的组件。关于渲染器和编辑器的部分在JTable教程中对此进行了解释(针对JTable进行了解释,但对使用渲染器和编辑器的所有其他Swing组件都有效)。

If you really want an item in the combobox that allows to show a file chooser, I would opt for something similar to the following SSCCE:

如果你真的想要在组合框中允许显示文件选择器的项目,我会选择类似于以下SSCCE的东西:

import javax.swing.JComboBox;
import javax.swing.JFrame;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class ComboboxTest {

  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        JFrame frame = new JFrame( "TestFrame" );
        JComboBox<String> comboBox = new JComboBox<>(new String[]{"Item1", "Item2"});
        final String browse = "<<BROWSE>>";
        comboBox.addItem( browse );
        comboBox.addItemListener( new ItemListener() {
          @Override
          public void itemStateChanged( ItemEvent e ) {
            if ( e.getStateChange() == ItemEvent.SELECTED && 
                browse.equals( e.getItem() ) ){
              System.out.println("Show filechooser");
            }
          }
        } );
        frame.add( comboBox );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setVisible( true );
        frame.pack();
      }
    } );
  }
}

#2


1  

Indeed, you will have to use a custom renderer as explained on http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer.

实际上,您必须使用http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer中所述的自定义渲染器。

#3


1  

Depending on where you want to put the search button, you could take a look at the xswingx Prompt/Buddy API. You could use this to "buddy" the browse button with the editor field

根据您想要放置搜索按钮的位置,您可以查看xswingx Prompt / Buddy API。您可以使用它来使用编辑器字段“伙伴”浏览按钮

Or you could simply add a browse button next to the combo box.

或者您只需在组合框旁边添加一个浏览按钮即可。

#4


1  

After trying out many things I think I figured out the Answer, I am sure it will look very easy when you see it:

在尝试了很多事情后,我想我已经找到了答案,我相信当你看到它时看起来很容易:

        JComboBox comboBox = new JComboBox(new String[]{"Item1", "Item2"});
        ComboBoxRenderer renderer = new ComboBoxRenderer();
        comboBox.setRenderer(renderer);
        comboBox.addItem("<<BROWSE>>");

class ComboBoxRenderer implements ListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index,         boolean isSelected, boolean cellHasFocus) {
            if (value.equals("<<BROWSE>>")) {
                JButton btn = new JButton("Browse");
                return btn;
            } else {
                JLabel lbl = new JLabel(value.toString());
                lbl.setOpaque(true);
                return lbl;
            }
        }
    }

You can now customize the button and labels any way you wish.

您现在可以按照自己的方式自定义按钮和标签。

#1


3  

I would avoid the JButton. It is perfectly possible to get the image of a JButton inside your combobox, but it will not behave itself as a button. You cannot click it, it never gets visually 'pressed' nor 'released', ... . In short, your combobox will contain an item which behaves unfamiliar to your users.

我会避免JButton。完全有可能在组合框中获得JButton的图像,但它不会像按钮那样表现自己。你不能点击它,它永远不会被视觉上“按下”或“释放”,....简而言之,您的组合框将包含一个您的用户不熟悉的项目。

The reason for this is that the components you return in the getListCellRendererComponent method are not contained in the JCombobox. They are only used as a stamp. That also explains why you can (and should) reuse the Component you return in that method, and not create new components the whole time. This is all explained in the JTable tutorial in the part about Renderers and Editors (explained for a JTable but valid for all other Swing components which use renderers and editors).

原因是您在getListCellRendererComponent方法中返回的组件不包含在JCombobox中。它们仅用作邮票。这也解释了为什么你可以(并且应该)重用在该方法中返回的Component,而不是一直创建新的组件。关于渲染器和编辑器的部分在JTable教程中对此进行了解释(针对JTable进行了解释,但对使用渲染器和编辑器的所有其他Swing组件都有效)。

If you really want an item in the combobox that allows to show a file chooser, I would opt for something similar to the following SSCCE:

如果你真的想要在组合框中允许显示文件选择器的项目,我会选择类似于以下SSCCE的东西:

import javax.swing.JComboBox;
import javax.swing.JFrame;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class ComboboxTest {

  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        JFrame frame = new JFrame( "TestFrame" );
        JComboBox<String> comboBox = new JComboBox<>(new String[]{"Item1", "Item2"});
        final String browse = "<<BROWSE>>";
        comboBox.addItem( browse );
        comboBox.addItemListener( new ItemListener() {
          @Override
          public void itemStateChanged( ItemEvent e ) {
            if ( e.getStateChange() == ItemEvent.SELECTED && 
                browse.equals( e.getItem() ) ){
              System.out.println("Show filechooser");
            }
          }
        } );
        frame.add( comboBox );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setVisible( true );
        frame.pack();
      }
    } );
  }
}

#2


1  

Indeed, you will have to use a custom renderer as explained on http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer.

实际上,您必须使用http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer中所述的自定义渲染器。

#3


1  

Depending on where you want to put the search button, you could take a look at the xswingx Prompt/Buddy API. You could use this to "buddy" the browse button with the editor field

根据您想要放置搜索按钮的位置,您可以查看xswingx Prompt / Buddy API。您可以使用它来使用编辑器字段“伙伴”浏览按钮

Or you could simply add a browse button next to the combo box.

或者您只需在组合框旁边添加一个浏览按钮即可。

#4


1  

After trying out many things I think I figured out the Answer, I am sure it will look very easy when you see it:

在尝试了很多事情后,我想我已经找到了答案,我相信当你看到它时看起来很容易:

        JComboBox comboBox = new JComboBox(new String[]{"Item1", "Item2"});
        ComboBoxRenderer renderer = new ComboBoxRenderer();
        comboBox.setRenderer(renderer);
        comboBox.addItem("<<BROWSE>>");

class ComboBoxRenderer implements ListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index,         boolean isSelected, boolean cellHasFocus) {
            if (value.equals("<<BROWSE>>")) {
                JButton btn = new JButton("Browse");
                return btn;
            } else {
                JLabel lbl = new JLabel(value.toString());
                lbl.setOpaque(true);
                return lbl;
            }
        }
    }

You can now customize the button and labels any way you wish.

您现在可以按照自己的方式自定义按钮和标签。