Gui JCombobox Text gets blurred - java

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

Related

JOptionPane closing array of buttons in showOptionDialog [duplicate]

I need the user to input a name and I want to disable the ok button until some input is given. How can I disable it... ?
JOptionPane allows you to supply a component as the message pane and the controls/options that can be displayed on it.
If you add the correct listeners to the message component, then you should be able to influence the controls that are used as options.
Take a look at JOptionPane.showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue)
Updated
For example...
public class TestOptionPane05 {
public static void main(String[] args) {
new TestOptionPane05();
}
protected JOptionPane getOptionPane(JComponent parent) {
JOptionPane pane = null;
if (!(parent instanceof JOptionPane)) {
pane = getOptionPane((JComponent)parent.getParent());
} else {
pane = (JOptionPane) parent;
}
return pane;
}
public TestOptionPane05() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JButton okay = new JButton("Ok");
okay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(okay);
}
});
okay.setEnabled(false);
final JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(cancel);
}
});
final JTextField field = new JTextField();
field.getDocument().addDocumentListener(new DocumentListener() {
protected void update() {
okay.setEnabled(field.getText().length() > 0);
}
#Override
public void insertUpdate(DocumentEvent e) {
update();
}
#Override
public void removeUpdate(DocumentEvent e) {
update();
}
#Override
public void changedUpdate(DocumentEvent e) {
update();
}
});
JOptionPane.showOptionDialog(
null,
field,
"Get",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
new Object[]{okay, cancel},
okay);
}
});
}
}
As far as I know this is impossible without overriding JOptionPane.
Try searching for swinglabs or jGoodies libraries for Java. They have built in type for the thing you need.
I need the user to input a name and I want to disable the ok button until some input is given.
wrong way to do it.
i.e. define 'what is a name' = can be anything.
so, what you're, in effect, trying to do is not accept an empty string,
and you do that as an error-check 'after' the OK button has been pressed.
if empty - pop-up error message/repeat input request/confirm cancel/whatever you want to do

Restoring JFrame blinks, and set it on top of everything using WindowListener

I know there are already lot of thread available for this topic. I have already visited almost all of em, this one, this one, this one, also this one and this one.But didn't solve my issue.
My problem is different over here when I try to restore the JFrame it blinks, and didn't come on top of everything. I have already run this code in Ubuntu and it worked like a charm on ubuntu. frame.setAlwaysOnTop(true); works absolutely fine on ubuntu.
To solve this issue in windows I tried to use WindowsListener,
But in windows 7 it blinks and didn't come on top of every windows. What I think is that it's trying to come on top of everything but may be other application has higher priority than this it goes away. How can I resolve this issue ?
EDIT :
I have two thread over here one thread is authenticating and if it's authenticated it minimized. If not authenticated it should always be on top for authenticating. Even if user switches window by pressing Alt key tab it should again come on top after 2 seconds.
Code for authentication :
public class ScreenLockAndUnlock implements Runnable{
public static JFrame frame;
public static boolean working = false;
private JTextField punch;
public void stop(){
working = false;
}
public void run(){
try{
frame = new JFrame("Protected");
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\four.four-PC\\eclipse-workspace\\optimization\\src\\main\\java\\com\\greycode\\optimization\\finger_PNG6297.png")));
frame.setVisible(true);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
gs.setFullScreenWindow(frame);
frame.validate();
frame.setLayout(new BorderLayout());
punch = new JTextField();
frame.add(punch,BorderLayout.SOUTH);
punch.requestFocus();
punch.addActionListener(action);
}finally{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
private void onTop() throws AWTException{
// TODO Auto-generated method stub
AlwaysOnTop top = new AlwaysOnTop();
new Thread(top).start();
while(true){
try{
frame.setState(Frame.NORMAL);
if(punch.getText().trim()!= null && punch.getText().trim().toLowerCase().equals("true")){
working = true;
top.cancel();
frame.setState(JFrame.ICONIFIED);
Thread.sleep(10000);
top.star();
top = new AlwaysOnTop();
new Thread(top).start();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
Action action = new AbstractAction(){
public void actionPerformed(ActionEvent e){
try{
onTop();
} catch (AWTException e1){
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
This code always look for whether JFrame is on top or not if not authenticated
public class AlwaysOnTop implements Runnable{
boolean cancelled = false;
public void run(){
while(!cancelled){
try{
lookForMinimised();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void cancel(){
this.cancelled = true;
}
public void star(){
this.cancelled = false;
}
public void lookForMinimised() throws InterruptedException{
// TODO Auto-generated method stub
ScreenLockAndUnlock.frame.addWindowStateListener(new WindowStateListener(){
public void windowStateChanged(WindowEvent e){
// TODO Auto-generated method stub
int newState = e.getNewState();
if((newState & Frame.ICONIFIED) == Frame.ICONIFIED){
System.out.println("Frame is minimised");
ScreenLockAndUnlock.frame.setAlwaysOnTop(false);
ScreenLockAndUnlock.frame.setAlwaysOnTop(true);
ScreenLockAndUnlock.frame.setVisible(true);
ScreenLockAndUnlock.frame.toFront();
ScreenLockAndUnlock.frame.requestFocus();
ScreenLockAndUnlock.frame.validate();
ScreenLockAndUnlock.frame.setState(Frame.NORMAL);
}
else if ((newState & Frame.NORMAL) == Frame.NORMAL){
System.out.println("Waiting for authentication ...");
}
}
});
Thread.sleep(2000);
}
}
Main method:
public class Authenticate{
public static void main(String[] args){
Thread displayScreen = new Thread(new ScreenLockAndUnlock());
displayScreen.start();
}
}
Please find a code which depicts the logical functionality that you want.
Also note that this code just depicts the functionality only which are frame restore-minimize, thread and their inter-working.
At the end, it will be you, who have to use the same at appropriate locations as per your need.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
public class TestClass2 extends JFrame {
private JPanel contentPane;
private JTextField textField;
static boolean isAuthenticationStarted = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestClass2 frame = new TestClass2();
frame.setVisible(true);
frame.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
// minimized
if ((e.getNewState() & Frame.ICONIFIED) == Frame.ICONIFIED){
if (!isAuthenticationStarted)
{
// Authentication not started yet and window minimized
frame.setState(Frame.NORMAL);
}
}
// // maximized
// else if ((e.getNewState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH){
//
// }
}
});
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestClass2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
new Thread()
{
public void run()
{
// Start authentication here
isAuthenticationStarted = true;
// if authentication is success show next jframe
// else restore window
// reset the flag only when authentication is successful
// isAuthenticationStarted = false;
// Minimizing frame
setState(Frame.ICONIFIED);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// restoring frame
setState(Frame.NORMAL);
}
}.start();
}
}
});// End listener
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
}
}
Hope this will help you. :-)

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

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)
}

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.

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