2011-01-27 61 views
2

假设我想将JComboBox(或更一般的JPanel,或许?)添加到JRadioButton,那么最简单的方法是什么?JRadioButton中的JComboBox

伪明智的,单选按钮组,其中一人包括多种选择看起来是这样的:

澳天气
Ø缔约方
-O {元,伪} -science
Ø动物

其中{}将成为下拉列表。这里的诀窍是,如果点击下拉列表或标签10'-science'单选按钮将被激活并显示UI边界和所有花哨的东西。

谢谢:)

回答

3

我不喜欢给这样的答案,但在这种情况下,我觉得这是最好的......

这似乎是一个非常不标准的用户界面组件。这将是更好的UX,如果你只是做:

O The weather 
O Parties 
O meta-science 
O pseudo-science 
O Animals 

用户将不熟悉你所建议的组件的类型,它是在列表中的其他选项非常不一致。我强烈建议使用更标准的约定。


反对我的判断,我将向您展示ComboBoxRadioButton
它是不完整的,我也不建议使用它,但它看起来像你想要什么。

import java.awt.FlowLayout; 

import javax.swing.AbstractButton; 
import javax.swing.ButtonGroup; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JRadioButton; 
import javax.swing.JToggleButton; 

public class ComboBoxRadioButton extends JRadioButton { 

    private JLabel beforeText, afterText; 
    private JComboBox comboBox; 

    public ComboBoxRadioButton(String beforeTxt, JComboBox comboBox, 
              String afterText) { 
     this.comboBox = comboBox; 
     this.beforeText = new JLabel(" " + beforeTxt); 
     this.afterText = new JLabel(afterText); 
     comboBox.setSelectedIndex(0); 
     setLayout(new FlowLayout()); 
     setModel(new JToggleButton.ToggleButtonModel()); 
     add(this.beforeText); 
     add(this.comboBox); 
     add(this.afterText); 
    } 

    public static void main(String[] args) { 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel mainPane = new JPanel(); 
     ButtonGroup group = new ButtonGroup(); 
     AbstractButton b2 = new JRadioButton("Java Swing"); 
     AbstractButton b3 = new ComboBoxRadioButton(
       "It's gonna be a", new JComboBox(new String[] { "good", "bad", 
       "rainy" }), "day!"); 
     AbstractButton b4 = new JRadioButton("After the combo"); 
     group.add(b2); 
     group.add(b3); 
     group.add(b4); 
     mainPane.add(b2); 
     mainPane.add(b3); 
     mainPane.add(b4); 
     f.add(mainPane); 
     f.pack(); 
     f.setVisible(true); 
    } 
} 
+0

是啊非标准的UI FTW,我为什么要符合? :) 您的解决方案很简单,虽然对于“很多”选项,并假设其他单选按钮选项是真正相关和相关的,我不认为这是一个可行的解决方案。 此外,我真的很想看到一个Java Guru抛出一些不错的代码来炫耀:) – Juhl 2011-01-27 21:34:38

+0

@Juhl,你问它,所以它就是这样。它不完整,我也不建议使用它。看我的编辑。 – jjnguy 2011-01-27 22:48:44

0

我喜欢Justin的答案,但另一个备选建议:

放在一个单一的JComboBox的所有选项。

如果你真的想要从你的问题采取的路线是可能的。实现这一目标的最佳方式将是:

  • 在中间创建一个JPanel具有一个JRadioButton在左边,组合及标签的权利。
  • 添加鼠标侦听器来捕捉面板上的点击。
  • 调整边框,布局和其他UI项目,使其看起来不错。