gpt4 book ai didi

java - 将对象与 JTable 上的单元格关联

转载 作者:行者123 更新时间:2023-11-30 07:48:37 25 4
gpt4 key购买 nike

我正在尝试将 Ellipse2D 对象与 JTable 上的单元格关联。具体来说,如果用户单击一个 Ellipse2D,那么它将突出显示 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 );
}
}

最佳答案

好吧,也许您首先创建一个 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);

the user clicks on one Ellipse2D then it would highlight a cell on the JTable and accept input.

那么您需要向面板添加一个 MouseListener 并处理 mousePressed() 事件。该代码需要遍历列表才能找到包含该点的椭圆。然后您可以开始在单元格上进行编辑。也许是这样的:

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

关于java - 将对象与 JTable 上的单元格关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33577773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com