How to update look and feel clean seperate in a class? - java

I want to update my look and feel by JRadioButtonMenuItem. And I searching in Stackoverflow but what I find was a big bunch of code in 1 class. For me as a beginner its easier to seperate function in a special class.
That is my Frame-Class.
public class CalenderFrame extends JFrame {
public CalenderFrame() throws HeadlessException {
createFrame();
}
public void createFrame() {
setJMenuBar(CalenderMenuBar.getInstance().createMenu());
setTitle("Calender");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 300));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
And that is my MenueBar Class. I just give a short one of Code that is specific for this question. This class is an Singleton.
public JMenuBar createMenu() {
JMenu lookAndFeelMenu = new JMenu("Look & Feel");
JRadioButtonMenuItem lAndFWindowsItem = new JRadioButtonMenuItem("Windows",true);
lAndFWindowsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lAndFWindowsItem) {
lAndFAction(1);
}
}
});
JRadioButtonMenuItem lAndFMetalItem = new JRadioButtonMenuItem("Metal",false);
lAndFMetalItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lAndFMetalItem) {
lAndFAction(2);
}
}
});
JRadioButtonMenuItem lAndFMotifItem = new JRadioButtonMenuItem("Motif", false);
lAndFMotifItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lAndFMotifItem) {
lAndFAction(3);
}
}
});
ButtonGroup group = new ButtonGroup();
group.add(lAndFWindowsItem);
group.add(lAndFMetalItem);
group.add(lAndFMotifItem);
lookAndFeelMenu.add(lAndFWindowsItem);
lookAndFeelMenu.add(lAndFMetalItem);
lookAndFeelMenu.add(lAndFMotifItem);
}
public void lAndFAction(int counter) {
try {
String plaf = "";
if (counter == 1) {
plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
} else if (counter == 2) {
plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if (counter == 3) {
plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
}
UIManager.setLookAndFeel(plaf);
//SwingUtilities.updateComponentTreeUI(this);
} catch (UnsupportedLookAndFeelException ue) {
System.err.println(ue.toString());
} catch (ClassNotFoundException ce) {
System.err.println(ce.toString());
} catch (InstantiationException ie) {
System.err.println(ie.toString());
} catch (IllegalAccessException iae) {
System.err.println(iae.toString());
}
}
}
I hope you guys can help me.

I'm not sure what your problem actually is. But, you must update your components after changing the LaF. According to the Look and Feel Documentation:
Changing the Look and Feel After Startup
You can change the L&F with setLookAndFeel even after the program's
GUI is visible. To make existing components reflect the new L&F,
invoke the SwingUtilities updateComponentTreeUI method once per
top-level container. Then you might wish to resize each top-level
container to reflect the new sizes of its contained components. For
example:
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
Therefore, you would need a reference to the frame holding the components in your UI. An idea would be doing something like:
public class CalendarMenuBar {
// Add this field to tour factory
private static JFrame frameThatWillBeUpdated;
// ... (Your code goes here)
// update this method to receive the reference of the frame which will
// need to be refreshed (update the GUI)
public JMenuBar createMenu(JFrame frame) {
// sets the reference for the frame
frameThatWillBeUpdated = frame;
// ... (the rest of your code for this method)
}
// ...
// Update this method to refresh the frame
public void lAndFAction(int counter) {
try{
// ... (your code)
// Set the LaF
UIManager.setLookAndFeel(plaf);
// Update the component tree (frame and its children)
SwingUtilities.updateComponentTreeUI(frameThatWillBeUpdated);
// repack to resize
frame.pack();
} catch(Exception ex){
// Your catches
}
}
}
And here is how you use it when creating your frame (inside your CalenderFrame class):
public void createFrame() {
// use this frame as reference
setJMenuBar(CalenderMenuBar.getInstance().createMenu(this));
// ... (your code goes here)
}

Related

Blank JFrame when program is run

I am an absolute beginner in coding. I would like to know why is my Jframe blank when run, how do I fix it. From what I have research on the internet it seems that I should put the component inside the JFrame as it is empty but how do I do it
My Code
public class Video extends JFrame
{
public static void main(String[] args) throws URISyntaxException {
final URI uri = new URI("https://www.youtube.com/watch?v=rl0YiZjTqpw");
class OpenUrlAction implements ActionListener
{
#Override public void actionPerformed(ActionEvent e) {
open(uri);
}
}
JFrame frame = new JFrame("Links");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(410, 400);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JButton btnclickHereTo = new JButton();
btnclickHereTo.setText("<HTML> <FONT color=\"#000099\"><U>Click Here To Watch Video</U></FONT>");
btnclickHereTo.setHorizontalAlignment(SwingConstants.LEFT);
btnclickHereTo.setBorderPainted(false);
btnclickHereTo.setOpaque(false);
btnclickHereTo.setBackground(Color.WHITE);
btnclickHereTo.setToolTipText(uri.toString());
btnclickHereTo.addActionListener(new OpenUrlAction());
container.add(btnclickHereTo);
frame.setVisible(true);
}
private static void open(URI uri)
{
if (Desktop.isDesktopSupported())
{
try
{
Desktop.getDesktop().browse(uri);
}
catch (IOException e)
{ /* TODO: error handling */ }
}
else
{ /* TODO: error handling */ }
}
}
public void setVisible(boolean b) {
Why would you override the setVisible(...) method of your frame? There is no reason to do that.
I am an absolute beginner in coding
Start with something basic, like the example from the Swing tutorial on How to Make Frames.
Keep a reference to the tutorial link handy since it contains information and examples for all Swing basics.

How to check if a JFrame is open by checking it's one of the components are visible

I have this code sample in a separate jDialog (jDialog is in the same package as that of JFrame) which used to check (using a Thread) if the jCheckBox1 in the jFrame is whether visible or not. JDialog is set to visible by clicking a JLabel (Change Password) in JFrame. I have not set the visibility of the JFrame even to false even after I click on the Change Password JLabel.
The problem I encountered is that even if the JFrame is not visible i.e when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible" and I'm more than sure that the jFrame is not visible and not running.
This is the code snippet (Thread) I have used to check the visibility of the JFrame's jCheckBox1:
LockOptions lock = new LockOptions();
private void setLocation2() {
new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lock.jCheckBox1.isVisible()) {
System.out.println("Visible");
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
And this is the Code I have written in JFrame's Change Password JLabel:
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {
Container c = new ChangePassword(this, rootPaneCheckingEnabled);
if (!c.isShowing()) {
c.setVisible(true);
hideMeToSystemTray();
this.requestFocusInWindow();
}
}
But when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible"
I have attached a Screenshots of both JFrame and JDialog
JFrame containing jCheckBox1
JDialog:
OK, let's have the simplest possible example.
The following code creates a main frame having a button to create a new frame of class LockOptionsWindow, which extends JFrame.
The class FrameDemo implements Runnable. So can it be accessed on the event dispatching thread using SwingUtilities.invokeLater as mentioned in Swing's Threading Policy. So it is possible creating a new thread checklockoptionswindow which then can check whether the new window created by the button is visible or not visible.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameDemo extends WindowAdapter implements ActionListener, Runnable {
private LockOptionsWindow lockoptionswindow;
private Thread checklockoptionswindow = new Thread();
private void showLockOptionsWindow() {
if (lockoptionswindow != null && lockoptionswindow.isDisplayable()) {
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
} else {
lockoptionswindow = new LockOptionsWindow();
lockoptionswindow.setSize(new Dimension(300, 100));
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
}
}
private void startCheckLockOptionsWindow() {
if (!checklockoptionswindow.isAlive()) {
checklockoptionswindow = new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lockoptionswindow.isVisible()) {
if (lockoptionswindow.getExtendedState() == Frame.ICONIFIED) {
System.out.println("Visible iconified");
} else {
System.out.print("Visible on screen ");
int x = lockoptionswindow.getLocation().x;
int y = lockoptionswindow.getLocation().y;
System.out.println("at position " + x + ", " + y);
}
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
checklockoptionswindow.start();
}
}
public void actionPerformed(ActionEvent e) {
showLockOptionsWindow();
startCheckLockOptionsWindow();
}
public void run() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Show LockOptions frame");
button.addActionListener(this);
Container contentPane = frame.getContentPane();
contentPane.add(button);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new FrameDemo());
}
class LockOptionsWindow extends JFrame {
public LockOptionsWindow() {
super("LockOptions frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
Edited to determine whether the LockOptionsWindow is visible iconified only or is really showed as window on the screen.

Extension of JDialog (hidden?) not showing up in front of parent JFrame?

I have an application I'm making for a game to automatically update a game client.
Once you press Launch, it will open up my DownloadFrame (extends JDialog), and will look like this:
If you click the icon for the application in the taskbar, (maybe Windows 8 is the problem?) it will minimize the application like usual. However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent. It looks like this:
Here's my code for my extension of JDialog. Apologies in advance for it being messy.
public class DownloadFrame extends JDialog implements Runnable {
private static final long serialVersionUID = -8764984599528942303L;
private Background frame;
private ImageIcon[] gifs;
private JLabel spinner;
public DownloadFrame() {
super(Loader.application, false);
setLayout(null);
setUndecorated(true);
setAutoRequestFocus(true);
new Thread(this).start();
generateBackground();
generateButton();
generateGif();
}
private void generateBackground() {
frame = new Background("sub_background.png");
setSize(frame.getWidth(), frame.getHeight());
setBackground(new Color(1.0f, 1.0f, 1.0f, 0.0f));
setLocationRelativeTo(null);
setLocation(this.getX(), this.getY() + 5);
setLayout(null);
setContentPane(frame);
}
private void generateGif() {
gifs = Utils.generateGifImages();
spinner = new JLabel(gifs[0]);
spinner.setBounds(70, 30, gifs[0].getIconWidth(), gifs[0].getIconHeight());
add(spinner);
}
private HoverableButton cancel;
public HoverableButton getCancelButton() {
return cancel;
}
private void generateButton() {
cancel = new HoverableButton(Settings.CANCEL_BUTTON, 75, 145);
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
/*
* TODO -
* stop the download in progress
*/
for (HoverableButton button : Loader.application.getPrimaryButtons()) {
button.setActive(true);
button.setVisible(true);
}
dispose();
}
});
add(cancel);
}
private int cycleCount;
private void cycleGif() {
if (spinner == null) {
return;
}
cycleCount++;
if (cycleCount > 7) {
cycleCount = 0;
}
spinner.setIcon(gifs[cycleCount]);
}
#Override
public void run() {
while (true) {
cycleGif();
try {
Thread.sleep(100L);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
In case it's needed, here's my usage of it. Most of the stuff can be ignored I'm sure, it's simply there to hide the four buttons while the download is in progress.
((HoverableButton) components[2]).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
HoverableButton source = (HoverableButton) components[2];
if (source.isActive()) {
try {
Thread.sleep(500L);
} catch (Exception ex) {
ex.printStackTrace();
}
if (panel == null) {
panel = new DownloadFrame();
panel.setVisible(true);
} else {
panel.setVisible(true);
panel.getCancelButton().removeHighlight();
}
for (HoverableButton button : getPrimaryButtons()) {
button.setActive(false);
button.setVisible(false);
button.removeHighlight();
}
/*
* TODO -
* handle checking for updates / downloading updates
*/
}
}
});
However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent
Yes. When you create the JDialog, you need to specify the "owner" JFrame of the dialog in the constructor.
So you must create and make the JFrame and make the frame visible before you create the dialog.

Gui JCombobox Text gets blurred

Recently I have been getting into some Gui programming in Java. I noticed that when I created a JComboBox and tried to display in my gui that the text doesn't come in full. Alot of the time it is blurred, as shown as below. I have tried increasing the size of the GridBagConstraint but it still occurs. This would also happen to the button once I press it as well.
Class 1:
public class load {
private JFrame frame;
public static void main(String args[]) throws InvocationTargetException,
InterruptedException {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
// Create the UI here
load window = new load();
window.frame.setVisible(true);
}
});
}
private void loadGui() {
JButton create = new JButton();
create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
SelectionView a = new SelectionView();
// VVPRIMARY ERROR CURRENTLY VV
// unable to setvisible false without the nextframe losing pixel
frame.setVisible(false);
frame.dispose();
}
});
frame.setSize(400, 400);
frame.add(create);
}
}
Class 2:
public class SelectionView extends JFrame {
public SelectionView() {
// intialize frame
JFrame selection = new JFrame("Sport Selection");
JPanel a = new JPanel();
a.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
selection.setSize(300, 500);
final JComboBox box = createDropdown();
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int value = box.getSelectedIndex();
switch (value) {
case 0:
TableTennisView a = new TableTennisView();
break;
case 1:
BasketBallView b = new BasketBallView();
break;
default:
System.out.println("Nothing");
break;
}
}
});
// create comboBox
a.add(box, c);
a.add(load, c);
selection.add(a);
selection.setVisible(true);
}
/**
* Method CreateDropDown
*
* Creates the dropdown menu for the selection view
*
* #return the dropdown menu used in the view
*/
public JComboBox createDropdown() {
String[] sport = { "Table Tennis", "BasketBall" };
JComboBox cb = new JComboBox(sport);
return cb;
}
}
Make sure you are initialise (and updating) the UI from within the context of the Event Dispatching Thread.
See Initial Threads for more details.
EventQueue.invokeAndWait(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
// Create the UI here
}
});
Also, if possible, call setVisible on the window last, after you have established the basic UI. If the UI is dynamic, you will need to call revalidate and repaint on the parent container that you are adding your components to or consider using a CardLayout
Some video drivers can cause problems on some platforms, if problems persist, consider providing a runnable example which demonstrates your problem. This will result in less confusion and better responses

Unable to set background color of checkbox at runtime

There is a class AgentHome which extends JFrame.
AgentHome has a JPanel rem_panel. Checkboxes are added dynamically into rem_panel…number of checkboxes depending on the number of entries in the database table from where the text to be displayed by the textboxes are read.
AgentHome has an integer variable x and a checkbox arraylist rem_cbarr.
rem_cbarr stores the checkboxes as they are created and added to rem_panel.
I am trying to set the background color of these checkboxes to red when the variable x is set to 1 as the program executes.
I have implemented the TickerBehaviour of JADE framework to check if the variable x is set to 1.
I am unable to set the background color of the checkboxes to red. This is the code I have implemented. Please help. Thanks.
public void setup()
{
Behaviour loop = new TickerBehaviour( this, 2000 )
{
protected void onTick() {
timer();
}
};
addBehaviour( loop );
}
public void timer()
{
AgentHome hm=new AgentHome();
if(hm.x==1)
{
for (int i = hm.rem_cbarr.size()-1; i>=0; i--)
{
JCheckBox cb=hm.rem_cbarr.get(i);
cb.setBackground(Color.red);
hm.rem_panel.revalidate();
hm.rem_panel.repaint();
}
}
}
GUI operations need to be done on the EDT (Event Dispatcher Thread). In java this happens by calling SwingUtilities.invokeLater(Runnable run).
A number of things...
UI components should only ever be updated within the context of the Event Dispatching Thread
You should never perform any action which might block the Event Dispatching Thread (like using loops or Thread#Sleep to try and update the screen)
The Event Dispatching Thread is responsible for dispatching paint updates...
JCheckBox is transparent by default.
public class FlashCheckBox {
public static void main(String[] args) {
new FlashCheckBox();
}
public FlashCheckBox() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(new FlashyCheckBox());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FlashyCheckBox extends JCheckBox {
private final Color defaultBackground;
private int flash;
private Timer flashTimer;
public FlashyCheckBox() {
defaultBackground = getBackground();
flashTimer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
flash++;
if (flash % 5 == 0) {
setOpaque(false);
setBackground(defaultBackground);
flashTimer.stop();
} else if (flash % 2 == 0) {
setBackground(Color.YELLOW);
setOpaque(true);
} else {
setBackground(defaultBackground);
setOpaque(false);
}
repaint();
}
});
flashTimer.setRepeats(true);
flashTimer.setCoalesce(true);
flashTimer.setInitialDelay(0);
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
flashTimer.restart();
}
});
}
}
}

Categories