我试图将Ellipse2D对象与JTable上的单元格相关联。具体来说,如果用户点击一个Ellipse2D,那么它将突出显示JTable上的一个单元格并接受输入。我需要以允许用户将字符串与每个Ellipse相关联的方式执行此操作。
我正在尝试做什么,如果可以,我该怎么办呢?
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 );
}
}
答案 0 :(得分:1)
好吧,也许你首先创建一个HashMap
,其中键是椭圆,值是Point,其中Point表示表中椭圆的行/列。
//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;
}
}
}