目前我编写了一些代码,用户在点击Ellipse2D时选择JTable中的单元格。如果用户点击JTable中的相关单元格,我也想填充Ellipse2D。使用下面的代码,我该怎么做?
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class SelfContainedExample extends JPanel implements MouseListener {
private Map<Ellipse2D.Double, Point> shapesMap = new HashMap<>();
private Ellipse2D.Double[] ellipses = new Ellipse2D.Double[] {
new Ellipse2D.Double(50, 100, 30, 30),
new Ellipse2D.Double(175, 100, 30, 30),
new Ellipse2D.Double(300, 100, 30, 30),
new Ellipse2D.Double(50, 160, 30, 30),
new Ellipse2D.Double(175, 160, 30, 30),
new Ellipse2D.Double(300, 160, 30, 30)};
static Object[][] data = {{"1_1", "1_2", "1_3"},
{"2_1", "2_2", "2_3"},
{"3_1", "2_2", "2_3"},
{"4_1", "2_2", "2_3"},
{"5_1", "2_2", "2_3"},
{"6_1", "2_2", "2_3"}};
static Object[] columnNames = {"1", "2", "3"};
static JTable jtable = new JTable(data, columnNames);
public static void main(String[] args)
{
EventQueue.invokeLater(() -> createAndShowGUI());
}
public SelfContainedExample() {
int row = 0;
int column = 0;
for (Ellipse2D.Double ellipse : ellipses) {
shapesMap.put(ellipse, new Point(row, column));
row++;
}
addMouseListener(this);
}
@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);
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.GRAY);
for (Ellipse2D ellipse : ellipses) {
g2d.draw(ellipse);
}
g2d.dispose();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Example");
JPanel panel = new JPanel();
JPanel tablePanel = new JPanel();
JScrollPane jScrollPane = new JScrollPane(jtable);
jScrollPane.setPreferredSize(new Dimension(385, 119));
tablePanel.add(jScrollPane);
tablePanel.setSize(200, 200);
panel.setLayout(new BorderLayout());
panel.add(new SelfContainedExample(), BorderLayout.CENTER);
panel.add(tablePanel, 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);
}
@Override
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
for (Ellipse2D.Double ellipse : ellipses) {
if (ellipse.contains(e.getPoint())) {
jtable.requestFocusInWindow();
Point p = shapesMap.get(ellipse);
jtable.editCellAt(p.x, p.y);
}
if (jtable.contains(e.getPoint())) {
}
}
}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
答案 0 :(得分:2)
建议: