2015-11-07 69 views
1

我想將Ellipse2D對象與JTable上的單元格相關聯。特別是如果用戶點擊一個Ellipse2D,那麼它會突出顯示JTable上的一個單元並接受輸入。我需要以允許用戶將字符串與每個橢圓相關聯的方式來執行此操作。將對象與JTable上的單元格相關聯

正在嘗試做什麼,如果可以,我該怎麼做?

import java.awt.*; 
import java.awt.geom.*; 
import java.util.*; 
import java.util.List; 
import javax.swing.*; 

public class SelfContainedExample extends JPanel { 
    private List<Shape> shapes = new ArrayList<>(); 

    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(() -> createAndShowGUI()); 
    } 

    public SelfContainedExample() 
    { 
     //Circle of Radios 
     shapes.add(new Ellipse2D.Double(250, 100, 20, 20)); 
     shapes.add(new Ellipse2D.Double(160, 100, 20, 20)); 
     shapes.add(new Ellipse2D.Double(70, 100, 20, 20)); 
     shapes.add(new Ellipse2D.Double(70, 160, 20, 20)); 
     shapes.add(new Ellipse2D.Double(160, 160, 20, 20)); 
     shapes.add(new Ellipse2D.Double(250, 160, 20, 20)); 
    } 

    @Override 
    protected void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 

     Graphics2D g2d = (Graphics2D)g.create(); 
     g2d.setColor(Color.BLACK); 

     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
       RenderingHints.VALUE_ANTIALIAS_ON); 

     shapes.forEach(g2d::fill); 

     g2d.dispose(); 
    } 

    private static void createAndShowGUI() 
    { 
     JFrame frame = new JFrame("Example"); 
     JPanel panel = new JPanel(); 

     Object[][] data = {{"1_1", "1_2", "1_3"}, 
          {"2_1", "2_2", "2_3"}}; 

     Object[] columnNames = {"1", "2", "3"}; 
     JTable jtable = new JTable(data, columnNames); 

     panel.setLayout(new BorderLayout()); 
     panel.add(new SelfContainedExample(), BorderLayout.CENTER); 
     panel.add(jtable, BorderLayout.SOUTH); 
     panel.setOpaque(true); 
     panel.setVisible(true); 

     frame.add(panel); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(400,400); 
     frame.setLocationByPlatform(false); 
     frame.setLocationRelativeTo(null); 
     frame.setContentPane(panel); 
     frame.setVisible(true); 
    } 
} 

回答

1

嗯,也許你通過創建一個HashMap其中關鍵是橢圓和值是一個點,點在哪裏將代表該表中的橢圓形的行/列開始。

//shapes.add(new Ellipse2D.Double(250, 100, 20, 20)); 
Ellipse2D.Double ellipse = new Ellipse2D.Double(...); 
shapes.add(ellipse); 
shapesMap.put(ellipse, new Point(0, 0); 

一個在Ellipse2D的用戶點擊那就突出顯示JTable的細胞和接受輸入。

所以你需要添加一個MouseListener到你的面板並處理mousePressed()事件。該代碼需要迭代List來查找包含該點的橢圓。然後你可以開始編輯單元格。可能是這樣的:

public void mousePressed(MouseEvent e) 
{ 
    for (Ellipse2D.Double ellipse: shapes) 
    { 
     if (ellipse.contains(e.getPoint()) 
     { 
      table.requestFocusInWindow(); 
      Point p = shapesMap.get(ellipse); 
      table.editCellAt(p.x, p.y); 
      break; 
     } 
    } 
}