【问题标题】:How to show combo box elements by clicking a button?如何通过单击按钮显示组合框元素?
【发布时间】:2021-10-18 16:23:07
【问题描述】:

我正在使用 Java Swing。我在组合框上保留了一个按钮,因为对我来说,着色按钮比着色组合框容易得多,我希望当单击按钮时,所有组合框元素都应该显示。我在分层窗格中保留了组合框和按钮,布局是绝对布局。

如果不可能,我们如何更改组合框的背景颜色?

【问题讨论】:

标签: java swing jbutton jcombobox


【解决方案1】:

由于您没有提供最小的可运行示例,因此我继续创建了这个 GUI。

这是我左键单击 JButton 后的相同 GUI。

如您所见,JComboBox 现在有选择。

Oracle 有一个很棒的教程Creating a GUI With Swing,它将教您如何创建 Swing GUI。跳过 Netbeans 部分。

这是完整的可运行代码。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ComboBoxButton implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ComboBoxButton());
    }
    
    private JComboBox<String> comboBox;
    
    @Override
    public void run() {
        JFrame frame = new JFrame("ComboBox Button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createMainPanel(), BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JButton button = new JButton("Click Me");
        button.addActionListener(new ButtonListener());
        panel.add(button, BorderLayout.BEFORE_FIRST_LINE);
        
        comboBox = new JComboBox<>();
        panel.add(comboBox, BorderLayout.CENTER);
        
        return panel;
    }
    
    public class ButtonListener implements ActionListener {
        
        private boolean firstTimeSwitch = true;

        @Override
        public void actionPerformed(ActionEvent event) {
            if (firstTimeSwitch) {
                String[] selection = { "alpha", "beta", "gamma", "zeta" };
                for (int index = 0; index < selection.length; index++) {
                    comboBox.addItem(selection[index]);
                }
                
                firstTimeSwitch = false;
            }
        }
        
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2019-10-05
    • 2021-03-03
    • 2012-11-13
    • 1970-01-01
    • 2019-08-26
    相关资源
    最近更新 更多