Java 使用JComboBox设置绘制的绘图的颜色

Java 使用JComboBox设置绘制的绘图的颜色,java,swing,jcombobox,listeners,Java,Swing,Jcombobox,Listeners,我创建了一个模拟,它执行大量计算,然后将由x和y坐标组成的点存储到点阵列列表中 然后我有一个for循环,循环遍历每个点,并将该点绘制到GUI上。 以下是在模拟结束时执行的for循环和drawPoint方法: //Iterates through each point in Point Array List for(Point i: PointArray) { drawPoint(g, i, black); //Draw Point } //Draws point onto pa

我创建了一个模拟,它执行大量计算,然后将由x和y坐标组成的点存储到点阵列列表中

然后我有一个for循环,循环遍历每个点,并将该点绘制到GUI上。 以下是在模拟结束时执行的for循环和drawPoint方法:

//Iterates through each point in Point Array List
for(Point i: PointArray)
 {
      drawPoint(g, i, black); //Draw Point
 }

//Draws point onto panel
public void drawPoint(Graphics g, Point PointArray, Color color)
{
     Graphics2D g2d = (Graphics2D)g;
     g2d.setStroke(new BasicStroke(2f));
     g.setColor(color); //g2d.setColor(Color.black); 
     g2d.drawOval((int)PointArray.a, (int)PointArray.b, 2, 2);
} 
我想实现一个JComboBox,以便用户可以指定绘制时希望打印的颜色。我已经创建了不同的颜色对象用于此

在我的actionPerformed方法中,我还有处理JButton事件的代码,这些事件启动、停止和擦除模拟。 这就是我的actionPerformed方法:

 public void actionPerformed(ActionEvent e) 
 {
       Object source = e.getSource(); 

       JComboBox cb = (JComboBox)e.getSource();
       String colorName = (String)cb.getSelectedItem();

       //Get Graphics on Drawing Panel
       Graphics g = dPanel.getGraphics();

       //if JButton source == start, do something

       //if JButton source == stop, do something

       //If JButton source == erase, do something

       if(colorName == "Default")
       {
            g.setColor(black); 
       }

       if(colorName == "Red")
       {
            g.setColor(startColor); 
       }

       if(colorName == "Green")
       {
            g.setColor(forestGreen); 
       }
 }
我得到以下错误: 线程“AWT-EventQueue-0”java.lang.ClassCastException中的异常:javax.swing.JButton无法转换为javax.swing.JComboBox 在SimulationGUI.actionPerformed(SimulationGUI.java:332)

所以我的问题是,我想做的是可能的吗?如果是(因为我的实现不起作用),那么实现这一点的方法是什么

编辑:

以下是我为JComboBox创建的新操作侦听器:

    colorBox.addActionListener(new ActionListener()               
    {                                                         
        public void actionPerformed(ActionEvent e)               
        {                                                        
                 JComboBox cb = (JComboBox)e.getSource();
                 String colorName = (String)cb.getSelectedItem();

            Graphics g = dPanel.getGraphics();

            if(colorName.equals("Default"))
            {
                g.setColor(black);
            }

            if(colorName.equals("Red"))
            {
                g.setColor(startColor);
            }

            if(colorName.equals("Green"))
            {
                g.setColor(forestGreen);
            }

            if(colorName.equals("Blue"))
            {
                g.setColor(eraseColor);
            }                    
        }                                                        
    });
}
JComboBox cb = (JComboBox)e.getSource();

对组合框和按钮使用单独的ActionListener。现在,您的主要问题是,您正在这里进行铸造,希望看到JComboBox:

    colorBox.addActionListener(new ActionListener()               
    {                                                         
        public void actionPerformed(ActionEvent e)               
        {                                                        
                 JComboBox cb = (JComboBox)e.getSource();
                 String colorName = (String)cb.getSelectedItem();

            Graphics g = dPanel.getGraphics();

            if(colorName.equals("Default"))
            {
                g.setColor(black);
            }

            if(colorName.equals("Red"))
            {
                g.setColor(startColor);
            }

            if(colorName.equals("Green"))
            {
                g.setColor(forestGreen);
            }

            if(colorName.equals("Blue"))
            {
                g.setColor(eraseColor);
            }                    
        }                                                        
    });
}
JComboBox cb = (JComboBox)e.getSource();
但单击按钮时,此操作将失败,因为
JButton
不是
JComboBox
。如果在ActionListener中只处理JComboxes,那么执行此强制转换就可以了。

1)不要使用
getGraphics()
方法进行绘制。它可能看起来有效,但尝试最小化然后恢复框架,绘画就会消失。查看有关如何做到这一点的想法

2) 不要使用“==”来比较字符串值。使用:

colorName.equals("Red");
实际上,更好的解决方案是在组合框中存储一个自定义的“ColorItem”对象。此项将同时存储字符串显示文本和颜色对象。那么ActionListener中就不需要多个if语句了。下面是一个使用此方法的简单示例:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ComboBoxItem extends JFrame implements ActionListener
{
    public ComboBoxItem()
    {
        Vector model = new Vector();
        model.addElement( new Item(1, "car" ) );
        model.addElement( new Item(2, "plane" ) );
        model.addElement( new Item(4, "boat" ) );
        model.addElement( new Item(3, "train" ) );
        model.addElement( new Item(5, "boat" ) );

        JComboBox comboBox;

        //  Easiest approach is to just override toString() method
        //  of the Item class

        comboBox = new JComboBox( model );
        comboBox.setSelectedIndex(-1);

        comboBox.addActionListener( this );
//      comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add(comboBox, BorderLayout.NORTH );

        //  Most flexible approach is to create a custom render
        //  to diplay the Item data
        //  Note this approach will break keyboard navigation if you don't
        //  implement a default toString() method.

        comboBox = new JComboBox( model );
        comboBox.setSelectedIndex(-1);
        comboBox.setRenderer( new ItemRenderer() );
        comboBox.addActionListener( this );
        getContentPane().add(comboBox, BorderLayout.SOUTH );
    }

    public void actionPerformed(ActionEvent e)
    {
        JComboBox comboBox = (JComboBox)e.getSource();
        Item item = (Item)comboBox.getSelectedItem();
        System.out.println( item.getId() + " : " + item.getDescription() );
    }

    class ItemRenderer extends BasicComboBoxRenderer
    {
        public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

            if (value != null)
            {
                Item item = (Item)value;
                setText( item.getDescription().toUpperCase() );
            }
/*
            if (index == -1)
            {
                Item item = (Item)value;
                setText( "" + item.getId() );
            }
*/

            return this;
        }
    }

    class Item
    {
        private int id;
        private String description;

        public Item(int id, String description)
        {
            this.id = id;
            this.description = description;
        }

        public int getId()
        {
            return id;
        }

        public String getDescription()
        {
            return description;
        }

        public String toString()
        {
            return description;
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxItem();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
     }

}

如果这是
JButton
实例的
actionPerformed
方法,那么您为什么认为将其强制转换为
JComboBox
首先是有效的?您可能需要做的是将
JComboBox
实例设置为当前类的字段。当
JButton
上发生操作事件时,请像上面所做的那样,查询
JComboBox
实例,查找它当前所选的项。因此,我需要创建一个单独的actionPerformed方法来处理JComboBox事件?最好是ItemListener+1@kachilous是的,有点。创建单独的ActionListener将强制您使用单独的actionPerformed方法。@jzd:好的,谢谢。我已经更新了组合框的操作侦听器(请参阅原始帖子),但是由于某些原因,颜色的选择没有保存到g中,我是否必须将g传递回drawPoint()方法