2011-08-22 5 views
0

여러 계산을 수행 한 후 x 및 y 좌표로 구성된 점을 점 배열 목록에 저장하는 시뮬레이션을 만들었습니다.JComboBox를 사용하여 그려지는 그림의 색을 설정합니다.

그렇다면 for 루프를 사용하여 각 점을 반복하고 그 점을 GUI에 그립니다. 다음은 시뮬레이션과 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 이벤트를 처리하는 코드가 있습니다. 나는 다음과 같은 오류가 무엇입니까

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); 
     } 
} 

: 이 내의 actionPerformed 방법에 대한이 무엇 스레드에서 예외 "AWT-EventQueue의-0"java.lang.ClassCastException가 : javax.swing.JButton는 캐스트 할 수없는 (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); 
      }      
     }               
    }); 
} 
+1

, 왜 당신은'JComboBox'에 캐스팅하는 것은 처음부터 유효 할 것이라고 생각하십니까? 'JComboBox' 인스턴스를 현재의 클래스의 필드로합니다. 그리고'JButton'에서 액션 이벤트가 발생하면 위와 마찬가지로 JComboBox 인스턴스에 대해 현재 선택된 아이템을 쿼리합니다. – mre

답변

1

를 사용하여 별도의 ActionListener를가.

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

을하지만 JButtonJComboBox하지 않기 때문에 버튼을 클릭 할 때이 오류가 발생합니다 : 지금 당신의 가장 큰 문제는 당신이 JComboBox에 기대 여기에 캐스팅된다. JComboBoxes만을 다루는 ActionListener에 있으면이 캐스트를 수행하는 것이 좋습니다.

+0

그래서 JComboBox 이벤트를 처리하기 위해 별도의 actionPerformed 메서드를 만들어야합니까? – kachilous

+1

더 좋을 것 ItemListener +1 – mKorbel

+0

@kachilous, 예. 일종의. 별도의 ActionListener를 작성하면 별도의 actionPerformed 메소드가 있어야합니다. – jzd

1

1) 도장에는 getGraphics() 방법을 사용하지 마십시오. 작동하는 것처럼 보일 수 있지만 프레임을 최소화 한 다음 복원하면 그림이 사라집니다. 이 작업을 수행하는 방법에 대한 아이디어는 Custom Painting Approaches을 확인하십시오.

2) "=="을 사용하여 문자열 값을 비교하지 마십시오. 실제로는 더 좋은 해결책은 콤보 상자에 사용자 정의`ColorItem '객체를 저장하는 것입니다. 이 항목에는 String 표시 텍스트와 Color 객체가 저장됩니다. 그런 다음 ActionListener에 여러 if 문이 필요하지 않습니다. 다음은이 방법을 사용하는 간단한 예입니다 : 즉`JButton` 인스턴스의`actionPerformed` 방법의 경우

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); 
    } 

} 
+0

감사합니다. 주제 – kachilous

관련 문제