loadingLab=new JLabel("The name is being saved..");
loadPanel.add(loadingLab);
submitBttn=new JButton("Submit");
submitBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Submit Button Clicked!!");
try {
//something is wrong in here as it throws an exception
//what is wrong?
frame.setUndecorated(false);
frame.setOpacity(0.55f);
//when above both lines are commented, the code works fine
//but doesnt have transparency
frame.add(loadPanel,BorderLayout.SOUTH);
frame.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
I am trying to display transparent JFrame when "submit" button is clicked which displays panel with a JLabel...
I have tried using setOpacity(0.55f), but it throws exception.. what am i doing wrong?
Unfortunately I think there's no way to keep the system window decoration, you will probably have to go with the default one. Since I'm not 100% sure if you want to toggle the opacity of the whole frame or just the frame's background, I've included both functions in my example. (mKorbels answer help you more if you don't want to have a decoration)
Code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
Color defaultBackground = getBackground();
float defaultOpacity = getOpacity();
JToggleButton button1 = new JToggleButton("Toggle background transparency");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button1.isSelected()) {
setBackground(new Color(defaultBackground.getRed(), defaultBackground.getGreen(),
defaultBackground.getBlue(), 150));
} else {
setBackground(defaultBackground);
}
}
});
JToggleButton button2 = new JToggleButton("Toggle opacity of whole frame");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
if (button2.isSelected()) {
setOpacity(0.55f);
} else {
setOpacity(defaultOpacity);
}
setVisible(true);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button1);
getContentPane().add(button2);
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
});
}
}
Picture of frame with no togglebutton selected:
Picture of frame with the first togglebutton selected:
Picture of frame with the second togglebutton selected:
#Programmer007 wrote - the exception is "
java.awt.IllegalComponentStateException: The frame is displayable."
please where I can't see any, for more info about the possible exceptions to read,
as mentioned no idea, everything is about your effort, transformed to the SSCCE / MCVE, short, runnable, compilable
.
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GenericForm extends JDialog {
private static final long serialVersionUID = 1L;
private Timer timer;
private JDialog dialog = new JDialog();
private int count = 0;
public GenericForm() {
dialog.setSize(400, 300);
dialog.setUndecorated(true);
dialog.setOpacity(0.5f);
dialog.setName("Toggling with opacity");
dialog.getContentPane().setBackground(Color.RED);
dialog.setLocation(150, 150);
dialog.setVisible(true);
timer = new javax.swing.Timer(1500, updateCol());
timer.setRepeats(true);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Hello World") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
boolean bol = dialog.getOpacity() < 0.55f;
count += 1;
if (count < 10) {
if (bol) {
dialog.setOpacity(1.0f);
dialog.getContentPane().setBackground(Color.WHITE);
} else {
dialog.setOpacity(0.5f);
dialog.getContentPane().setBackground(Color.RED);
}
} else {
System.exit(0);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GenericForm();
}
});
}
}
Related
I have simple Java Swing application. I want before close main window get confirmation from user.
There is my code:
package client_interface;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MainWindow {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainWindow() {
initialize();
}
private void setFrameSize(JFrame frame) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
frame.setBounds(new Rectangle(width/4, height/4, width/2, height/2));
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
private void initialize() {
frame = new JFrame("Test");
setFrameSize(frame);
frame.addWindowFocusListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
}
}
But seems that frame.addWindowFocusListener doesn't work.
Please show me the correct way to add event windowClosing to my frame.
Replace
frame.addWindowFocusListener(new WindowAdapter() {
with
frame.addWindowListener(new WindowAdapter() {
The first takes a WindowFocusListener which will be called when the window either gains or loses focus.
In my application I have a JTable where I mapped a Key event. The source:
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextColumnCell");
getActionMap().put("selectNextColumnCell", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
}
});
}
But this action is only called when I press the enter key and don't release it. But I need call this action every time when the user type the enter key.
please see my syntax for put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER....
for example
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FullScreen {
private static final long serialVersionUID = 1L;
private GraphicsDevice device;
private JButton button = new JButton("Close Meeee");
private JPanel myPanel = new JPanel();
private JFrame frame = new JFrame();
public FullScreen() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
myPanel.setFocusable(true);
myPanel.add(button);
frame.add(myPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
frame.getRootPane().getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
exitFullScreen();
}
});
enterFullScreen();
frame.setVisible(true);
// code line for #MOD
// from http://stackoverflow.com/questions/15152297/how-to-get-extendedstate-width-of-jframe
Runnable doRun = new Runnable() {
#Override
public void run() {
System.out.println(frame.getBounds());
}
};
SwingUtilities.invokeLater(doRun);
}
private void enterFullScreen() {
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = graphicsEnvironment.getDefaultScreenDevice();
if (device.isFullScreenSupported()) {
device.setFullScreenWindow(frame);
frame.validate();
}
}
private void exitFullScreen() {
device.setFullScreenWindow(null);
myPanel.setPreferredSize(new Dimension(400, 300));
frame.pack();
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
FullScreen fullScreen = new FullScreen();
}
};
SwingUtilities.invokeLater(doRun);
}
}
I wanted to know if there's any easy way to delete the content (text) from a JLabel after 5 seconds. Is that possible? Because I have a JLabel in a JFrame and it shows some internal errors from the program I'm coding and I want the JLabel to show the message for a couple of seconds and then go to blank. Any ideas?
Simplest solution is to use a Swing Timer. It will prevent freezing the GUI and ensure proper Thread access (ie, UI modification is performed on the EDT).
Small demo example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLabelDelete {
private JFrame frame;
private JLabel label;
protected void initUI() {
frame = new JFrame(TestLabelDelete.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Some text to delete in 5 seconds");
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer t = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(null);
}
});
t.setRepeats(false);
t.start();
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestLabelDelete testLogin = new TestLabelDelete();
testLogin.initUI();
}
});
}
}
Use Timer. Please see my example.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class SourceCodeProgram {
private static void createAndShowGUI() {
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setMinimumSize(new Dimension(200, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the ubiquitous "Hello World" label.
final JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
// Display the window.
frame.pack();
frame.setVisible(true);
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Clear text or whatever you want
label.setText("New text");
}
});
// start Tick-Tack
timer.start();
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Or you can write a separate class, which can clean label.
class JLabelCleaner {
private JLabel label;
private int waitSeconds;
public JLabelCleaner(int waitSeconds, JLabel label) {
this.label = label;
this.waitSeconds = waitSeconds;
}
public void startCountdownFromNow() {
Timer timer = new Timer(waitSeconds * 1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText("");
}
});
timer.start();
}
}
Now, you can use it whenever you need it in this way:
new JLabelCleaner(5, label).startCountdownFromNow();
Also see:
How to Use Swing Timers
There is an easy solution to this.
JLabel label = new JLabel("error text");
Thread.sleep(5000);
label.setText("");
Hope this helps!
EDIT: If you don't want the program to freeze for 5 secs you'll have to put this inside a Runnable.
It's very easy to do... just create a new thread and write code to clear text on label, and make that thread to sleep for 5sec and then start it.
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class LabelThread {
private JLabel textLabel;
public LabelThread() {
try {
JFrame frame = new JFrame("Label");
frame.setSize(500, 500);
textLabel = new JLabel("Hiiii.... Kill me");
frame.setContentPane(textLabel);
frame.setVisible(true);
MyThread thread = new MyThread();
MyThread.sleep(5000);
thread.start();
} catch (InterruptedException ex) {
}
}
class MyThread extends Thread{
#Override
public void run() {
System.out.print("Running thread");
textLabel.setText("");
}
}
public static void main(String args[]){
LabelThread labelThread = new LabelThread();
}
}
Designing a questionary, the scope of answer can be elected by radioButtons.
To display a greater clickable area (the application is for touchscreen), I layed icon_1 over the radiobuttons.
Every mouseclick can change the displayed icon to icon_2 and permantly vice versa.
I am sorry, using
jRadioButtonActionPerformed
ImageIcon o_ButtonIcon = new ImageIcon ("....")
jRadioButton.setIcon(Icon m_ButtonIcon).
I get no changing, clickable image.
Can you please give me a helping hand?
Seems to be working fine.
Post an SSCCE to show specific problems.
Here is example ( i do not recommend getScaledInstance(..) just used it for quick example)
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class Test {
private ImageIcon ii1;
private ImageIcon ii2;
private JRadioButton jrb = new JRadioButton("Click me :)");
private JFrame frame = new JFrame();
public Test() {
try {
ii1 = new ImageIcon(ImageIO.read(new URL("http://cdn.macrumors.com/article/2010/09/03/145454-itunes_10_icon.jpg")).getScaledInstance(48, 48, Image.SCALE_SMOOTH));
ii2 = new ImageIcon(ImageIO.read(new URL("http://www.quarktet.com/Icon-small.jpg")).getScaledInstance(48, 48, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
initComponents();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jrb.setIcon(ii1);
jrb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (jrb.getIcon() == ii1) {
jrb.setIcon(ii2);
} else {
jrb.setIcon(ii1);
}
}
});
frame.add(jrb);
frame.pack();
frame.setVisible(true);
}
}
I've made my own SwingWorker example to get familiar with how it works.
What I'm wanting to do is the following:
When the button is clicked I want a progress bar appear until the task is done I want to simply remove the progress bar and add a string to the dialog.
When the button is clicked, the progress bar comes up but never goes away. (never removes the progress bar after 10 seconds and never places the label up)
Here is an SSCCE:
package swingtesting;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingTesting {
/**
* Creates a frame that will hold a simple button to make use of SwingWorker
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();
}
});
button.setText("Test Me");
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
}
class GuiWorker extends SwingWorker<Integer, Integer> {
/*
* This should just create a frame that will hold a progress bar until the
* work is done. Once done, it should remove the progress bar from the dialog
* and add a label saying the task complete.
*/
private JFrame frame = new JFrame();
private JDialog dialog = new JDialog(frame, "Swingworker test", true);
private JProgressBar progressBar = new JProgressBar();
public GuiWorker() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
dialog.getContentPane().add(progressBar);
dialog.pack();
dialog.setVisible(true);
}
#Override
protected Integer doInBackground() throws Exception {
Thread.sleep(10000);
return 0;
}
#Override
protected void done() {
JLabel label = new JLabel("Task Complete");
dialog.getContentPane().remove(progressBar);
dialog.getContentPane().add(label);
}
}
Here an updated version of your code which works
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingTesting {
public static void main(String[] args) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();
}
});
button.setText("Test Me");
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
} );
}
}
class GuiWorker extends SwingWorker<Integer, Integer> {
/*
* This should just create a frame that will hold a progress bar until the
* work is done. Once done, it should remove the progress bar from the dialog
* and add a label saying the task complete.
*/
private JFrame frame = new JFrame();
private JDialog dialog = new JDialog(frame, "Swingworker test", true);
private JProgressBar progressBar = new JProgressBar();
public GuiWorker() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
dialog.getContentPane().add(progressBar);
dialog.pack();
dialog.setModal( false );
dialog.setVisible(true);
}
#Override
protected Integer doInBackground() throws Exception {
System.out.println( "GuiWorker.doInBackground" );
Thread.sleep(1000);
return 0;
}
#Override
protected void done() {
System.out.println("done");
JLabel label = new JLabel("Task Complete");
dialog.getContentPane().remove(progressBar);
dialog.getContentPane().add(label);
dialog.getContentPane().validate();
}
}
Key point is that setting a model dialog visible blocks until the dialog is disposed. So making it non-modal fixed it + the validate call on the content pane when you switch components. I also adjusted your main method to run on the EDT, and added some System.out calls. If you remove the setModal( false ) call you will see those statements are not printed until you close the dialog
There's no need to make the dialog non-modal. Simply display the dialog after starting the SwingWorker. This can be done either from the calling class, the one executing the SwingWorker, by first calling execute, and then showing the dialog, or it can be done from the SwingWorker, but if from the latter, you'll have to make your own pseudo-execute method that calls super's execute, and then shows the dialog. Note that you can't override execute() itself since it's final.
For example...
import java.awt.CardLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwingTesting2 {
private static void createAndShowGui() {
final JFrame frame = new JFrame("SwingTesting2");
final JDialog dialog = new JDialog(frame, "Dialog",
ModalityType.APPLICATION_MODAL);
final DialogPanel dialogPanel = new DialogPanel();
dialog.getContentPane().add(dialogPanel.getMainPanel());
dialog.pack();
dialog.setLocationRelativeTo(frame);
JButton button = new JButton(new AbstractAction("Test Me") {
#Override
public void actionPerformed(ActionEvent actEvt) {
final GuiWorker2 guiWorker = new GuiWorker2();
guiWorker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getPropertyName().equals("state")) {
if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
try {
dialogPanel.done(guiWorker.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} else if (pcEvt.getPropertyName().equals("progress")) {
dialogPanel.setProgress((Integer)pcEvt.getNewValue());
}
}
});
guiWorker.execute();
dialogPanel.start();
dialog.setVisible(true);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GuiWorker2 extends SwingWorker<Integer, Integer> {
private static final int MAX_COUNT = 20;
private static final long SLEEP_TIME = 100;
private int count = 0;
#Override
protected Integer doInBackground() throws Exception {
while (count < MAX_COUNT) {
Thread.sleep(SLEEP_TIME);
count++;
setProgress((100 * count) / MAX_COUNT);
}
return count;
}
}
#SuppressWarnings("serial")
class DialogPanel {
public static final String PROGRESS_BAR = "Progress Bar";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 2000;
private CardLayout cardLayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardLayout);
private JLabel doneLabel = new JLabel("Done", JLabel.CENTER);
private JProgressBar progressBar = new JProgressBar();
public DialogPanel() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(false);
mainPanel.add(progressBar, PROGRESS_BAR);
mainPanel.add(doneLabel, DONE);
}
public void setProgress(Integer newValue) {
progressBar.setValue(newValue);
}
public void start() {
cardLayout.show(mainPanel, PROGRESS_BAR);
progressBar.setValue(0);
}
public void done(int countValue) {
doneLabel.setText(DONE + ". Count: " + countValue);
cardLayout.show(mainPanel, DONE);
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
}){{setRepeats(false);}}.start();
}
public JPanel getMainPanel() {
return mainPanel;
}
}