我正在尝试映射一些服务器主机之间的数据流。这个想法是,数据在网络中的多播会话之间流动,我有一个数据来自和到达的表。我想要生成使用箭头来显示什么东西在哪里的图表。
我已经使用图形库绘制了一些形状(用于主机的矩形和用于多播会话的椭圆),并将形状的位置/比例数据存储在对象中,以便我可以计算箭头应该锁定的位置。我也在他们之间做了箭。箭头是使用带有paintComponenet方法的自定义函数添加的,有点像addArrow(startShape,endShape),它将找到形状中最近的两个锚点,并在它们之间绘制箭头。
My work so far, randomly using the addArrow function
然而,这本身是非常没有生命力的。我还想给箭头添加一个悬停效果,这样当鼠标指针触摸到它时,它就会变厚并显示一些自定义的文本。使用paintComponent函数似乎不可行,因为我不能将事件添加到它绘制的形状中。
我认为可以绘制箭头,然后将它们放入JLabel组件中,并在该组件上定义鼠标事件。我也可以创建一个新的“箭头摆动组件”,但我认为这超出了我的能力范围。
你们有没有关于如何进行的建议?
发布于 2018-09-22 04:22:29
我认为可以绘制箭头,然后将它们放入JLabel组件中,并在该组件上定义鼠标事件。
是。您只需创建一个图标来表示箭头,然后将该图标添加到标签中。
有几种方法可以创建图标。
您可以实际实现Icon接口:
import java.awt.*;
import javax.swing.*;
public class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
JPanel panel = new JPanel( new GridLayout(2, 2) );
for (int i = 0; i < 4; i++)
{
Icon icon = new ColorIcon(Color.RED, 50, 50);
JLabel label = new JLabel( icon );
label.setText("" + i);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
panel.add(label);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}
或者,您可以在BufferedImage上绘制,然后使用该图像在ImageIcon中创建:
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.setColor(...);
g.fillOval(...);
ImageIcon icon = new ImageIcon( bi );
当然,这样做的问题之一是图标始终是矩形的,所以即使在箭头之外一点的地方也会生成事件。
您可以尝试使用Playing With Icons中的Shape Component
https://stackoverflow.com/questions/52448549
复制相似问题