Change colors for JProgressBar with Nimbus? - java

does anyone know how to change the colors for JProgressBar when you use Nimbus LookAndFeel?

I have overridden the whole nimbusOrange-Default Value, which change all ProgressBar-Colors and any other nimbusOrange. (InternalFrame - minimize Button)
here with nimbusBase (blue)
UIDefaults defaults = UIManager.getLookAndFeelDefaults();
defaults.put("nimbusOrange",defaults.get("nimbusBase"));
Better is to write a own Painter and set this to the UIManager via
UIManager.put("ProgressBar[Enabled].backgroundPainter", myPainter);
If You want to change the Color for only a single ProgressBar instance, you can use Per-component customization
progress = new JProgressBar();
UIDefaults defaults = new UIDefaults();
defaults.put("ProgressBar[Enabled].backgroundPainter", new MyPainter());
progress.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
progress.putClientProperty("Nimbus.Overrides", defaults);

an example of MyPainter can be as following:
class MyPainter implements Painter<JProgressBar> {
private final Color color;
public MyPainter(Color c1) {
this.color = c1;
}
#Override
public void paint(Graphics2D gd, JProgressBar t, int width, int height) {
gd.setColor(color);
gd.fillRect(0, 0, width, height);
}
}
but my compiler or IDE (eclipse) says that it doesn't know the Painter.
is there anybody to help me!

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class JProgressBarDemo extends JFrame {
protected int minValue = 0;
protected int maxValue = 100;
protected int counter = 0;
protected JProgressBar progressBar;
public JProgressBarDemo() {
super("JProgressBar Demo");
setSize(300, 100);
UIManager.put("ProgressBar.background", Color.BLACK); //colour of the background
UIManager.put("ProgressBar.foreground", Color.RED); //colour of progress bar
UIManager.put("ProgressBar.selectionBackground",Color.YELLOW); //colour of percentage counter on black background
UIManager.put("ProgressBar.selectionForeground",Color.BLUE); //colour of precentage counter on red background
progressBar = new JProgressBar();
progressBar.setMinimum(minValue);
progressBar.setMaximum(maxValue);
progressBar.setStringPainted(true);
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
counter = minValue;
while (counter <= maxValue) {
Runnable runme = new Runnable() {
public void run() {
progressBar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
});
getContentPane().add(progressBar, BorderLayout.CENTER);
getContentPane().add(start, BorderLayout.WEST);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String[] args) {
new JProgressBarDemo();
}
}

Related

How to define multiple JButton actions from a different class

I am writing a program where I need to do different actions for a separate class depending on which button is clicked.
public class NewJFrame{
public static JButton b1;
public static JButton b2;
public static JButton b3;
}
public class Slot{
int value;
JButton button;
Slot(int value, JButton button)
{
this.value=value;
this.button=button;
}
}
public class Game{
Slot[] slots=new Slot[3];
Game(){
slots[0]=new Slot(1,NewJFrame.b1);
slots[1]=new Slot(2,NewJFrame.b2);
slots[2]=new Slot(3,NewJFrame.b3);
}
public void actionPerformed(ActionEvent e) {
for(int i=0;i<3;i++){
if(e.getSource()==slots[i].button)
slots[i].button.setText(String.valueOf(value));
}
}
}
Something like this. Note that, I'm completely novice at GUI designing.
Use Action to encapsulate functionality for use elsewhere in your program, e.g. buttons, menus and toolbars. The BeaconPanel shown below exports several actions that make it easy to use them in a control panel. To limit the proliferation of instances, the actions themselves can be class members. As an exercise, change controls to a JToolBar or add the same actions to a menu.
JPanel controls = new JPanel();
controls.add(new JButton(beaconPanel.getFlashAction()));
controls.add(new JButton(beaconPanel.getOnAction()));
controls.add(new JButton(beaconPanel.getOffAction()));
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.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/a/37063037/230513 */
public class Beacon {
private static class BeaconPanel extends JPanel {
private static final int N = 16;
private final Ellipse2D.Double ball = new Ellipse2D.Double();
private final Timer timer;
private final Color on;
private final Color off;
private final AbstractAction flashAction = new AbstractAction("Flash") {
#Override
public void actionPerformed(ActionEvent e) {
timer.restart();
}
};
private final AbstractAction onAction = new AbstractAction("On") {
#Override
public void actionPerformed(ActionEvent e) {
stop(on);
}
};
private final AbstractAction offAction = new AbstractAction("Off") {
#Override
public void actionPerformed(ActionEvent e) {
stop(off);
}
};
private Color currentColor;
public BeaconPanel(Color on, Color off) {
this.on = on;
this.off = off;
this.currentColor = on;
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
changeColors();
}
});
}
public void start() {
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x = getX() + N;
int y = getY() + N;
int w = getWidth() - 2 * N;
int h = getHeight() - 2 * N;
ball.setFrame(x, y, w, h);
g2.setColor(currentColor);
g2.fill(ball);
g2.setColor(Color.black);
g2.draw(ball);
}
private void changeColors() {
currentColor = currentColor == on ? off : on;
repaint();
}
private void stop(Color color) {
timer.stop();
currentColor = color;
repaint();
}
public Action getFlashAction() {
return flashAction;
}
public Action getOnAction() {
return onAction;
}
public Action getOffAction() {
return offAction;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(N * N, N * N);
}
}
public static void display() {
JFrame f = new JFrame("Beacon");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final BeaconPanel beaconPanel = new BeaconPanel(Color.orange, Color.orange.darker());
f.add(beaconPanel);
JPanel controls = new JPanel();
controls.add(new JButton(beaconPanel.getFlashAction()));
controls.add(new JButton(beaconPanel.getOnAction()));
controls.add(new JButton(beaconPanel.getOffAction()));
f.add(controls, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
beaconPanel.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Beacon.display();
}
});
}
}

Can't animate an Image in a JLabel

I would like to animate an Image placed in a JLabel like you can see below.
I have a problem with animation. The code doesn't produce any errors, but it just works in the void indefinitely.
Class Obstacle:
package imageTest;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Obstacle extends JPanel {
//Position
int posX,posY;
public int getPosX(){
return this.posX;
}
public void setPosX(int posX){
this.posX=posX;
}
public int getPosY(){
return this.posY;
}
public void setPosY(int posY){
this.posY=posY;
}
public int fctHasard(int borneInf,int borneSup){
int random = (int)(Math.random() * (borneSup-borneInf)) + borneInf;
return random;
}
//Image Obstacle
Image imgObstacle =new Image("C:\\Users\\antoine\\Desktop\\imgProjetObstacle.JPG");
JLabel labImgObstacle =null;
public void fctDessinerObstacle(JFrame fenPrincipale, JPanel panPrincipale) throws IOException{
int posXDepart=fctHasard(0,fenPrincipale.getWidth()),posYDepart=ImageUtil.getImageHeight(imgObstacle.adresseImg);
posX=posXDepart;
posY=posYDepart;
labImgObstacle=imgObstacle.fctAfficherImg(panPrincipale, posX,posY,ImageUtil.getImageWidth(imgObstacle.adresseImg), ImageUtil.getImageHeight(imgObstacle.adresseImg));
panPrincipale.add(labImgObstacle);
//fctMouvement(fenPrincipale, labImgObstacle ,panPrincipale,posX,posY);
}
public void fctMouvement(JFrame fenPrincipale, JLabel labImgObstacle , JPanel panPrincipale,int posX ,int posY) throws IOException{
boolean continuer=true;
while(continuer){
posY++;
labImgObstacle=imgObstacle.fctAfficherImg(panPrincipale, posX,posY,ImageUtil.getImageWidth(imgObstacle.adresseImg), ImageUtil.getImageHeight(imgObstacle.adresseImg));
panPrincipale.add(labImgObstacle);
panPrincipale.repaint();//remetlefondvierge
if(posY==fenPrincipale.getHeight()){
posX=fctHasard(0,fenPrincipale.getWidth());
posY=-ImageUtil.getImageHeight(imgObstacle.adresseImg);
//remet le fond vierge
labImgObstacle=imgObstacle.fctAfficherImg(panPrincipale, posX,posY,ImageUtil.getImageWidth(imgObstacle.adresseImg), ImageUtil.getImageHeight(imgObstacle.adresseImg));
panPrincipale.add(labImgObstacle);
}
}
}
}
EDIT1:
I try to understand you problem, is it to move a image into a JLabel ?
In this case, I try just to put an image as icon into a Jlabel and move while clicking on the JPanel as you can see below :
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
public class Main extends JPanel {
public JLabel label1 ;
private int x = 100;
private int y = 5;
public Main() {
setLayout(null);
setPreferredSize( new Dimension(640, 480 ) );
addMouseListener(new MouseListener() {
#Override
public void mousePressed(MouseEvent e) {
x = x + 10;
y = y + 10;
label1.setBounds(x + getInsets().left, y + getInsets().top, label1.getPreferredSize().width, label1.getPreferredSize().height);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
ImageIcon icon = createImageIcon("middle.gif", "a pretty but meaningless splat");
label1 = new JLabel("Image and Text",icon, JLabel.CENTER);
add(label1);
label1.setBounds(x + getInsets().left, y + getInsets().top, label1.getPreferredSize().width, label1.getPreferredSize().height);
}
protected static ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = Main.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Main());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
May be that could be the beginning to animate something ?

Java - (NetBeans) Make a JTextArea Slide Out From Behind JFrame

I have just written a program in Netbeans that moves/copies/deletes files, and I wanted to give it a "diagnostic mode" where information about selected files, folders, variables, etc is displayed in a Text Area. Now, I could set this to only be visible when the "diagnostic mode" toggle is selected, but I think it would look awesome if the text area started behind the program, and "slid" out from behind the JFrame when the button is toggled. Is there any way to do this?
Thanks!
-Sean
Here is some starter code for you. This will right-slide a panel
of just about any content type. Tweak as necessary. Add error
checking and exception handling.
Tester:
static public void main(final String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
final JPanel slider = new JPanel();
slider.setLayout(new FlowLayout());
slider.setBackground(Color.RED);
slider.add(new JButton("test"));
slider.add(new JButton("test"));
slider.add(new JTree());
slider.add(new JButton("test"));
slider.add(new JButton("test"));
final CpfJFrame42 cpfJFrame42 = new CpfJFrame42(slider, 250, 250);
cpfJFrame42.slide(CpfJFrame42.CLOSE);
cpfJFrame42.setSize(300, 300);
cpfJFrame42.setLocationRelativeTo(null);
cpfJFrame42.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cpfJFrame42.setVisible(true);
}
});
}
Use GAP & MIN to adjust spacing from JFrame and closed size.
The impl is a little long...it uses a fixed slide speed but
that's one the tweaks you can make ( fixed FPS is better ).
package com.java42.example.code;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
public class CpfJFrame42 extends JFrame {
public static int GAP = 5;
public static int MIN = 1;
public static final int OPEN = 0x01;
public static final int CLOSE = 0x02;
private JDialog jWindow = null;
private final JPanel basePanel;
private final int w;
private final int h;
private final Object lock = new Object();
private final boolean useSlideButton = true;
private boolean isSlideInProgress = false;
private final JPanel glassPane;
{
glassPane = new JPanel();
glassPane.setOpaque(false);
glassPane.addMouseListener(new MouseAdapter() {
});
glassPane.addMouseMotionListener(new MouseMotionAdapter() {
});
glassPane.addKeyListener(new KeyAdapter() {
});
}
public CpfJFrame42(final Component component, final int w, final int h) {
this.w = w;
this.h = h;
component.setSize(w, h);
addComponentListener(new ComponentListener() {
#Override
public void componentShown(final ComponentEvent e) {
}
#Override
public void componentResized(final ComponentEvent e) {
locateSlider(jWindow);
}
#Override
public void componentMoved(final ComponentEvent e) {
locateSlider(jWindow);
}
#Override
public void componentHidden(final ComponentEvent e) {
}
});
jWindow = new JDialog(this) {
#Override
public void doLayout() {
if (isSlideInProgress) {
}
else {
super.doLayout();
}
}
};
jWindow.setModal(false);
jWindow.setUndecorated(true);
jWindow.setSize(component.getWidth(), component.getHeight());
jWindow.getContentPane().add(component);
locateSlider(jWindow);
jWindow.setVisible(true);
if (useSlideButton) {
basePanel = new JPanel();
basePanel.setLayout(new BorderLayout());
final JPanel statusPanel = new JPanel();
basePanel.add(statusPanel, BorderLayout.SOUTH);
statusPanel.add(new JButton("Open") {
private static final long serialVersionUID = 9204819004142223529L;
{
setMargin(new Insets(0, 0, 0, 0));
}
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slide(OPEN);
}
});
}
});
statusPanel.add(new JButton("Close") {
{
setMargin(new Insets(0, 0, 0, 0));
}
private static final long serialVersionUID = 9204819004142223529L;
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slide(CLOSE);
}
});
}
});
{
//final BufferedImage bufferedImage = ImageFactory.getInstance().createTestImage(200, false);
//final ImageIcon icon = new ImageIcon(bufferedImage);
//basePanel.add(new JButton(icon), BorderLayout.CENTER);
}
getContentPane().add(basePanel);
}
}
private void locateSlider(final JDialog jWindow) {
if (jWindow != null) {
final int x = getLocation().x + getWidth() + GAP;
final int y = getLocation().y + 10;
jWindow.setLocation(x, y);
}
}
private void enableUserInput() {
getGlassPane().setVisible(false);
}
private void disableUserInput() {
setGlassPane(glassPane);
}
public void slide(final int slideType) {
if (!isSlideInProgress) {
isSlideInProgress = true;
final Thread t0 = new Thread(new Runnable() {
#Override
public void run() {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
disableUserInput();
slide(true, slideType);
enableUserInput();
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
isSlideInProgress = false;
}
});
t0.setDaemon(true);
t0.start();
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
private void slide(final boolean useLoop, final int slideType) {
synchronized (lock) {
for (int x = 0; x < w; x += 25) {
if (slideType == OPEN) {
jWindow.setSize(x, h);
}
else {
jWindow.setSize(getWidth() - x, h);
}
jWindow.repaint();
try {
Thread.sleep(42);
} catch (final Exception e) {
e.printStackTrace();
}
}
if (slideType == OPEN) {
jWindow.setSize(w, h);
}
else {
jWindow.setSize(MIN, h);
}
jWindow.repaint();
}
}
}

Animate bg color with hsb model Java

I'm fairly new to java, so i don't think I have this fairly close to right, but I can seem to find any other help with this. Basically, I'm trying to animate a jPanel's background color so that it's hue (I'm using an hsb color model) changes. sort of like this: https://kahoot.it/#/ notice how the color kinda floats from one to another. Here is my code that I have so far:
public void animate(){
for(float i=.001f;i<1f;i+=.001f){
jPanel1.setBackground(Color.getHSBColor(i, .53f, .97f));
try{
Thread.sleep(5L);
}catch(InterruptedException ex){
}
System.out.println(i);
}
}
now i know this probably isn't right, but the loop works fine, the only problem is that the jPanel doesn't "update" until the loop is finished. Sorry all for being a huge noob at stuff like this, and thanks for any responses
The problem is that you are blocking the event dispatch thread, so no drawing can happen. Use a swing Timer instead of sleeping. A running example of changing HSB colors:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ColorCycle {
private static class ColorPanel extends JPanel {
private final float stepSize;
private final Timer timer;
private int index;
ColorPanel(final int steps, int fps) {
stepSize = 1f / steps;
timer = new Timer(1000 / fps, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
index++;
if (index > steps) {
index = 0;
}
repaint();
}
});
}
void start() {
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.getHSBColor(index * stepSize, 1f, 1f));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Colors");
ColorPanel panel = new ColorPanel(300, 20);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
panel.start();
}
});
}
}
Works for me...
import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class HsbBackground {
public static void main(String[] args) throws Exception {
new HsbBackground();
}
private JPanel jPanel1 = new JPanel();
public HsbBackground() throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
JFrame jFrame = new JFrame();
jFrame.setContentPane(jPanel1);
jFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jFrame.setSize(400, 300);
jFrame.setVisible(true);
}
});
animate();
}
public void animate() {
for (float i = .001f; i < 1f; i += .001f) {
final float j = i;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jPanel1.setBackground(Color.getHSBColor(j, .53f, .97f));
}
});
try {
Thread.sleep(5L);
} catch (InterruptedException ex) {
}
System.out.println(i);
}
}
}
Make sure, that you call setVisible of your frame before you start your loop.
PS: I updated the code, so that GUI changes are all made from the event dispatching thread. The code still works fine.

How can I avoid flicker when resizing a Swing window?

I have a dialog where additional controls cause the dialog to resize when they appear. One day I will probably find a way to animate that, but for now I'm content with it just resizing. Problem is, it flickers.
I reduced the problem to a test:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Shows flickering when resizing a dialog.
*/
public class FlickerTest extends FakeJDialog
{
public FlickerTest()
{
super((Window) null, "Flicker Test");
JButton button = new JButton("Bigger!");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
Window window = SwingUtilities.getWindowAncestor((Component) event.getSource());
window.setSize(window.getWidth(), window.getHeight() + 20);
}
});
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
contentPane.add(button, BorderLayout.PAGE_START);
JRootPane rootPane = new JRootPane();
rootPane.setContentPane(contentPane);
add(rootPane);
setResizable(false);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) throws Exception
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FlickerTest().setVisible(true);
}
});
}
}
Each time I click the button, the window changes size. For a noticeable amount of time, the bottom of the dialog goes black. By recording my screen, I was able to get a screenshot demonstrating it:
How can I avoid this?
Further investigation:
The following subclass of Dialog exhibits the same flickering as JDialog:
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Window;
import javax.swing.JLayeredPane;
import javax.swing.JRootPane;
import javax.swing.RootPaneContainer;
/**
* Minimal subclass of Dialog required to cause the flickering.
* If you comment out "implements RootPaneContainer", the flickering goes away.
*/
public class FakeJDialog extends Dialog implements RootPaneContainer
{
public FakeJDialog(Window owner, String title)
{
super(owner, title, Dialog.ModalityType.MODELESS);
}
public JRootPane getRootPane()
{
throw new UnsupportedOperationException();
}
public Container getContentPane()
{
throw new UnsupportedOperationException();
}
public void setContentPane(Container contentPane)
{
throw new UnsupportedOperationException();
}
public JLayeredPane getLayeredPane()
{
throw new UnsupportedOperationException();
}
public void setLayeredPane(JLayeredPane layeredPane)
{
throw new UnsupportedOperationException();
}
public Component getGlassPane()
{
throw new UnsupportedOperationException();
}
public void setGlassPane(Component glassPane)
{
throw new UnsupportedOperationException();
}
}
I find this kind of interesting, because merely commenting out the implements RootPaneContainer is somehow enough to completely change the behaviour. Something in Swing or AWT is obviously looking for this interface and treating those components specially. So this suggests that no subclass of JDialog would avoid the issue.
I don't believe there is a way around this with JDialog. However, java.awt.Dialog doesn't have this issue.
Try this, i have made an example which removes flickering almost completely
in addition u will get well-marked resize corner
/*
* resizing swing trick in Win7+Aero demo
* #author: s1w_
*/
import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
class ResizeHookDemo extends JDialog {
private final static int width = 580, height = 350;
private final JFileChooser fc;
private java.awt.geom.GeneralPath gp;
public ResizeHookDemo() {
super((JDialog)null, "Choose File", true);
fc = new JFileChooser() {
#Override
public void paint(Graphics g) {
super.paint(g);
int w = getWidth();
int h = getHeight();
g.setColor(new Color(150, 150, 150, 200));
g.drawLine(w-7, h, w, h-7);
g.drawLine(w-11, h, w, h-11);
g.drawLine(w-15, h, w, h-15);
gp = new java.awt.geom.GeneralPath();
gp.moveTo(w-17, h);
gp.lineTo(w, h-17);
gp.lineTo(w, h);
gp.closePath();
}
};
fc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("CancelSelection")) {
setVisible(false);
// action...
}
else if (e.getActionCommand().equals("ApproveSelection")) {
setVisible(false);
// action...
}
}
});
MouseInputListener resizeHook = new MouseInputAdapter() {
private Point startPos = null;
public void mousePressed(MouseEvent e) {
if (gp.contains(e.getPoint()))
startPos = new Point(getWidth()-e.getX(), getHeight()-e.getY());
}
public void mouseReleased(MouseEvent mouseEvent) {
startPos = null;
}
public void mouseMoved(MouseEvent e) {
if (gp.contains(e.getPoint()))
setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
else
setCursor(Cursor.getDefaultCursor());
}
public void mouseDragged(MouseEvent e) {
if (startPos != null) {
int dx = e.getX() + startPos.x;
int dy = e.getY() + startPos.y;
setSize(dx, dy);
repaint();
}
}
};
fc.addMouseMotionListener(resizeHook);
fc.addMouseListener(resizeHook);
fc.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 20));
add(fc);
setResizable(false);
setMinimumSize(new Dimension(width, height));
setDefaultCloseOperation(HIDE_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String args[]) {
System.out.println("Starting demo...");
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ResizeHookDemo().setVisible(true);
}
});
}
}

Categories

Resources