【问题标题】:How can I put labels on buttons created from a JComboBox?如何在从 JComboBox 创建的按钮上放置标签?
【发布时间】:2013-04-15 01:52:30
【问题描述】:

我正在创建电梯,并从 JComboBox 制作了一些按钮,但我似乎无法在它们上贴上标签。最多可以创建 8 个按钮,并且这些按钮必须从下到上命名。所以最后添加的按钮应该是一楼。

如何在从 JComboBox 创建的按钮上制作标签?

[-------floor N-------]
[-------floor 3-------]
[-------floor 2-------]
[-------floor 1-------]

这是我的一些代码...

//The main class
public class Elevator_Simulation extends JFrame implements ActionListener {

public JLabel state; //The current state of the elevator being displayed
public ButtonPanel control; //The button control panel
private Elevator elevator; //The elevator area
String[] floorStrings = {"Select one", "1", "2", "3", "4", "5", "6", "7", "8"};    
JComboBox floorList = new JComboBox(floorStrings); //The combo box
JButton go = new JButton();
public JPanel buttons;
//private int counter;

//constructor
public Elevator_Simulation() {        

    //Setting up layout and content pane
    this.setSize(500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocation(100, 100);
    this.getContentPane().setLayout(new BorderLayout(1, 1));

    buttons = new JPanel(new GridLayout(8, 1));
    add(buttons);

    //Panel creation
    JPanel centerpanel = new JPanel();
    centerpanel.setLayout(new FlowLayout());

    //Adds the button panel to the BorderLayout
    this.getContentPane().add(buttons, BorderLayout.EAST);

    // adds the title to the top of p3
    p3.add(title, BorderLayout.NORTH);
    // adds floorlist to the top right of p3
    p3.add(floorList, BorderLayout.NORTH);
    // adds the start button to the panel
    p3.add(go, BorderLayout.NORTH);
    go.setText("Start");
    go.addActionListener(this);
    // adds p2 to the right of the container
    this.getContentPane().add(p3, BorderLayout.NORTH);

//Main method
public static void main(String[] args) {
    Elevator_Simulation eSim = new Elevator_Simulation();
    eSim.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    eSim.setVisible(true);
}

//start of the actionPerformed
@Override
public void actionPerformed(ActionEvent e) {
    int count = floorList.getSelectedIndex();
    //buttons.removeAll();
    for (int index = 0; index < count; index++) {
        buttons.add(new JButton("F" + String.valueOf(index)));
    }
    buttons.revalidate();

    elevator = new Elevator(this);
    this.getContentPane().add(elevator, BorderLayout.CENTER);

}
//end of the actionPerformed

【问题讨论】:

  • 按您希望它们出现的顺序将项目添加到组合框中

标签: java swing jbutton jcombobox


【解决方案1】:

更改floorStrings 的顺序,使楼层按您期望的顺序显示。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox08 {

    public static void main(String[] args) {
        new TestComboBox08();
    }

    public TestComboBox08() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JComboBox cb = new JComboBox(new String[]{"Select one", "8", "7", "6", "5", "4", "3", "2", "1"});

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(cb);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

更新为能够简单地反转选择索引...

所以,现在我们颠倒了顺序,所以我们颠倒了选择索引(项目8 不在位置1)。

我认为解决此问题的最简单方法是使用 Arrays.asList(floorsList).indexOf(...),它将返回 floorsList 数组中所选值的位置...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox08 {

    public static void main(String[] args) {
        new TestComboBox08();
    }

    private String[] floorsList = new String[]{"Select one", "8", "7", "6", "5", "4", "3", "2", "1"};

    public TestComboBox08() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JComboBox cb = new JComboBox(floorsList);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(cb);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                cb.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String value = (String)cb.getSelectedItem();
                        int index = Arrays.asList(floorsList).indexOf(value);
                        System.out.println("Item at " + index + " = " + floorsList[index]);
                    }
                });
            }
        });
    }

}

【讨论】:

  • 嗯,这很奇怪。当我选择“3”层时,我得到 6 个按钮,如果我选择“1”层,我得到 8 个按钮。显然,它们上的文字仍然相同。我认为它返回数组的索引。
  • 是的,你假设值的顺序,现在颠倒了,所以8不在1的位置,19的位置
【解决方案2】:

使用ListCellRenderer 来控制项目在组合框中的显示方式。

http://docs.oracle.com/javase/6/docs/api/javax/swing/ListCellRenderer.html

编辑:

实现ListCellRenderer 是一种更好的表达方式

【讨论】:

  • 我不在乎它在组合框中的外观。我对创建的按钮上显示的文本感兴趣。在阅读了我从中得到的 ListCellRenderer API 之后。我这样说是对的还是我完全误解了它?
  • 看来我误解了这个问题。尝试在组合框的 actionPerformed() 方法上添加按钮后修复布局和按钮属性。还可以尝试调用buttons.pack(),它将在面板上布局所有组件。
猜你喜欢
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2023-03-27
  • 2018-04-02
  • 2018-05-29
  • 1970-01-01
相关资源
最近更新 更多