Java Swing Location On Screen after Resize - java

I'm trying to keep a JDialog centered inside of a JFrame, regardless if the JFrame is moved or resized.
Essentially, I have a class like (This is not the real code, just an example )
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.Dimension;
import java.awt.Color;
public class HelloWorldSwing extends ComponentAdapter implements AncestorListener {
private JDialog dialog;
private JFrame frame;
#Override
public void componentResized( ComponentEvent event ) {
//This value does not hcange when dragged from the left or right
System.err.println( " Location " + frame.getLocationOnScreen() );
recenter();
}
#Override
public void ancestorAdded( AncestorEvent evt ) {
}
#Override
public void ancestorRemoved( AncestorEvent evt ) {
}
#Override
public void ancestorMoved( AncestorEvent evt ) {
//This value does not hcange when dragged from the left or right
System.err.println( " Location " + frame.getLocationOnScreen() );
recenter();
}
private void recenter() {
dialog.setLocationRelativeTo( frame.getRootPane() );
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getRootPane().addAncestorListener( this );
frame.getRootPane().setBackground( Color.WHITE );
frame.addComponentListener( this );
frame.setMinimumSize( new Dimension( 500, 500 ) );
frame.setMaximumSize( new Dimension( 500, 500 ) );
dialog = new JDialog();
dialog.setResizable( true );
dialog.setAlwaysOnTop( true );
dialog.setVisible( true );
dialog.setMaximumSize( new Dimension( 200, 200 ) );
dialog.setMinimumSize( new Dimension( 200, 200 ) );
//Display the window.
frame.pack();
frame.setVisible(true);
}
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() {
HelloWorldSwing swing = new HelloWorldSwing();
swing.createAndShowGUI();
}
});
}
}
When the JFrame is resized from the left or the top, the location on the screen changes, but the getLocationOnScreen() does not change it's result. It seems like the getLocationOnScreen should change as the top left corner has changed due to a resize.
What am I missing ? Thanks.
Update ::
This code seems to run fine on Windows, but does not run correctly on Fedora 21, java 7

Related

How would I refresh this panel

I want to make a kind of digital clock which you can activate by using enter to kind of refresh the clock display, for that I use this method:
private static void GUI(String time, int action){
JLabel textLabel = new JLabel(time);
JPanel panel = new JPanel();
JFrame enterMessage = new JFrame("Tester");
if (action == 1){
enterMessage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
enterMessage.setSize(190, 80);
enterMessage.setVisible(true);
panel.setBackground(Color.WHITE);
panel.add(textLabel);
enterMessage.add(panel);
}else {
System.out.printf("Refresh");
panel.revalidate();
enterMessage.revalidate();
panel.repaint();
enterMessage.repaint();
}
}
}
This method gets called twice in the program code: one time to make the GUI upon opening the program and everytime an enterpress is detected to refresh it. I searched on internet how to refresh a JPanel and I found that you needed to use revalidate(); and then repaint(); but it does not refresh the time displayed by the panel. How would I refresh it?
ps:the time is passed from the main as a string and everytime an enterpress is detected gets overwritten and passed
Follow Java naming conventions. Variable names should NOT start with an upper case character.
Don't keep adding the label to the panel. Just use the setText(...) method of JLabel to change the text being displayed.
Edit:
An example of a SSCCE that shows you how to use the setText(...) method:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class TimerTime extends JPanel implements ActionListener
{
private JLabel timeLabel;
public TimerTime()
{
timeLabel = new JLabel( new Date().toString() );
add( timeLabel );
Timer timer = new Timer(1000, this);
timer.setInitialDelay(1);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e)
{
//System.out.println(e.getSource());
timeLabel.setText( new Date().toString() );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("TimerTime");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TimerTime() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

How to catch mouse click event on a window blocked by opened JDialog

To put it simple - what i want is to catch mouse click on a Window blocked by a modal JDialog.
Here is an example:
public class BlockedFrameTest
{
public static void main ( final String[] args )
{
Toolkit.getDefaultToolkit ().addAWTEventListener ( new AWTEventListener ()
{
#Override
public void eventDispatched ( final AWTEvent event )
{
if ( event instanceof MouseEvent )
{
System.out.println ( event );
}
}
}, AWTEvent.MOUSE_EVENT_MASK );
final JFrame frame = new JFrame ( "Frame" );
frame.add ( new JLabel ( "Content" )
{
{
setBorder ( BorderFactory.createEmptyBorder ( 100, 100, 100, 100 ) );
}
} );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setVisible ( true );
final JDialog dialog = new JDialog ( frame, "Dialog" );
dialog.setModal ( true );
dialog.add ( new JLabel ( "Content" )
{
{
setBorder ( BorderFactory.createEmptyBorder ( 50, 50, 50, 50 ) );
}
} );
dialog.pack ();
dialog.setLocationRelativeTo ( frame );
dialog.setVisible ( true );
}
}
By looking at the example output log you will see that events from JFrame are not passed when JDialog is opened (even into the global AWT event listener added in the example).
So i wonder - is there any way to catch the click on the blocked JFrame?
Or at least catch an event when something blocked is "touched" by user?
The reason why i need this is to make custom-decorated JDialog blick when such event occurs.
Maybe this helps :
how to obtain mouse click coordinates outside my window in Java
Its a bit difficult because you are leaving the realm of Swing and entering the native-GUI domain.
I think you can't do that if your JDialog is modal, but you can use next trick with FocusListener :
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Example {
public static void main(final String[] args) {
final JFrame frame = new JFrame("Frame");
final JDialog dialog = new JDialog(frame, "Dialog");
frame.add(new JLabel("Content") {
{
setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
}
});
frame.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println("frame pressed");
System.out.println("dialog focused " + dialog.isFocused());
System.out.println("frame focused " + frame.isFocused());
super.mousePressed(arg0);
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
dialog.add(new JLabel("Content") {
{
setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
}
});
dialog.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
super.focusLost(arg0);
dialog.requestFocus();
}
});
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
}
and output:
frame pressed
dialog focused true
frame focused false

JSlider Event Firing twice

I have a simple JSlider with an attached ChangeListerner. Here's the code:
JSlider slider = new JSlider();
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(20);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setOrientation(SwingConstants.VERTICAL);
contentPane.add(slider, BorderLayout.CENTER);
slider.addChangeListener(new SliderListener());
class SliderListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
System.out.println("boo");
}
}
}
As you can see, the code isn't doing much, all I want to do for now is make sure the event is only firing once, and hence my event is simply to print something to the Console within Eclipse.
But the above code is printing "boo" twice each time I change the Slider. I'm guessing this has got something to do with Mouse Release on Slider, but whatever it is, I want it to only fire the event once, and hence only print the word once.
How can I achieve that?
Thanks
Are you certain the listener is not added twice ? The following SSCCE works as expected on my machine (OS X, JDK7)
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.EventQueue;
public class SliderTest {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( );
final JSlider slider = new JSlider( 0, 100 );
frame.add( slider );
slider.addChangeListener( new ChangeListener() {
#Override
public void stateChanged( ChangeEvent e ) {
if ( !( slider.getValueIsAdjusting() ) ){
System.out.println( "SliderTest.stateChanged" );
}
}
} );
frame.pack();
frame.setVisible( true );
frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
}
} );
}
}
I know the issue. My workaround is to set global eventOnwer to all other listeners,
That solves other event fires to occure while one is the event owner.
And then, to solve the slider, I set the getValueIsAdjusting() to true in a if. In case of another fire, return.

Java Popup Button

Note: You may have to compile and run my example to fully understand my question. If this is not kosher, I apologize in advance.
I am trying to create a Swing control that is based on a JToggleButton and a JPopupMenu.
The toggle button is selected iff the popup menu is visible, and the toggle button is deselected iff the popup menu is not visible. Thus, the behavior is similar to a JComboBox, except that the popup can contain arbitrary components.
The code that follows is an example of how I would create the control (except that it would be in its own class... something like a JPopupToggleButton). Unfortunately, it exhibits different behavior under different look and feels (I have tested it with Metal and Nimbus).
The code as posted here behaves as expected in Metal, but not in Nimbus. When using Nimbus, just show and hide the popup by repeatedly clicking the toggle button and you will see what I mean.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class PopupButtonExample extends JFrame
{
public static void main( String[] args )
{
java.awt.EventQueue.invokeLater( new Runnable()
{
#Override
public void run()
{
PopupButtonExample example = new PopupButtonExample();
example.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
example.setVisible( true );
}
});
}
public PopupButtonExample()
{
super( "Components in Popup" );
JPanel popupPanel = new JPanel();
popupPanel.setLayout( new BorderLayout() );
popupPanel.add( new JLabel( "This popup has components" ),
BorderLayout.NORTH );
popupPanel.add( new JTextArea( "Some text", 15, 20 ),
BorderLayout.CENTER );
popupPanel.add( new JSlider(), BorderLayout.SOUTH );
final JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add( popupPanel );
final JToggleButton popupButton = new JToggleButton( "Show Popup" );
popupButton.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if( popupButton.isSelected() )
popupMenu.show( popupButton, 0, popupButton.getHeight() );
}
});
popupMenu.addPopupMenuListener( new PopupMenuListener()
{
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {}
#Override
public void popupMenuCanceled(PopupMenuEvent pme) {}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
Point componentLoc = popupButton.getLocationOnScreen();
mouseLoc.x -= componentLoc.x;
mouseLoc.y -= componentLoc.y;
if( !popupButton.contains( mouseLoc ) )
popupButton.setSelected( false );
}
});
JPanel toolBarPanel = new JPanel();
toolBarPanel.add( popupButton );
JToolBar toolBar = new JToolBar();
toolBar.add( toolBarPanel );
setLayout( new BorderLayout() );
add( toolBar, BorderLayout.PAGE_START );
setPreferredSize( new Dimension( 640, 480 ) );
pack();
}
}
Commeting out the following lines makes the code behave as expected in Nimbus, but not in Metal. Again, just keep clicking the toggle button to see what I mean.
// Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
// Point componentLoc = popupButton.getLocationOnScreen();
// mouseLoc.x -= componentLoc.x;
// mouseLoc.y -= componentLoc.y;
// if( !popupButton.contains( mouseLoc ) )
So here are my two questions:
(1) In Nimbus, why does the click that hides the popup panel not get passed to the toggle button, as it does with Metal?
(2) How can I solve this problem so that it works with all look and feels?
Nimbus is too buggy (and development ended somewhere in the middle) I see that you need three mouse click to the JToggleButton in compare with Metal
every standard L&F have got own specific issues, especially SystemLookAndFeel
use JWindow rather that JPopup, because with JPopup there are another Bugs too e.g. JPopup with JCombobox
After some investigation, I found the cause for the difference between Nimbus and Metal. The following flag is used (at least by BasicPopupMenuUI) to control the consumption of events when a popup is closed:
UIManager.getBoolean( "PopupMenu.consumeEventOnClose" );
When using Nimbus, this returns true. When using Metal, this returns false. Thus, the method popupMenuWillBecomeInvisible should be defined as follows:
if( UIManager.getBoolean( "PopupMenu.consumeEventOnClose" ) )
{
popupButton.setSelected( false );
}
else
{
Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
Point componentLoc = popupButton.getLocationOnScreen();
mouseLoc.x -= componentLoc.x;
mouseLoc.y -= componentLoc.y;
if( !popupButton.contains( mouseLoc ) )
{
popupButton.setSelected( false );
}
}

Java Swing rendering bug on Windows 7 look-and-feel?

The knob on vertical JSlider's on my Windows 7 machine (with native look-and-feel) is really, really tiny in both directions. Not just skinny but short as well.
Can anyone confirm this? Should I report it? If so, where? Thanks!
Here is the code for the sample program (in the screen shot):
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class SliderTest
{
public static void main( String[] args )
{
// Set the look and feel to that of the system
try
{ UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); }
catch ( Exception e )
{ System.err.println( e ); }
// Launch the GUI from the event dispatch thread
javax.swing.SwingUtilities.invokeLater( new Runnable()
{
public void run ()
{
JFrame window = new JFrame();
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel contentPane = new JPanel();
contentPane.add( new JSlider(SwingConstants.HORIZONTAL) );
contentPane.add( new JSlider(SwingConstants.VERTICAL) );
window.setContentPane( contentPane );
window.pack();
window.setLocationRelativeTo( null ); // Center window
window.setVisible( true );
}
});
}
}
First off, this happens in Windows Vista too. It seems to be the case, that the slider tries to take as little space as possible. If you want a bigger JSlider use JSlider.setPaintTicks. So you have to add the following:
JSlider vertical = new JSlider( SwingConstants.VERTICAL );
vertical.setPaintTicks( true );
contentPane.add( vertical );
That should do the trick.

Categories

Resources