目前我已經編寫了一些代碼,當用戶單擊一個Ellipse2D時,它將在JTable中選擇一個單元格。如果用戶單擊JTable中的關聯單元格,我也想填充Ellipse2D。使用下面的代碼,我將如何做到這一點?將Ellipse2D與JTable單元相關聯
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) {}
}
出於好奇,你在這個網站上問過這個問題多少次? –
@hovercraftfullofeels這是第一個,我問了幾個其他相關的。我仍在學習。 – feltersnach
我的問題是你的代碼沒有顯示你的解決方案。將來,你會想要向我們展示這一點,否則你可能無法充分發揮你的大腦功能,我們也不會知道你會做錯什麼。 –