java - 使用 Java swing 制作交互式组件
问题描述
我正在尝试在某些服务器主机之间映射数据流。这个想法是数据在网络中的多播会话之间流动,并且我有一个数据来自和去向的表。我想生成图表,显示使用箭头的去向。
我使用图形库绘制了一些形状(用于主机的矩形,用于多播会话的椭圆)并将形状的位置/比例数据存储在对象中,以便我可以计算箭头应锁定的位置。我也在他们之间做了箭头。使用带有 paintComponenet 方法的自定义函数添加箭头,有点像addArrow(startShape, endShape),它将找到形状的两个最近的锚点并在它们之间绘制箭头。
然而,这本身就很没有生命力。我还想为箭头添加悬停效果,以便当鼠标指针触摸它时它会变粗并显示一些自定义文本。使用paintComponent 函数这似乎不可行,因为我无法将事件添加到它绘制的形状中。
我认为可以绘制箭头,然后将它们放入 JLabel 组件并在其上定义鼠标事件。我也许还可以创建一个新的“箭头摆动组件”,但我认为这超出了我的水平。
各位大佬有什么方法可以推荐吗?
解决方案
我认为可以绘制箭头,然后将它们放入 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 IconsShape Component
中的
推荐阅读
- bash - 如何将 let 命令输出分配给变量?
- ruby-on-rails - 迭代期间的 Ruby/Rails 6 求和
- github - 删除存储库并重新创建后,Github Pages 404 错误
- android - 如何在我的应用程序中播放来自服务器的 AudioRecord 缓冲区
- c# - 如何在outlook中获取所有打开的inspector的title?
- javascript - div 块正在监听内部和外部事件
- c++ - QComboBox 末尾的白线。什么原因?
- r - 通过 R 中的 mutate 为多列操作命名
- flutter - 有没有办法在不添加 else 语句的情况下有条件地呈现小部件?
- ios - NSMutableDictionary 中的 setValuesForKeysWithDictionary 崩溃