简体   繁体   English

从右到左(向后)JProgressBar

[英]Right to left (backwards) JProgressBar

My app needs to display a graphical representation of a value ranging from -1 to 1. Negative values should be in one color, with positive values in another. 我的应用程序需要显示值为-1到1的图形表示。负值应为一种颜色,正值为另一种颜色。 Zero is in the center and shows nothing. 零位于中心,不显示任何内容。 (If it helps, the particular use here is to display the relative weight of buy and sell orders in a financial application.) (如果有帮助,这里的特殊用途是显示金融应用程序中买卖订单的相对权重。)

I would ideally like to use a pair of JProgressBars for this, however the Swing control starts (at its minimum) at the left. 理想情况下,我想为此使用一对JProgressBars,但Swing控件在左侧开始(至少)。 The standard control only supports two orientations, left-right or bottom-top. 标准控件仅支持两个方向,左右或底部。 Passing in negative values doesn't help. 传递负值并没有帮助。 My question is, what is the quickest way to achieve this effect? 我的问题是,实现这种效果的最快方法是什么?

Subclassing JProgressBar would involve re-implementing it almost entirely. 子类化JProgressBar将涉及几乎完全重新实现它。 Using a JFreeChart bar chart seems like a great deal of code (and effort) for a relatively trivial task. 使用JFreeChart条形图似乎是一项相对简单的任务的大量代码(和努力)。 I could perhaps make a small, square-celled JTable and fill it in, but again that's a lot of code. 我也许可以制作一个小的,方形的JTable并填充它,但这又是很多代码。 What would you suggest? 你会建议什么?

Umm, maybe this won't work at all, but how about making a sub-class of JProgressBar and overriding paintComponent() to something like this: 嗯,也许这根本不起作用,但如何制作JProgressBar的子类并将paintComponent()重写为这样的东西:

@Override
protected void paintComponent(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
  g2d.rotate(Math.PI);
  super.paintComponent(g2d);
}

I'd test it if I was more lucid and awake. 如果我更清醒和清醒,我会测试它。

Edit: While rotating it might work too, I found it easier to scale it and then translate, as follows: 编辑:旋转它也可能有效,我发现它更容易扩展然后翻译,如下所示:

@Override
protected void paintComponent(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
  g2d.scale(-1, 1); //Flips over y-axis
  g2d.translate(-getWidth(), 0); //Moves back to old position.
  super.paintComponent(g2d);
}

Using JFreeChart or subclassing JProgressBar seems like overkill, but overriding paintTrack() in BasicSliderUI may be effective. 使用JFreeChart或子类化JProgressBar似乎paintTrack()矫枉过正,但是在BasicSliderUI覆盖paintTrack()可能会有效。 Here's an example . 这是一个例子

I had a look at JFreeChart the other day and for what you want to do it looks like complete overkill. 前几天我看了一下JFreeChart,你想做什么看起来像是完全矫枉过正。

As this seems as if it would be fairly easy to draw procedurally, I'd just make a class extending JComponent, override the paint method to draw a rect in it, and add it as a custom widget. 由于这似乎很容易在程序上绘制,我只是创建一个扩展JComponent的类,重写paint方法以在其中绘制rect,并将其添加为自定义小部件。

交换背景和前景色,回归看起来像左边的进度。

以下代码完成工作:

setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM