我目前在程序中使用启动画面,然后在其上显示信息,例如文件的下载百分比。我想要像 JProgressBar
字符串一样,我的意思是,当蓝色进度经过字符串上方时,字符串的颜色会发生变化。
这是我当前正在使用的代码。
private static void splashProgress(float percent, String str)
{
if (mySplash != null && mySplash.isVisible())
{ // important to check here so no other methods need to know if there
// really is a Splash being displayed
float width = (186*percent)/100;
splashProgress = new Rectangle2D.Double(4., 211., width, 24.);
splashTextArea = new Rectangle2D.Double(width+4., 211., 186.-width, 24.);
splashGraphics.setColor(new Color(255,177,100,255));
splashGraphics.fill(splashProgress);
splashGraphics.setColor(new Color(175,25,25,255));
splashGraphics.fill(splashTextArea);
splashGraphics.setColor(new Color(25,25,25,255));
splashGraphics.drawString(str, 4,226);
// make sure it's displayed
mySplash.update();
}
}
进度条如下所示:
如您所见,字符串的颜色与进度条的颜色相同,我希望将隐藏部分的颜色设置为不同的颜色。
感谢您的帮助,并对我的英语不好感到抱歉,这不是我的母语。
最佳答案
您使用Graphics2D#setXORMode
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGraphics {
public static void main(String[] args) {
new TestGraphics();
}
public TestGraphics() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(new Color(175,25,25,255));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(255,177,100,255));
g2d.fillRect(0, 0, getWidth() / 2, getHeight());
g2d.setXORMode(new Color(175,25,25,255));
FontMetrics fm = g2d.getFontMetrics();
String text = "I'm some exciting text";
int x = (getWidth() - fm.stringWidth(text)) / 2;
int y = ((getHeight()- fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(text, x, y);
g2d.dispose();
}
}
}
关于java - 如何根据百分比使用拉绳方法更改范围像素的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990266/