简体   繁体   English

如何使用 JComboBox 更改背景颜色

[英]How to change background color using JComboBox

So, basically, the main idea for this project is that I wanted to change the background color by using the jcombobox method.所以,基本上,这个项目的主要思想是我想通过使用jcombobox方法来改变背景颜色。 and the background will change with the option chosen when the button(proceed) is clicked.并且背景将随着单击按钮(继续)时选择的选项而改变。 The background color chosen will then be implemented to the next page when the button is clicked.当单击按钮时,选择的背景颜色将被实施到下一页。 The background that im talking about is the background for all the JPanel(including the other page's JPanel).我所说的背景是所有JPanel(包括其他页面的JPanel)的背景。 If (getsource() == f2.btenter2), it will go to f2(2nd file) btenter2(button)'s when clicked.如果 (getsource() == f2.btenter2),单击时它将 go 到 f2(2nd file) btenter2(button) 的。

public class MainPage extends JFrame implements ActionListener {

    JLabel lbTitle, lbWelcome, lbSelect;
    JComboBox cbColor;
    public Color color[] = {RED, GREEN, BLUE, YELLOW, GRAY};
    public String clr[] ={"RED","GREEN","BLUE","YELLOW","GRAY"};
    public int index;
    JButton btProceed;

    public static void main(String[] args) {
        MainPage f1 = new MainPage();
        f1.setSize(800, 500);
        f1.setTitle("Java Assignment");
        f1.setVisible(true);
        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public MainPage() {
        lbTitle = new JLabel("Rock-Paper-Scissors-Lizard-Spock");
        lbWelcome = new JLabel("Welcome!");
        lbSelect = new JLabel("Please select the background color before you proceed:");

        lbWelcome.setFont(new Font("Courier", Font.PLAIN, 18));lbSelect.setFont(new Font("Courier", Font.PLAIN, 15)); cbColor = new JComboBox(color);btProceed = new JButton("Proceed");

        //1st panel on the north side to set the title
        JPanel p1 = new JPanel();
        p1.add(lbTitle);
        p1.setBackground(new Color(255, 106, 0));

        //2nd panel on the center position

        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout(14, 1));JPanel a1 = new JPanel();
        JPanel a2 = new JPanel();
        JPanel a3 = new JPanel();
        JPanel e1 = new JPanel();
        a1.add(lbWelcome);
        a2.add(lbSelect);
        a3.add(cbColor);
        p2.add(e1);
        p2.add(a1);
        p2.add(a2);
        p2.add(a3);

        JPanel p3 = new JPanel();
        p3.add(btProceed);

        setLayout(new BorderLayout());
        add(p1, BorderLayout.NORTH);
        add(p2, BorderLayout.CENTER);
        add(p3, BorderLayout.SOUTH);

        btProceed.addActionListener(this);
        cbColor.addActionListener(this);
        color().addActionListener(this);
    }

      @Override
    public void actionPerformed(ActionEvent e) {
        index = cbColor.getSelectedIndex();  //to get the index

        if (e.getSource()==cbColor) {
            index = cbColor.getSelectedIndex();
            p2.setBackground(color[index]);
            a1.setBackground(color[index]);
            a2.setBackground(color[index]);
            a3.setBackground(color[index]);
            e1.setBackground(color[index]);
            e1.setBackground(color[index]);
            p3.setBackground(color[index]);

        }

        Team f2 = new Team();
        GamePage f3 = new GamePage();
        GamePage2 f4 = new GamePage2();
        Result f5 = new Result();

        if (e.getSource()==btProceed) {
            this.setVisible(false);
            f2.setVisible(true);
            f2.setSize(800, 500);
            f2.p2.setBackground(color[index]);
            f2.p3.setBackground(color[index]);
            f2.p4.setBackground(color[index]);
            // btenter2 is located in the second file under the same package
if (e.getSource()==f2.btenter2){
            this.setVisible(false);
            f3.setVisible(true);
            f3.setSize(800,500);
            f3.p2.setBackground(color[index]);
            f3.p3.setBackground(color[index]);
            f3.p4.setBackground(color[index]);
            f3.p5.setBackground(color[index]);}
if (e.getSource()==f3.btNext){this.setVisible(false);
            f4.setVisible(true);
            f4.setSize(800,500);
            f4.p2.setBackground(color[index]);
            f4.p3.setBackground(color[index]);
            f4.p4.setBackground(color[index]);
            f4.p5.setBackground(color[index]); }
        if (e.getSource() == f4.btResult)
        {
            this.setVisible(false);
            f5.setVisible(true);
            f5.setSize(800,500);
            f5.p2.setBackground(color[index]);
            f5.p3.setBackground(color[index]);
            f5.p4.setBackground(color[index]);
            f5.p5.setBackground(color[index]);}}

The background assigned by the renderer is overriden by the selection background color of the JList that is used in the popup for the combo box.渲染器分配的背景被组合框的弹出窗口中使用的 JList 的选择背景颜色覆盖。

JComboBox cbColor = new JComboBox(...);
Object child = cbColor.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setSelectionBackground(Color.RED);

Credits to this answer归功于此答案

Introduction介绍

I started working on this before I saw the OP's latest edit.在我看到 OP 的最新编辑之前,我开始研究这个。

Here's the GUI I came up with.这是我想出的GUI。

浅灰色图形用户界面

Here's the GUI when you pick red.这是您选择红色时的 GUI。

红色图形用户界面

Here's the GUI when you pick yellow.这是您选择黄色时的 GUI。

黄色图形用户界面

The red GUI uses white text for better contrast.红色 GUI 使用白色文本以获得更好的对比度。 Some background colors work better with black text.一些背景 colors 更适合黑色文本。

I didn't create an ActionListener for the button.我没有为按钮创建ActionListener I wanted to demonstrate two things.我想展示两件事。

  1. A JComboBox can hold any class, not just the String class. JComboBox可以包含任何 class,而不仅仅是String class。

  2. An ActionListener that changes the background and foreground color of a JPanel .更改JPanel的背景和前景颜色的ActionListener

Explanation解释

When creating a Swing GUI, or almost any Java application, I use the model / view / controller pattern.在创建 Swing GUI 或几乎任何 Java 应用程序时,我使用model / 视图 / Z5904C1ABAZ3F2F6D601E4C10ABAZ3F2F603E模式。 This pattern allows me to focus on one part of the application at a time and helps me separate my concerns.这种模式允许我一次专注于应用程序的一个部分,并帮助我分离我的关注点。

So, the first thing I did was create a ColorPair class.所以,我做的第一件事是创建一个ColorPair class。 The ColorPair class holds a background color, a foreground color, and a String name of the background color. ColorPair class 包含一个背景色、一个前景色和一个背景色的字符串名称。 When passing class instances to a JComboBox , the class toString method is used to display the combo box options.将 class 实例传递给JComboBox时,class toString方法用于显示组合框选项。

Next, I created a Pallete class.接下来,我创建了一个Pallete class。 The Pallete class holds a List of ColorPair instances. Pallete class 包含一个ColorPair实例列表。

Once I created the model, I started on the view.创建 model 后,我开始查看视图。 I reorganized the OP's view code so it was easier to read.我重新组织了 OP 的视图代码,使其更易于阅读。 Generally, I keep all the methods for each Swing component together, and create the Swing components in the order they appear on the JPanel .通常,我将每个 Swing 组件的所有方法保存在一起,并按照它们在JPanel上出现的顺序创建 Swing 组件。

I separated the JFrame and JPanel creation into separate methods.我将JFrameJPanel创建分成单独的方法。

After I was satisfied with the view, I wrote the ActionListener for the JComboBox .在对视图感到满意后,我为JComboBox编写了ActionListener I didn't need to pass all the components to the ActionListener class since I could get the children components of the JPanel .我不需要将所有组件传递给ActionListener class 因为我可以获得JPanel的子组件。

The propagateColors method of the ActionListener is recursive. ActionListenerpropagateColors方法是递归的。 This is one of those rare instances where a recursive method makes sense in the real world since you can have JPanels as children of a JPanel .这是递归方法在现实世界中有意义的少数情况之一,因为您可以将JPanels作为JPanel的子级。

Here's the complete runnable code.这是完整的可运行代码。 I hope it's helpful.我希望它会有所帮助。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

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

public class BackgroundColorGUI implements Runnable {
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new BackgroundColorGUI());
    }
    
    private ColorPair colorPair;
    
    private JPanel mainPanel;
    private JPanel buttonPanel;
    
    private Pallete pallete;
    
    public BackgroundColorGUI() {
        this.pallete = new Pallete();
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Java Assignment");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createTitlePanel(), BorderLayout.BEFORE_FIRST_LINE);
        this.mainPanel = createMainPanel();
        frame.add(mainPanel, BorderLayout.CENTER);
        this.buttonPanel = createButtonPanel();
        frame.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }    
     
    private JPanel createTitlePanel() {
        //1st panel on the north side to set the title
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JLabel lbTitle = new JLabel("Rock-Paper-Scissors-Lizard-Spock");
        lbTitle.setFont(panel.getFont().deriveFont(Font.BOLD, 24f));
        panel.add(lbTitle);
        panel.setBackground(new Color(255, 106, 0));
        return panel;
    }
       
    private JPanel createMainPanel() {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        panel.setLayout(new GridLayout(0, 1, 5, 5));
        
        JPanel e1 = new JPanel();
        JLabel dummy = new JLabel(" ");
        e1.add(dummy);
        panel.add(e1);

        JPanel a1 = new JPanel();
        JLabel lbWelcome = new JLabel("Welcome!");
        lbWelcome.setFont(new Font("Courier", Font.PLAIN, 18));
        a1.add(lbWelcome);
        panel.add(a1);
        
        JPanel a2 = new JPanel();
        JLabel lbSelect = new JLabel("Please select the background "
                + "color before you proceed:");
        lbSelect.setFont(new Font("Courier", Font.PLAIN, 15));
        a2.add(lbSelect);
        panel.add(a2);
 
        JPanel a3 = new JPanel();
        JComboBox<ColorPair> cbColor = new JComboBox<ColorPair>();
        List<ColorPair> colors = pallete.getColors();
        for (ColorPair colorPair : colors) {
            cbColor.addItem(colorPair);
        }
        cbColor.addActionListener(new ColorListener(this));
        a3.add(cbColor);
        panel.add(a3);
        
        return panel;
    }
        
    private JPanel createButtonPanel() {
         JPanel panel = new JPanel();
         JButton btProceed = new JButton("Proceed");
         panel.add(btProceed);
         
         return panel;
    }
    
    public JPanel getMainPanel() {
        return mainPanel;
    }

    public JPanel getButtonPanel() {
        return buttonPanel;
    }

    public class ColorListener implements ActionListener {
        
        private BackgroundColorGUI frame;

        public ColorListener(BackgroundColorGUI frame) {
            this.frame = frame;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
            colorPair = (ColorPair) comboBox.getSelectedItem();
            propagateColors(frame.getMainPanel(), colorPair);
            propagateColors(frame.getButtonPanel(), colorPair);
        }

        private void propagateColors(JPanel panel, ColorPair colorPair) {
            panel.setBackground(colorPair.getBackgroundColor());
            panel.setForeground(colorPair.getForegroundColor());
            Component[] components = panel.getComponents();
            for (Component component : components) {
                if (component instanceof JPanel) {
                    JPanel childPanel = (JPanel) component;
                    propagateColors(childPanel, colorPair);
                }
                component.setBackground(colorPair.getBackgroundColor());
                component.setForeground(colorPair.getForegroundColor());
            }
        }
        
    }
    
    public class Pallete {
        
        private final List<ColorPair> colors;
        
        public Pallete() {
            this.colors = generatePalleteFactory();
        }
        
        private List<ColorPair> generatePalleteFactory() {
            List<ColorPair> colors = new ArrayList<>();
            colors.add(new ColorPair("Light Grey", 
                    new Color(238, 239, 238), Color.BLACK));
            colors.add(new ColorPair("Red", Color.RED, Color.WHITE));
            colors.add(new ColorPair("Green", Color.GREEN, Color.BLACK));
            colors.add(new ColorPair("Blue", Color.BLUE, Color.WHITE));
            colors.add(new ColorPair("Yellow", Color.YELLOW, Color.BLACK));
            colors.add(new ColorPair("Grey", 
                    new Color(153, 153, 153), Color.WHITE));
            
            return colors;
        }

        public List<ColorPair> getColors() {
            return colors;
        }
        
    }
    
    public class ColorPair {
        
        private final Color backgroundColor;
        private final Color foregroundColor;
        
        private final String backgroundColorName;
        
        public ColorPair(String backgroundColorName, 
                Color backgroundColor, Color foregroundColor) {
            this.backgroundColorName = backgroundColorName;
            this.backgroundColor = backgroundColor;
            this.foregroundColor = foregroundColor;
        }

        public Color getBackgroundColor() {
            return backgroundColor;
        }

        public Color getForegroundColor() {
            return foregroundColor;
        }

        public String getBackgroundColorName() {
            return backgroundColorName;
        }
        
        @Override
        public String toString() {
            return getBackgroundColorName();
        }

    }
       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM