How to customize a JProgressBar? - java

I am making a launcher and I want to have a customized ProgressBar.
I have done some research and it's possible with JavaFX(Never did something with it) and it's possible with replacing the UI.
I am looking for a bar with rounded edges and a rounded fill.
Something like this:
package gui;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private final JPanel contentPane;
final JFrame frame = new JFrame();
int pX,pY;
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
final Gui frame = new Gui();
frame.setVisible(true);
} catch (final Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gui() {
this.setTitle("Exile Launcher");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(0, 0, 1000, 563);
this.contentPane = new JPanel();
this.contentPane.setBorder(null);
this.setContentPane(this.contentPane);
this.contentPane.setLayout(null);
this.setUndecorated(true);
this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width/2-this.getSize().width/2, Toolkit.getDefaultToolkit().getScreenSize().height/2-this.getSize().height/2);
int X = 24;
int Y = 40;
final JButton HomeButton = new JButton();
HomeButton.setFocusPainted(false);
HomeButton.setBorder(null);
HomeButton.setContentAreaFilled(false);
HomeButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/0.png")));
HomeButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/0_h.png")));
HomeButton.setBounds(new Rectangle(X, Y, 50, 50));
this.contentPane.add(HomeButton);
HomeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
try {
Desktop.getDesktop().browse(new URL("http://www.google.nl").toURI());
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
});
Y += 60;
final JButton ForumButton = new JButton();
ForumButton.setFocusPainted(false);
ForumButton.setBorder(null);
ForumButton.setContentAreaFilled(false);
ForumButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/1.png")));
ForumButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/1_h.png")));
ForumButton.setBounds(new Rectangle(X, Y, 50, 50));
this.contentPane.add(ForumButton);
Y += 60;
final JButton VoteButton = new JButton();
VoteButton.setFocusPainted(false);
VoteButton.setBorder(null);
VoteButton.setContentAreaFilled(false);
VoteButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/4.png")));
VoteButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/4_h.png")));
VoteButton.setBounds(new Rectangle(X, Y, 50, 50));
this.contentPane.add(VoteButton);
final JButton CloseButton = new JButton();
CloseButton.setFocusPainted(false);
CloseButton.setBorder(null);
CloseButton.setContentAreaFilled(false);
CloseButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Close.png")));
CloseButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Close_h.png")));
CloseButton.setBounds(new Rectangle(875, 0, 27, 28));
this.contentPane.add(CloseButton);
CloseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.exit(0);
}
});
final JButton MinimizeButton = new JButton();
MinimizeButton.setFocusPainted(false);
MinimizeButton.setBorder(null);
MinimizeButton.setContentAreaFilled(false);
MinimizeButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Minimize.png")));
MinimizeButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Minimize_h.png")));
MinimizeButton.setBounds(new Rectangle(850, -1, 27, 28));
this.contentPane.add(MinimizeButton);
MinimizeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
setState(Frame.ICONIFIED);
}
});
final JProgressBar ProgressBar = new JProgressBar();
ProgressBar.setLocation(150, 500);
ProgressBar.setSize(600, 50);
ProgressBar.setValue(50);
getContentPane().add(ProgressBar);
final JLabel backgroundLabel = new JLabel(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Background.png")));
backgroundLabel.setBounds(new Rectangle(0, 0, 1000, 563));
getContentPane().add(backgroundLabel);
JPanel titleBar = new JPanel();
titleBar.setBounds(0, 0, 1000, 25);
contentPane.add(titleBar);
titleBar.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me)
{
// Get x,y and store them
pX=me.getX();
pY=me.getY();
}
});
titleBar.addMouseMotionListener(new MouseAdapter(){
public void mouseDragged(MouseEvent me)
{
setLocation(getLocation().x+me.getX()-pX,getLocation().y+me.getY()-pY);
}
});
}
}

There are a number of ways you might achieve this, one of the better ways would be to create a custom ProgressBarUI delegate which paints itself the way you want, for example...
public class FancyProgressBar extends BasicProgressBarUI {
#Override
protected Dimension getPreferredInnerVertical() {
return new Dimension(20, 146);
}
#Override
protected Dimension getPreferredInnerHorizontal() {
return new Dimension(146, 20);
}
#Override
protected void paintDeterminate(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int iStrokWidth = 3;
g2d.setStroke(new BasicStroke(iStrokWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(progressBar.getBackground());
g2d.setBackground(progressBar.getBackground());
int width = progressBar.getWidth();
int height = progressBar.getHeight();
RoundRectangle2D outline = new RoundRectangle2D.Double((iStrokWidth / 2), (iStrokWidth / 2),
width - iStrokWidth, height - iStrokWidth,
height, height);
g2d.draw(outline);
int iInnerHeight = height - (iStrokWidth * 4);
int iInnerWidth = width - (iStrokWidth * 4);
double dProgress = progressBar.getPercentComplete();
if (dProgress < 0) {
dProgress = 0;
} else if (dProgress > 1) {
dProgress = 1;
}
iInnerWidth = (int) Math.round(iInnerWidth * dProgress);
int x = iStrokWidth * 2;
int y = iStrokWidth * 2;
Point2D start = new Point2D.Double(x, y);
Point2D end = new Point2D.Double(x, y + iInnerHeight);
float[] dist = {0.0f, 0.25f, 1.0f};
Color[] colors = {progressBar.getBackground(), progressBar.getBackground().brighter(), progressBar.getBackground().darker()};
LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors);
g2d.setPaint(p);
RoundRectangle2D fill = new RoundRectangle2D.Double(iStrokWidth * 2, iStrokWidth * 2,
iInnerWidth, iInnerHeight, iInnerHeight, iInnerHeight);
g2d.fill(fill);
g2d.dispose();
}
#Override
protected void paintIndeterminate(Graphics g, JComponent c) {
super.paintIndeterminate(g, c); //To change body of generated methods, choose Tools | Templates.
}
}
Normally you might be tempered to register this as the default look and feel delegate of all JProgressBars, but typically, I would install only on those instance of JProgressBar you really wanted it, that comes down to you.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.LinearGradientPaint;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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(Color.BLACK);
JProgressBar fancyPB = new JProgressBar();
fancyPB.setUI(new FancyProgressBar());
JProgressBar normalPB = new JProgressBar();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(fancyPB, gbc);
add(normalPB, gbc);
Timer timer = new Timer(250, new ActionListener() {
private int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
fancyPB.setValue(count);
normalPB.setValue(count);
count++;
if (count >= 100) {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
}
public class FancyProgressBar extends BasicProgressBarUI {
#Override
protected Dimension getPreferredInnerVertical() {
return new Dimension(20, 146);
}
#Override
protected Dimension getPreferredInnerHorizontal() {
return new Dimension(146, 20);
}
#Override
protected void paintDeterminate(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int iStrokWidth = 3;
g2d.setStroke(new BasicStroke(iStrokWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(progressBar.getBackground());
g2d.setBackground(progressBar.getBackground());
int width = progressBar.getWidth();
int height = progressBar.getHeight();
RoundRectangle2D outline = new RoundRectangle2D.Double((iStrokWidth / 2), (iStrokWidth / 2),
width - iStrokWidth, height - iStrokWidth,
height, height);
g2d.draw(outline);
int iInnerHeight = height - (iStrokWidth * 4);
int iInnerWidth = width - (iStrokWidth * 4);
double dProgress = progressBar.getPercentComplete();
if (dProgress < 0) {
dProgress = 0;
} else if (dProgress > 1) {
dProgress = 1;
}
iInnerWidth = (int) Math.round(iInnerWidth * dProgress);
int x = iStrokWidth * 2;
int y = iStrokWidth * 2;
Point2D start = new Point2D.Double(x, y);
Point2D end = new Point2D.Double(x, y + iInnerHeight);
float[] dist = {0.0f, 0.25f, 1.0f};
Color[] colors = {progressBar.getBackground(), progressBar.getBackground().brighter(), progressBar.getBackground().darker()};
LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors);
g2d.setPaint(p);
RoundRectangle2D fill = new RoundRectangle2D.Double(iStrokWidth * 2, iStrokWidth * 2,
iInnerWidth, iInnerHeight, iInnerHeight, iInnerHeight);
g2d.fill(fill);
g2d.dispose();
}
#Override
protected void paintIndeterminate(Graphics g, JComponent c) {
super.paintIndeterminate(g, c); //To change body of generated methods, choose Tools | Templates.
}
}
}
If you want to install the look and feel delegate as the default delegate, take a look at this answer for more details (scroll down a little, it's there)

Related

How to achieve non-destructive painting in Java?

I want to plot many sinusoids with different frequencies on a panel, but because painting is destructive, I cannot achieve this. I can only see the last sinusoid plotted.
In the code, the generateSinus() method is called only three times, but it might be called many times and I don't want to call g.fillOval() method for each sinusoid in the paintComponent() method.
Is there a way to achieve non-destructive painting and see all sinusioids with different frequencies?
Please see the code below:
package testdrawsinus;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestDrawSinus extends JPanel
{
private static double[] x;
private static double[] y;
private static boolean buttonClicked = false;
private static JPanel panel = new TestDrawSinus();
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GREEN);
if (buttonClicked)
{
for (int i=0; i<x.length; i++)
{
g.fillOval((int)x[i] + panel.getWidth()/2, -1*((int)y[i]) + panel.getHeight()/2, 10, 10);
}
buttonClicked = false;
}
}
private static void generateSinus(int freq)
{
x = new double[200];
y = new double[200];
for (int i=0; i<=199; i++)
{
x[i]= (double)i;
y[i] = 100*Math.sin(2*Math.PI*freq*i/200);
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel.setLayout(null);
panel.setBounds(20,20, 700,400);
panel.setBackground(Color.BLACK);
frame.add(panel);
JButton button1 = new JButton();
button1.setText("plot");
button1.setBounds(300, 500, 150, 50);
frame.add(button1);
button1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
buttonClicked = true;
generateSinus(1);
panel.repaint();
generateSinus(2);
panel.repaint();
generateSinus(3);
panel.repaint();
}
});
}
}
Thanks for your help.
There are a number of ways you might do this, one way would be to seperate each series into its own model, then have the panel paint each model, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
private Color[] masterColors = new Color[]{
Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY,
Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK,
Color.RED, Color.WHITE, Color.YELLOW
};
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TestDrawSinus sinusPane = new TestDrawSinus();
JFrame frame = new JFrame();
frame.add(sinusPane);
JButton button1 = new JButton();
button1.setText("plot");
frame.add(button1, BorderLayout.SOUTH);
button1.addActionListener(new ActionListener() {
private List<Color> colors = new ArrayList<>();
private int freq = 0;
#Override
public void actionPerformed(ActionEvent e) {
sinusPane.addSinusPlot(generateSinus(++freq, nextColor()));
sinusPane.addSinusPlot(generateSinus(++freq, nextColor()));
sinusPane.addSinusPlot(generateSinus(++freq, nextColor()));
}
protected Color nextColor() {
if (colors.isEmpty()) {
colors.addAll(Arrays.asList(masterColors));
Collections.shuffle(colors);
}
return colors.remove(0);
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Random rnd = new Random();
private SinusPlot generateSinus(int freq, Color color) {
double[] x = new double[200];
double[] y = new double[200];
for (int i = 0; i < 200; i++) {
x[i] = (double) i;
y[i] = 100 * Math.sin(2d * Math.PI * freq * i / 200d);
}
return new SinusPlot(x, y, color);
}
public class SinusPlot {
private double[] x;
private double[] y;
private Color color;
public SinusPlot(double[] x, double[] y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public int getSize() {
return x.length;
}
public double getXAt(int index) {
return x[index];
}
public double getYAt(int index) {
return y[index];
}
public Color getColor() {
return color;
}
}
public class TestDrawSinus extends JPanel {
private List<SinusPlot> plots = new ArrayList<>(8);
public void addSinusPlot(SinusPlot plot) {
plots.add(plot);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (SinusPlot plot : plots) {
System.out.println(plot.getColor());
g2d.setColor(plot.getColor());
for (int i = 0; i < plot.getSize(); i++) {
Ellipse2D dot = new Ellipse2D.Double(((getWidth() - plot.getSize()) / 2) + plot.getXAt(i), plot.getYAt(i) + getHeight() / 2, 10, 10);
g2d.fill(dot);
}
}
g2d.dispose();
}
}
}
null layouts aren't going to help you, take the time to learn understand how the layout management system works, it will save you lot of time and effort. See Laying Out Components Within a Container for more details.
static is not your friend (especially in this context), make the effort to understand how to live without it (and when to use it)

Need help to adjust a Zoom system in Graphics2D - Java

This is my 1st question here. I'm trying to build a White Page adjustable by zoom. It's inside a JScrollPane, so the size of the JScrollPane's ScrollBars are adjustable in the Dimension of that JPanel.
I want to adjust the size of those ScrollBars as the Size of the page (variables width and height in the code) + 2 borderSize, so the full size is equal the Page + margin of a borderSize around it. It works if zoom = 1.0.
If zoom < 1.0, the scroll bar is smaller than the Page and cut a piece of it. If zoom > 1 the Dimension size is way bigger than the page, leaving a huger border on its right and down corners, bigger than the borderSize.
How do I do this?
PS: I'm started learning java by myself, in the Quarantine last year, never had a teacher, just the internet, so any critics or suggestions, please, tell me.
Here's the JPanel's code:
package test;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.JSlider;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
public class Main2 {
private MyPanel mp = new MyPanel();
private JFrame frame;
private JSlider zoomSlider = new JSlider();
private JLabel zoomLabel = new JLabel("Zoom: XXX");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main2 window = new Main2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main2() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 619, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpringLayout springLayout = new SpringLayout();
frame.getContentPane().setLayout(springLayout);
springLayout.putConstraint(SpringLayout.SOUTH, zoomSlider, 40, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, zoomSlider, -115, SpringLayout.EAST, frame.getContentPane());
zoomSlider.setValue(100);
zoomSlider.setSnapToTicks(true);
zoomSlider.setPaintTicks(true);
zoomSlider.setMaximum(200);
zoomSlider.setMinorTickSpacing(5);
zoomSlider.setMinimum(5);
springLayout.putConstraint(SpringLayout.NORTH, zoomSlider, 0, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, zoomSlider, 0, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().add(zoomSlider);
JScrollPane scrollPane = new JScrollPane(mp);
springLayout.putConstraint(SpringLayout.NORTH, scrollPane, 10, SpringLayout.SOUTH, zoomSlider);
springLayout.putConstraint(SpringLayout.WEST, scrollPane, 10, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, scrollPane, -10, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, scrollPane, -10, SpringLayout.EAST, frame.getContentPane());
frame.getContentPane().add(scrollPane);
springLayout.putConstraint(SpringLayout.NORTH, zoomLabel, 10, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, zoomLabel, 6, SpringLayout.EAST, zoomSlider);
frame.getContentPane().add(zoomLabel);
frame.addWindowStateListener(new WindowStateListener() {
#Override
public void windowStateChanged(WindowEvent arg0) {
// TODO Auto-generated method stub
mp.draw();
}
});
zoomSlider.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
int temp = (zoomSlider.getValue())-zoomSlider.getValue()%5;
setZoom(temp);
mp.draw();
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
int temp = (zoomSlider.getValue())-zoomSlider.getValue()%5;
setZoom(temp);
mp.draw();
}
});
mp.addMouseWheelListener(new MouseWheelListener() {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getPreciseWheelRotation() < 0) {
setZoom(zoomSlider.getValue()- 5);
} else {
setZoom(zoomSlider.getValue()+ 5);
}
// zoom += e.getPreciseWheelRotation();
if (mp.getZoom()*100 < 10) {
setZoom(10);
}
mp.draw();
}
});
AdjustmentListener adj = new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
setZoom(zoomSlider.getValue());
mp.draw();
}
};
scrollPane.getVerticalScrollBar().addAdjustmentListener(adj);
scrollPane.getHorizontalScrollBar().addAdjustmentListener(adj);
}
public void setZoom(int n) {
mp.setZoom(n);
zoomSlider.setValue(n);
zoomLabel.setText("Zoom: "+mp.getZoom()+"x");
}
}
class MyPanel extends JPanel{
private static final long serialVersionUID = -716735372803790424L;
int borderSize=28;
int zoom=100;
int height = 3565;
int width = 2537;
int widthz, heightz;
public MyPanel() {
setBackground(Color.DARK_GRAY);
}
#Override
public Dimension getPreferredSize() {
int a, b;
String temp;
Float x, y;
x=(getZoom()*width); //Size of the page adjusted by zoom
y=(getZoom()*height);
temp = x.toString();
String temp1[] = temp.split("\\."); // converted to string to convert it to int
a = Integer.valueOf(temp1[0])+2*borderSize; //that value + 2 BorderSize
temp = y.toString();
String temp2[] = temp.split("\\.");
b = Integer.valueOf(temp2[0])+2*borderSize;
return new Dimension (a,b);
}
#Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d = putZoom(g2d);
g2d.setColor(Color.WHITE);
g2d.fillRect(this.getX(),this.getY(), width, height);
g2d.setColor(Color.BLACK);
g2d.drawRect(this.getX()+borderSize,this.getY()+borderSize,width-2*borderSize,height-2*borderSize);
g2d.dispose();
}
public Graphics2D putZoom(Graphics2D g) {
AffineTransform at = new AffineTransform();
at.translate(borderSize,borderSize); // put the page a borderSize from the upper-left corner
at.scale(getZoom(),getZoom()); //adjust the page as zoom
Graphics2D g2d = g;
g2d.setTransform(at);
return g2d;
}
public void draw() { //this method is to update the draw from the main
repaint();
}
public Float getZoom() {
return Float.valueOf(zoom)/100;
}
public void setZoom(int zom) { //this method is to update Zoom from the main
zoom=zom;
String zoomheight []= (String.valueOf(getZoom()*height)).split("\\.");
heightz = Integer.valueOf(zoomheight[0]);
String zoomwidth []= (String.valueOf(getZoom()*width)).split("\\.");
widthz = Integer.valueOf(zoomwidth[0]);
}
public int getZoomInt() {
return this.zoom;
}
}
Zoom(values from 0.1 to 2.0).
How can i improve this? Also, i have no idea how to update the JScrollPane's scrollbars together with the zoom.Thanks for the help.
UPDATE: i've created a minimal reproducible exemple.
Introduction
I started working on this before you updated your question. I used a zoom percentage rather than a zoom factor.
I created the following GUI and set the initial state to 30 percent.
I made the inner JPanel a checkerboard so you can more easily see the zoom. I modified your initial values so the inner JPanel would represent an 8 1/2 x 11 piece of paper at 50 pixels per inch.
Here's the same GUI at 100 percent.
Here's the same GUI at 10 percent.
Explanation
I created a JFrame and a control JPanel to hold the JSlider. I used a GridLayout to create the control JPanel.
I created an inner JPanel to hold the drawing and a display JPanel that holds the JScrollPane. I made the display JPanel proportionate to the size of the inner JPanel so I wouldn't have any stretching issues.
Getting the GUI to revalidate / repaint turned out to be the biggest challenge. I wound up having to invalidate the JScrollPane, both JScrollBars, and the display JPanel. I also had to reset the JScrollBars to zero each time I changed the zoom percentage.
Code
Here's the complete runnable code. I made all of the classes inner classes so I could post this as one code block.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ZoomJPanelGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ZoomJPanelGUI());
}
private int zoomPercentage = 30;
private DisplayPanel displayPanel;
private JFrame frame;
#Override
public void run() {
frame = new JFrame("Zoom JPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createControlPanel(), BorderLayout.BEFORE_FIRST_LINE);
this.displayPanel = new DisplayPanel(zoomPercentage);
frame.add(displayPanel.getPanel(), BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
JLabel label = new JLabel("Zoom Percentage");
label.setFont(panel.getFont().deriveFont(Font.BOLD, 24f));
panel.add(label);
JSlider slider = new JSlider(
JSlider.HORIZONTAL, 10, 100, zoomPercentage);
slider.setFont(panel.getFont().deriveFont(16f));
slider.setMajorTickSpacing(30);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent event) {
JSlider slider = (JSlider) event.getSource();
if (!slider.getValueIsAdjusting()) {
zoomPercentage = (int) slider.getValue();
displayPanel.setZoomPercentage(zoomPercentage);
displayPanel.repaint();
frame.pack();
}
}
});
panel.add(slider);
return panel;
}
public class DisplayPanel {
private InnerPanel innerPanel;
private final JPanel panel;
private JScrollPane scrollPane;
private int zoomPercentage;
public DisplayPanel(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
this.panel = createDisplayPanel();
}
private JPanel createDisplayPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
this.innerPanel = new InnerPanel(zoomPercentage);
scrollPane = new JScrollPane(innerPanel);
scrollPane.setPreferredSize(new Dimension(475, 600));
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
public void setZoomPercentage(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
innerPanel.setZoomPercentage(zoomPercentage);
}
public JPanel getPanel() {
return panel;
}
public void repaint() {
innerPanel.repaint();
scrollPane.invalidate();
JScrollBar hScrollBar = scrollPane.getHorizontalScrollBar();
JScrollBar vScrollBar = scrollPane.getVerticalScrollBar();
hScrollBar.setValue(0);
vScrollBar.setValue(0);
hScrollBar.invalidate();
vScrollBar.invalidate();
panel.invalidate();
}
}
public class InnerPanel extends JPanel {
private static final long serialVersionUID = 1L;
private int maximumBorderSize = 25;
private int maximumCellSize = 50;
private int maximumHeight = 5500;
private int maximumWidth = 4250;
private int zoomPercentage;
public InnerPanel(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
}
public void setZoomPercentage(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
}
#Override
public Dimension getPreferredSize() {
int width = maximumWidth * zoomPercentage / 100;
int height = maximumHeight * zoomPercentage / 100;
return new Dimension(width, height);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int borderSize = maximumBorderSize * zoomPercentage / 100;
paintBackground(g2d);
paintBorder(g2d, borderSize);
paintCheckerboard(g2d, borderSize);
}
private void paintBackground(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
private void paintBorder(Graphics2D g2d, int borderSize) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(3f));
g2d.drawRect(borderSize, borderSize, getWidth() - 2 * borderSize,
getHeight() - 2 * borderSize);
}
private void paintCheckerboard(Graphics2D g2d, int borderSize) {
int cellSize = maximumCellSize * zoomPercentage / 100;
int width = maximumWidth - maximumBorderSize * 2 - 2;
int height = maximumHeight - maximumBorderSize * 2 - 2;
int cellWidth = width / maximumCellSize;
int cellHeight = height / maximumCellSize;
boolean isBlue = true;
int x = borderSize;
int y = borderSize;
int heightRemainder = height - cellHeight * cellSize;
for (int i = 0; i < cellHeight; i++) {
int widthRemainder = width - cellWidth * cellSize;
for (int j = 0; j < cellWidth; j++) {
if (isBlue) {
g2d.setColor(Color.BLUE);
} else {
g2d.setColor(Color.YELLOW);
}
isBlue = !isBlue;
g2d.fillRect(x, y, cellSize, cellSize);
x += cellSize;
if (widthRemainder > 0) {
x++;
widthRemainder--;
}
}
// isBlue = !isBlue;
x = borderSize;
y += cellSize;
if (heightRemainder > 0) {
y++;
heightRemainder--;
}
}
}
}
}
I've finally did it. Started by not using transformation for scaling it, but making a new draw with the size zoomed, adapting all sizes in the method setSizes(), and adjusting the Dimension by those sizes.
(Just changed this class)
class MyPanel extends JPanel{
private static final long serialVersionUID = -716735372803790424L;
int borderSize=28;
int zoom=100;
int height = 3565;
int width = 2537;
int widthz, heightz;
int maxHeight, maxWidth; //max size of draw
int maxAreaHeight, maxAreaWidth; //max size of area
public MyPanel() {
setBackground(Color.DARK_GRAY);
}
#Override
public Dimension getPreferredSize() {
setSizes();
return new Dimension (maxAreaWidth,maxAreaHeight);
}
#Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d= createBase(g2d);
}
public void draw() { //this method is to update the draw from the main
repaint();
}
public Float getZoom() {return Float.valueOf(zoom)/100;}
public void setZoom(int zom) {zoom=zom;}
public int getZoomInt() {return this.zoom;}
public void setSizes () {
widthz= width*getZoomInt()/100;
heightz=height*getZoomInt()/100;
maxHeight = heightz+2*borderSize;
maxWidth = widthz +2*borderSize;
maxAreaHeight = this.getY()+maxHeight;
maxAreaWidth = this.getX()+maxWidth;
if (this.getSize() != new Dimension(maxAreaWidth, maxAreaHeight)) {
this.setSize(maxAreaWidth, maxAreaHeight);
}
}
public Graphics2D createBase(Graphics2D g2d) {
Graphics2D g = g2d;
setSizes();
g.setColor(Color.WHITE);
g.fillRect(this.getX()+borderSize,this.getY()+borderSize, widthz, heightz);
g.setColor(Color.BLACK);
g.drawRect(this.getX()+borderSize+borderSize*zoom/100,this.getY()+borderSize+borderSize*zoom/100,widthz-2*borderSize*zoom/100,heightz-2*borderSize*zoom/100);
return g;
}
}
Thanks for all the help.

how to make looping circular progress with progress indeterminate task?

I have a program that retrieves data, where each retrieval can not be determined its completion time. My idea would be to make a progress that keeps repeating and flagging if the capture is complete.
my current source code, method from main class:
public JComponent makeUI(boolean displayProgressBar) {
if(displayProgressBar){
jpbCircularProg.setUI(new principal.ProgressCircleUI());
jpbCircularProg.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//Border emptyBorder = BorderFactory.createEmptyBorder();
//jpbCircularProg.setBorder(emptyBorder);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setFont(jpbCircularProg.getFont().deriveFont(24f));
jpbCircularProg.setForeground(Color.ORANGE);
if(jpbCircularProg.isVisible()==false){
jpbCircularProg.setVisible(true);
}
(new Timer(10, e -> {// percepat
System.out.println("progressbar on :");
int iv = Math.min(100, jpbCircularProg.getValue() + 1);
jpbCircularProg.setValue(iv);
if(jpbCircularProg.getValue()==100){
jpbCircularProg.setValue(1);
}
})).start();
}else{
if(jpbCircularProg.isVisible()==true){
jpbCircularProg.setVisible(false);
}
(new Timer(10, e -> {// percepat
System.out.println("progressbar on :");
int iv = Math.min(100, jpbCircularProg.getValue() + 1);
jpbCircularProg.setValue(iv);
if(jpbCircularProg.getValue()==100){
jpbCircularProg.setValue(0);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setVisible(false);
}
})).start();
}
jPanel2.setOpaque(false);
jPanel2.add(jpbCircularProg);
return jPanel2;
}
ProgressCircleUI.java:
public class ProgressCircleUI extends BasicProgressBarUI {
#Override
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
#Override public void paint(Graphics g, JComponent c) {
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - b.right - b.left;
int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = b.left + barRectWidth * .5;
double cy = b.top + barRectHeight * .5;
double or = sz * .5;
double ir = or * .5; //or - 20;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
Shape outer = new Arc2D.Double(
cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
g2.fill(area);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
}
}
}
Source code diatassaya get from a website then i modified a bit. I give the loop and the result is successful, but when the data retrieval more than once circular progress cycle becomes very fast and always increase faster for next data retrieval. I tried by using setIntermedinate (true) but it seems to ProgressBar not a Circular. Please help.
but when the data retrieval more than once circular progress cycle becomes very fast and always increase faster for next data retrieval
You're not stopping the timer, in fact, you seem to be using a second Timer to hide the progress bar ... for some reason.
This means, each time you want to use the progress indicator, you create ANOTHER Timer, which creates a bunch of competing Timers all changing the state and interfering with each other.
A better and simpler solution would be to create a single Timer and simply stop/start it as need, for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JProgressBar jpbCircularProg;
private Timer timer;
public TestPane() {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int iv = Math.min(100, jpbCircularProg.getValue() + 1);
jpbCircularProg.setValue(iv);
if (jpbCircularProg.getValue() == 100) {
jpbCircularProg.setValue(1);
}
}
});
jpbCircularProg = new JProgressBar();
jpbCircularProg.setUI(new ProgressCircleUI());
jpbCircularProg.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//Border emptyBorder = BorderFactory.createEmptyBorder();
//jpbCircularProg.setBorder(emptyBorder);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setFont(jpbCircularProg.getFont().deriveFont(24f));
jpbCircularProg.setForeground(Color.ORANGE);
if (jpbCircularProg.isVisible() == false) {
jpbCircularProg.setVisible(true);
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = GridBagConstraints.REMAINDER;
add(jpbCircularProg, gbc);
JButton toggle = new JButton("Toggle");
toggle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.restart();
}
}
});
add(toggle, gbc);
}
}
public class ProgressCircleUI extends BasicProgressBarUI {
#Override
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
#Override
public void paint(Graphics g, JComponent c) {
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - b.right - b.left;
int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = b.left + barRectWidth * .5;
double cy = b.top + barRectHeight * .5;
double or = sz * .5;
double ir = or * .5; //or - 20;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
Shape outer = new Arc2D.Double(
cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
g2.fill(area);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
}
}
}
}
Since you're trying to display this as a "intermediate" progress bar, it would be better to wrap up the animation functionality into the UI delegate itself.
The following example makes use of the "intermediate" state of the JProgressBar to self animate the progress, managing the Timer state itself
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.beans.PropertyChangeEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JProgressBar jpbCircularProg;
public TestPane() {
jpbCircularProg = new JProgressBar();
jpbCircularProg.setUI(new ProgressCircleUI());
jpbCircularProg.setIndeterminate(true);
jpbCircularProg.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//Border emptyBorder = BorderFactory.createEmptyBorder();
//jpbCircularProg.setBorder(emptyBorder);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setFont(jpbCircularProg.getFont().deriveFont(24f));
jpbCircularProg.setForeground(Color.ORANGE);
if (jpbCircularProg.isVisible() == false) {
jpbCircularProg.setVisible(true);
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = GridBagConstraints.REMAINDER;
add(jpbCircularProg, gbc);
JButton toggle = new JButton("Toggle");
toggle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jpbCircularProg.setIndeterminate(!jpbCircularProg.isIndeterminate());
}
});
add(toggle, gbc);
}
}
public class ProgressCircleUI extends BasicProgressBarUI {
private Timer timer;
private Handler handler = new Handler();
#Override
public void installUI(JComponent c) {
initTimer();
super.installUI(c);
}
protected void initTimer() {
if (timer == null) {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int iv = Math.min(100, progressBar.getValue() + 1);
progressBar.setValue(iv);
if (progressBar.getValue() == 100) {
progressBar.setValue(1);
}
progressBar.repaint();
}
});
}
}
#Override
protected void startAnimationTimer() {
timer.restart();
}
#Override
protected void stopAnimationTimer() {
timer.stop();
}
private void initIndeterminateValues() {
initTimer();
// we only bother installing the HierarchyChangeListener if we
// are indeterminate
progressBar.addHierarchyListener(handler);
// start the animation thread if necessary
if (progressBar.isDisplayable()) {
startAnimationTimer();
}
}
/**
* Invoked by PropertyChangeHandler.
*/
private void cleanUpIndeterminateValues() {
// stop the animation thread if necessary
if (progressBar.isDisplayable()) {
stopAnimationTimer();
}
progressBar.setValue(0);
progressBar.removeHierarchyListener(handler);
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if ("indeterminate" == prop) {
if (progressBar.isIndeterminate()) {
initIndeterminateValues();
} else {
//clean up
cleanUpIndeterminateValues();
}
progressBar.repaint();
}
}
#Override
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
#Override
public void paint(Graphics g, JComponent c) {
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - b.right - b.left;
int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = b.left + barRectWidth * .5;
double cy = b.top + barRectHeight * .5;
double or = sz * .5;
double ir = or * .5; //or - 20;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
Shape outer = new Arc2D.Double(
cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
g2.fill(area);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted() && !progressBar.isIndeterminate()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
}
}
protected class Handler implements HierarchyListener {
public void hierarchyChanged(HierarchyEvent he) {
if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (progressBar.isIndeterminate()) {
if (progressBar.isDisplayable()) {
startAnimationTimer();
} else {
stopAnimationTimer();
}
}
}
}
}
}
}

GUI doesn't respond to mouse click and drag while running from another class

I have 2 classes: TestingPanel and SnipIt.
SnipIt is used for selecting an area on the screen.
TestingPanel is the main frame, containing a button to run method Snip() and receiving the return values.
If I test the SnipIt class separately, it works. But if I create a SnipIt object and run method Snip() from TestingPanel class, it doesn't work. The GUI just freezes and doesn't respond to mouse click or drag event. I guess something block the thread handle the mouse events but I'm not sure.
I have been stuck for couple hours and still don't know what caused the issue. Please help.
TestingPanel
package Testing;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestingPanel {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestingPanel window = new TestingPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestingPanel() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 200, 160);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnSnip = new JButton("Snip");
btnSnip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getSelectionSize();
}
});
btnSnip.setBounds(47, 87, 89, 23);
frame.getContentPane().add(btnSnip);
}
private void getSelectionSize() {
int[] size = new int[4];
Thread worker = new Thread(new Runnable() {
public void run() {
SnipIt sn = new SnipIt();
sn.snip();
while(!sn.complete) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
size[0] = sn.returnSize()[0];
size[1] = sn.returnSize()[1];
size[2] = sn.returnSize()[2];
size[3] = sn.returnSize()[3];
}
});
worker.start();
try {
worker.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(size[0] + " " + size[1] + " " + size[2] + " " + size[3]);
}
}
SnipIt
package Testing;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class SnipIt {
private int recX = 0;
private int recY = 0;
private int recWidth = 0;
private int recHeight = 0;
public boolean complete = false;
/*
public static void main(String [] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SnipIt s = new SnipIt();
s.snip();
}
});
}
*/
public void snip() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SnipItPane());
frame.setBounds(getVirtualBounds());
frame.setVisible(true);
}
#SuppressWarnings("serial")
public class SnipItPane extends JPanel {
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
private ControlPane controlPane;
public SnipItPane() {
setOpaque(false);
setLayout(null);
selectionPane = new SelectionPane();
controlPane = new ControlPane();
add(selectionPane);
add(controlPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
controlPane.setLocation(mouseAnchor);
controlPane.setSize(0, 0);
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
int controlY = y + height + 5;
controlPane.setBounds(x, controlY, width, 25);
controlPane.revalidate();
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight());
Area area = new Area(bounds);
area.subtract(new Area(selectionPane.getBounds()));
g2d.setColor(new Color(102, 102, 102, 80));
g2d.fill(area);
}
}
#SuppressWarnings("serial")
public class ControlPane extends JPanel {
private JButton btnClose;
public ControlPane() {
setOpaque(false);
btnClose = new JButton("Save");
setLayout(new BorderLayout());
this.add(btnClose, BorderLayout.NORTH);
btnClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
complete = true;
SwingUtilities.getWindowAncestor(ControlPane.this).dispose();
}
});
}
}
#SuppressWarnings("serial")
public class SelectionPane extends JPanel {
public SelectionPane() {
setOpaque(false);
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
recX = getX();
recY = getY();
recWidth = getWidth();
recHeight = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
float strokeWidth = 1.0f;
float dash1[] = {10.0f};
BasicStroke dashed =
new BasicStroke(strokeWidth,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g2d.dispose();
}
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
for (GraphicsDevice gd : lstGDs) {
bounds.add(gd.getDefaultConfiguration().getBounds());
}
return bounds;
}
public int[] returnSize() {
int[] size = new int[4];
size[0] = recX;
size[1] = recY;
size[2] = recWidth;
size[3] = recHeight;
return size;
}
}
You're running the Snipit application in a background thread and then freezing that thread with Thread.sleep and a while true block, something guaranteed to freeze the GUI. Read Lesson: Concurrency in Swing and then be sure to always run Swing applications on the single Swing event thread, and do any long running or sleeping code in a background thread.
Possible solutions to your issue:
Make the Snipit window an undecorated modal dialog. This way program flow from the calling code stops when the dialog is visible and resumes when no longer visible.
Or Make the Snipit window JFrame an instance field of the class and allow outside classes to add listeners to it so that they will be notified when it closes.
e.g.,
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestSnipit {
private static void createAndShowGui() {
boolean runTest = true;
if (runTest) {
TestingPanel.main(null);
} else {
SnipIt.main(null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class TestingPanel {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestingPanel window = new TestingPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestingPanel() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 200, 160);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnSnip = new JButton("Snip");
btnSnip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getSelectionSize();
}
});
btnSnip.setBounds(47, 87, 89, 23);
frame.getContentPane().add(btnSnip);
}
private void getSelectionSize() {
int[] size = new int[4];
// !!
SnipIt sn = new SnipIt();
sn.snip(frame);
// Thread worker = new Thread(new Runnable() {
// public void run() {
// SnipIt sn = new SnipIt();
// sn.snip();
//
// while (!sn.complete) {
// try {
// Thread.sleep(800);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
size[0] = sn.returnSize()[0];
size[1] = sn.returnSize()[1];
size[2] = sn.returnSize()[2];
size[3] = sn.returnSize()[3];
// }
// });
//
// worker.start();
//
// try {
// worker.join();
// } catch (InterruptedException e1) {
// e1.printStackTrace();
// }
System.out.println(size[0] + " " + size[1] + " " + size[2] + " " + size[3]);
}
}
class SnipIt {
private int recX = 0;
private int recY = 0;
private int recWidth = 0;
private int recHeight = 0;
public boolean complete = false;
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SnipIt s = new SnipIt();
s.snip(null); // !!
}
});
}
public void snip(Window owner) { // !!
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
// JFrame frame = new JFrame();
JDialog frame = new JDialog(owner, null, ModalityType.APPLICATION_MODAL); // !!
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // !!
frame.setLayout(new BorderLayout());
frame.add(new SnipItPane());
frame.setBounds(getVirtualBounds());
frame.setVisible(true);
}
#SuppressWarnings("serial")
public class SnipItPane extends JPanel {
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
private ControlPane controlPane;
public SnipItPane() {
setOpaque(false);
setLayout(null);
selectionPane = new SelectionPane();
controlPane = new ControlPane();
add(selectionPane);
add(controlPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
controlPane.setLocation(mouseAnchor);
controlPane.setSize(0, 0);
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
int controlY = y + height + 5;
controlPane.setBounds(x, controlY, width, 25);
controlPane.revalidate();
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight());
Area area = new Area(bounds);
area.subtract(new Area(selectionPane.getBounds()));
g2d.setColor(new Color(102, 102, 102, 80));
g2d.fill(area);
}
}
#SuppressWarnings("serial")
public class ControlPane extends JPanel {
private JButton btnClose;
public ControlPane() {
setOpaque(false);
btnClose = new JButton("Save");
setLayout(new BorderLayout());
this.add(btnClose, BorderLayout.NORTH);
btnClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
complete = true;
SwingUtilities.getWindowAncestor(ControlPane.this).dispose();
}
});
}
}
#SuppressWarnings("serial")
public class SelectionPane extends JPanel {
public SelectionPane() {
setOpaque(false);
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
recX = getX();
recY = getY();
recWidth = getWidth();
recHeight = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
float strokeWidth = 1.0f;
float dash1[] = { 10.0f };
BasicStroke dashed = new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g2d.dispose();
}
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
for (GraphicsDevice gd : lstGDs) {
bounds.add(gd.getDefaultConfiguration().getBounds());
}
return bounds;
}
public int[] returnSize() {
int[] size = new int[4];
size[0] = recX;
size[1] = recY;
size[2] = recWidth;
size[3] = recHeight;
return size;
}
}
A side issue unrelated to your initial problem is your use of null layougs. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

Update LookAndFeel Values On The Fly

I want to be able to update the LookAndFeel attributes of my Swing GUI on the fly. In this case, I have a simple Swing/Awt game running what starts out as the Nimbus LookAndFeel. At various points after start up I want to change (let us say) just one detail: the background color of my application.
I can change the background color by doing this:
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.RED);
SwingUtilities.updateComponentTreeUI(SomeGame.this);
break;
}
}
This "works" in that the background color of the app changes correctly and the program doesn't crash. But on the command line I get error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.synth.SynthLookAndFeel.paintRegion(SynthLookAndFeel.java:371)
at javax.swing.plaf.synth.SynthLookAndFeel.update(SynthLookAndFeel.java:335)
Obviously, something is null, but I can not figure out what it is or how to fix it. There must be something I don't understand. I have looked at other StackOverflow questions about setting background colors in Nimbus and overriding the LookAndFeel information after startup.
When I call getLookAndFeelDefaults() do I need to specify the rest of the defaults as well?
Have there been changes in how this works between Java 1.6 and 1.7?
all code for Java6, have to change Nimbus imports for Java7
Nimbus has a few suprises, one of them is that is possible (without dirty hacks, I'm leaving comments for those hacks) to change Background for JPanel only one time
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
public class ButtonTest {
private JFrame frame;
private JPanel panel;
private JButton opaqueButton1;
private JButton opaqueButton2;
private SoftJButton softButton1;
private SoftJButton softButton2;
private Timer alphaChanger;
public void createAndShowGUI() {
opaqueButton1 = new JButton("Opaque Button");
opaqueButton2 = new JButton("Opaque Button");
softButton1 = new SoftJButton("Transparent Button");
softButton2 = new SoftJButton("Transparent Button");
opaqueButton1.setBackground(Color.GREEN);
softButton1.setBackground(Color.GREEN);
panel = new JPanel();
panel.setLayout(new java.awt.GridLayout(2, 2, 10, 10));
panel.add(opaqueButton1);
panel.add(softButton1);
panel.add(opaqueButton2);
panel.add(softButton2);
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
frame = new JFrame();
frame.add(panel);
frame.setLocation(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
alphaChanger = new Timer(50, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
softButton2.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(3500, new ActionListener() {
private final LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
if (laf[index].getClassName().equals("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel")) {
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.orange);
SwingUtilities.updateComponentTreeUI(frame);
} else {
panel.setBackground(Color.yellow);
SwingUtilities.updateComponentTreeUI(frame);
}
opaqueButton1.setText(laf[index].getClassName());
softButton1.setText(laf[index].getClassName());
frame.pack();
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private static class SoftJButton extends JButton {
private static final JButton lafDeterminer = new JButton();
private static final long serialVersionUID = 1L;
private boolean rectangularLAF;
private float alpha = 1f;
SoftJButton() {
this(null, null);
}
SoftJButton(String text) {
this(text, null);
}
SoftJButton(String text, Icon icon) {
super(text, icon);
setOpaque(false);
setFocusPainted(false);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
#Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
}
#Override
public void updateUI() {
super.updateUI();
lafDeterminer.updateUI();
rectangularLAF = lafDeterminer.isOpaque();
}
}
}
but for JComponent it is possible to change its Color, Font, etc by calling UIManager.getLookAndFeel().uninitialize();, but this does not work for containers
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
public class NimbusTestButtonsBackground extends JFrame {
private static final long serialVersionUID = 1L;
private javax.swing.JButton button;
public NimbusTestButtonsBackground() {
button = new javax.swing.JButton();
button.setText("Text");
add(button);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.pack();
Timer t = new Timer(1000, new ActionListener() {
private Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
try {
LookAndFeel lnf = UIManager.getLookAndFeel().getClass().newInstance();
UIDefaults uiDefaults = lnf.getDefaults();
uiDefaults.put("nimbusBase", c);
UIManager.getLookAndFeel().uninitialize();
UIManager.setLookAndFeel(lnf);
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
UIDefaults defaults = UIManager.getDefaults();
defaults.put("Button.background", c);
SwingUtilities.updateComponentTreeUI(button);
}
});
t.start();
}
public static void main(String args[]) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
return;
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NimbusTestButtonsBackground().setVisible(true);
}
});
}
}
then I see (this way as most comfortable, easiest, etc..) overriding paintComponent for JPanel as best the best way
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class ChangePanelBackgroundNimbus {
private JFrame frame = new JFrame();
public ChangePanelBackgroundNimbus() {
GradientPane pane = new GradientPane();
pane.setLayout(new GridLayout(6, 4, 10, 10));
for (int i = 1; i <= 24; i++) {
pane.add(createButton(i));
}
pane.setOpaque(false);
frame.add(pane);
RepaintManager.setCurrentManager(new RepaintManager() {
#Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Container con = c.getParent();
while (con instanceof JComponent) {
if (!con.isVisible()) {
return;
}
if (con instanceof GradientPane) {
c = (JComponent) con;
x = 0;
y = 0;
w = con.getWidth();
h = con.getHeight();
}
con = con.getParent();
}
super.addDirtyRegion(c, x, y, w, h);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
//frame.setSize(400, 300);
frame.pack();
frame.setVisible(true);
}
private JButton createButton(final int text) {
JButton button = new JButton(Integer.toString(text));
return button;
}
class GradientPane extends JPanel {
private static final long serialVersionUID = 1L;
private final int h = 150;
private BufferedImage img = null;
private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB);
public GradientPane() {
paintBackGround(new Color(150, 250, 150));
Timer t = new Timer(500, new ActionListener() {
private Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
paintBackGround(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
}
});
t.start();
}
public void paintBackGround(Color g) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(g);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h, new Color(0.4f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paintComponent(Graphics g) {
if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paintComponent(g2);
Rectangle bounds = this.getVisibleRect();
g2.scale(bounds.getWidth(), -1);
g2.drawImage(shadow, bounds.x, -bounds.y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
repaint();
}
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ChangePanelBackgroundNimbus ml = new ChangePanelBackgroundNimbus();
}
});
}
}

Categories

Resources