使用JComboBox来绘制绘图的setColor

时间:2011-08-22 18:53:10

标签: 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 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);
            }                    
        }                                                        
    });
}

2 个答案:

答案 0 :(得分:1)

为ComboBox和按钮使用单独的ActionListeners。现在你的主要问题是你在这里期待一个JComboBox:

JComboBox cb = (JComboBox)e.getSource();

但点击该按钮会失败,因为JButton不是JComboBox。如果它只在一个只处理JComboBoxes的ActionListener中,那么执行此转换会很好。

答案 1 :(得分:1)

1)不要使用getGraphics()方法进行绘画。它似乎可行,但尝试最小化然后恢复框架,画面将消失。请查看Custom Painting Approaches,了解有关如何执行此操作的建议。

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

colorName.equals("Red");

实际上,更好的解决方案是在组合框中存储自定义`ColorItem'对象。此项将存储String显示文本和Color对象。然后,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 );
     }

}