I was wondering whether the way I expect the JFormattedTextField to work in combination with a default button is correct. When editing the value of a JFormattedTextField, you usually want to commit the value and then use it, this usually happens on focusLost or sometimes when the ActionListener is manually triggered. Now, if such a text field is inside of a JDialog which has a DefaultButton defined, triggering the default button with Ctrl+Enter will not cause the currently focused JFormattedTextField to trigger it's focusLost event.
Now, I see two solutions for this:
Manually make sure all inupt fields are in a comitted (or reverted) state
Use a SwingUtilities.InvokeLater in the ActionListener of the default button
However, both of these seem dirty, especially the first one, as it's not very easy to extend said dialog without forgetting to handle the components. The second one is rather undesirable imo because more invokeLaters usually mean more code that's harder to debug.
Is there a better way of solving this?
EXAMPLE:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DefaultButton
{
public static void main( String[] args )
{
JFrame frame = new JFrame();
JFormattedTextField field = new JFormattedTextField();
field.setValue( "HELLO" );
JButton defaultButton = new JButton( "Default" );
defaultButton.addActionListener( __ ->
{
JOptionPane.showMessageDialog( frame, "You've chosen: " + field.getValue() );
} );
frame.getRootPane().setDefaultButton( defaultButton );
JPanel panel = new JPanel( new BorderLayout() );
panel.add( field, BorderLayout.NORTH );
panel.add( defaultButton, BorderLayout.SOUTH );
frame.add( panel );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
}
Yes, when the JFormattedTextField has input focus and you activate the defaultButton, the JFormattedTextField does not lose focus and therefore the value is not committed.
Refer to How to Use Formatted Text Fields.
Here is a quote:
A formatted text field's text and its value are two different properties, and the value often lags behind the text.
The text property is defined by the JTextField class. This property always reflects what the field displays. The value property, defined by the JFormattedTextField class, might not reflect the latest text displayed in the field. While the user is typing, the text property changes, but the value property does not change until the changes are committed.
I see two possible solutions (although I imagine there are more).
In the actionPerformed() method, either call getText() rather than getValue(), or call commitEdit() before calling getValue(), i.e.
JOptionPane.showMessageDialog( frame, "You've chosen: " + field.getText() );
or
try {
field.commitEdit();
}
catch (java.text.ParseException x) {
x.printStackTrace();
}
JOptionPane.showMessageDialog(frame, "You've chosen: " + field.getValue());
EDIT
I believe this is what you are looking for.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DefaultButton
{
public static void main( String[] args )
{
JFrame frame = new JFrame();
JFormattedTextField field = new JFormattedTextField();
field.setValue( "HELLO" );
JButton defaultButton = new JButton( "Default" );
defaultButton.addActionListener( __ ->
{
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (kfm.getFocusOwner() == field) {
kfm.focusNextComponent();
}
EventQueue.invokeLater(() -> JOptionPane.showMessageDialog( frame, "You've chosen: " + field.getValue() ));
} );
frame.getRootPane().setDefaultButton( defaultButton );
JPanel panel = new JPanel( new BorderLayout() );
panel.add( field, BorderLayout.NORTH );
panel.add( defaultButton, BorderLayout.SOUTH );
frame.add( panel );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
}
Concentrate on method actionPerformed(). If the JFormattedTextField currently has the focus then force the focus to move to the next component. Regardless of which component has the keyboard focus, wrap the displaying of the JOptionPane in a invokeLater() call.
Related
I am trying to color the Border of a JTextField red and then change it back to "normal" later on. When I am using Linux (furthermore Ubuntu), the initial Border differs from the Border that you get by using UIManager.getBorder("TextField.border"); one of them is a SynthBorder and one is a FieldBorder. The "correct" one would be the SynthBorder.
SSCCE:
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main
{
private static boolean switched;
public static void main( final String[] args )
throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
JFrame frame = new JFrame( "Test border change" );
frame.getContentPane().setLayout( new BoxLayout( frame.getContentPane(), BoxLayout.LINE_AXIS ) );
JTextField tf = new JTextField();
JButton button = new JButton( "Switch" );
button.addActionListener( action ->
{
if ( switched )
{
tf.setBorder( UIManager.getBorder( "TextField.border" ) );
switched = !switched;
}
else
{
tf.setBorder( BorderFactory.createLineBorder( Color.RED ) );
switched = !switched;
}
} );
frame.getContentPane().add( tf );
frame.getContentPane().add( button );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
}
I have already tried:
using JComponent.updateUI() (no effect)
nulling the border (ruins the layout)
preserving it (not a proper way)
Does anyone have a better idea?
You can get the default border in the UIManager with this code:
jTextField2.setBorder(UIManager.getLookAndFeel().getDefaults().getBorder("TextField.border"));
When you replace the Border try using:
Border uiBorder = BorderUIResource( BorderFactory.createLineBorder( Color.RED ) );
tf.setBorder( uiBorder );
When you use any wrapper class with "UIResource" this tell the LAF the component is part of the LAF and not a custom implementation
Then to restore the Border:
SwingUtilities.updateComponentTreeUI( tf );
Hopefully this will fake the UI into resetting the LAF properties, specifically the Border.
Read the section from the Swing tutorial on How to Set the LAF for more information.
Of course this is not as efficient as simply saving the Border and resetting it as all properties of the text field will be updated bye the updatComponentTreeUI(...) (if this works).
Still don't see why you can't save the Border. You could use the putClientProperty(...) method of the JComponent class to save the Border and then restore it using the getClientProperty(...) method.
You could even automate this by using adding a PropertyChangeListener to listen for a change in the border. When an event is generated if the getClientProperty(...) returns null, then you save the old value from the PropertyChangeEvent.
yourJTextField.setBorder(new JTextField().getBorder());
You can get the border right after creating the component to save it, and set it again later.
Border defaultBorder = tf.getBorder();
...
tf.setBorder(defaultBorder);
I have found that when a modal JDialog launches a second modal JDialog, and when that second JDialog is disposed, the first JDialog seems to (mostly) ignore the keyboard.
I have included a sample program to demonstrate the issue. On running the code, I should be able to hit the space bar (the button in the main JFrame has focus) and the first JDialog is launched, containing a button (also with focus).
I hit the space bar and the second JDialog is launched. Hitting enter, the second JDialog disposes.
Hitting space bar on the first JDialog results in no response. Alt- F4 will close the first JDialog, so the keyboard is not completely disconnected.
Repeating the above procedure using the mouse only, the issue does not occur.
The background to all of this is I wanted to set the default button on a dialog (in which the user enters some text and other data). If I comment out the setDefaultButton in the second JDialog and now use TAB to move around, the issue does not occur.
In short, I want to be able to set a default button on a JDialog (so I can hit the enter key), but at the same time, I want default focus on a JTextField.
I am on Ubuntu 13.10 using the OpenJDK (64 bit). I have found this happens regardless of using the GTK+ look and feel or the metal look and feel (that is, not setting any look and feel).
I cannot reproduce on Windows XP (using Oracle Java 32 bit).
On reading a few posts, it seems Linux and Java have a few focus problems and so I'm not sure if this is a programming error on my part or I've stumbled upon a Linux/Java issue.
Any ideas please?
Below is example code which reproduces the issue.
import java.awt.BorderLayout;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Test extends JFrame
{
public Test()
{
JButton button = new JButton( "Test" );
button.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent actionEvent ) { new Test1( Test.this ); } } );
JPanel panel = new JPanel();
panel.add( button );
getContentPane().add( panel );
pack();
setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
setVisible( true );
}
protected class Test1 extends JDialog
{
public Test1( JFrame owner )
{
super( owner );
JButton button = new JButton( "1" );
button.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent actionEvent ) { new Test2( Test1.this ); } } );
JPanel panel = new JPanel();
panel.add( button );
getContentPane().add( panel );
pack();
setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
setLocationRelativeTo( null );
setModalityType( ModalityType.APPLICATION_MODAL );
setVisible( true );
}
}
protected class Test2 extends JDialog
{
public Test2( JDialog owner )
{
super( owner );
JTextField textField = new JTextField();
JButton button = new JButton( "2" );
getRootPane().setDefaultButton( button );
button.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent actionEvent )
{
// Test2.this.getRootPane().setDefaultButton( null ); // Makes no difference!
Test2.this.dispose();
}
}
);
JPanel panel = new JPanel( new BorderLayout() );
panel.add( textField, BorderLayout.CENTER );
panel.add( button, BorderLayout.SOUTH );
getContentPane().add( panel );
pack();
setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
setLocationRelativeTo( null );
setModalityType( ModalityType.APPLICATION_MODAL );
setVisible( true );
}
}
public static void main( String[] args )
{
new Test();
}
}
I have the following sample-code:
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class SampleFocus extends JFrame {
public SampleFocus(String titel) {
setTitle(titel);
JTextField txtField1 = new JTextField("default-click");
JTextField txtField2 = new JTextField("alternative-Text");
JTextField txtField3 = new JTextField("own diaolog textfield");
JTextArea dummyLabel = new JTextArea(10, 20);
dummyLabel.setText("empty textarea, which is focusable");
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(txtField1);
add(dummyLabel);
add(txtField2);
JDialog altDialog = new JDialog(this);
altDialog.add(txtField3);
altDialog.setVisible(true);
altDialog.pack();
FocusAdapter myFocusListner = new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
if (e.getComponent() instanceof JTextField) {
System.out.println("gained for TextField: "
+ ((JTextField) e.getComponent()).getText());
} else {
System.out.println("gained for component: " + e.getComponent());
}
}
};
txtField1.addFocusListener(myFocusListner);
txtField2.addFocusListener(myFocusListner);
txtField3.addFocusListener(myFocusListner);
// dummyLabel.addFocusListener(myFocusListner);
}
public static void main(String[] args) {
JFrame frame = new SampleFocus("FocusListener - sample");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
When I switch from the Frame to the dialog I get the proper event. When I switch back to the Frame I get as well the proper FocusEvents. My problem is, that when I switch back, I get as well the FocusEvents for components which I am not interested in.
e.g.
Select 'default-click' ==> Dialog/Textfield ==> Frame/'empty textarea'
Result: I get a FocusGained-Event for 'default-click' although the component has NOT the focus.
Desired Result: Either
Component 'default-click' does not get the FocusEvent OR
distinguish if the component really received the Event properly (e.g. I could have clicked into it as well)
Workaround I found:
Attach to the JTextArea as well a FocusListener. Problem is, that this would mean, I need to attach to ALLLL of my components a Listener. Which is hardly possible. Any ideas?
Any ideas how to get the result?
Thx LeO
Its working as intended.
You select "default-click". It gains focus.
You select Dialog. Frame and "default-click" loses focus.
You select Text area. Now, things becomes interesting. Dialog loses focus. Frame gets focus. "default-click" also gains focus, because he had it when Frame was active. And then "default-click" loses focus, textarea gains focus (because you clicked on text area).
Try combine focusGained and focusLost events.
Or tell me more what are you trying to accomplish, maybe I can help.
The way I found the workaround was to check in the focusGained-method if the current component is in an own JDialog and if previous component was a JTextField in a JFrame. If so, then I memorize the gained focused component, change the focus to another component and when I receive a focusLost I request it back to the previously memorized component.
Some kind of hack, but it works.... If there are any better ideas, I am interested in ...
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.
I want to maximize a JPanel inside a JFrame when the user clicks a button.What is the best way to achieve this.The view and the data model should be in sync in both the panels,that is the panel which in the JFrame and the maximized one.Please suggest me some solution.
my requirement is: i have a JFrame with 4 JPanels named as
JPanelA,JPanelB,JPanelC,JPanelD
Here the JPanelD contains a JList and
a button below it say "MAXIMIZE
PANEL" button . JList has a JTree
with in it . Sometimes the JList may
have huge set of data and it is not
visible to the user clearly.
So he need to maximize this JPanelD alone to see the contents of the JList clearly.For that he clicks "MAXIMIZE PANEL" button.After the click action ,the JPanelD in the JFrame remains there,also a new JPanel with the same JList data(ie.,the replica of the JPanelD say JPanelDMaximized)should be popped up.This is what i want to do ..
Of course you could do this yourself, but you should really look at JInternalFrame and consider using that for your panel. It will save a bunch of headache.
Edit: Sun's tutorial should get you what you need.
Follow-up to your clarification of the problem:
Take my code, and remove:
maximizedFrame.setUndecorated( true );
and size the frame bigger before you make it visible. That should satisfy the maximize-like behaviour you need.
Your other problem is that you cannot add JPanelD to the two JFrames. The pop-up frame must have its own unique JPanel object (let's call it JPanelE). So you need to:
Initialize and lay out JPanelE like you do JPanelD. That means giving JPanelE its own JList (and JTree, and so on).
Share the ListModel from JPanelD's JList with JPanelE's JList, and so on. The feasibility and details of executing this successfully depends on the specifics of your implementation, and is beyond the scope of your original problem.
Create a JWindow (or an undecorated JFrame) with a JPanel. Leave the JWindow invisible, initially. (The wiring of this new JPanel to the same data model used by the original JPanel is left as an exercise.)
When your maximize-panel button's ActionListener executes, it must:
2.1. Update the (invisible) JWindow's location and size to match the (visible) JFrame's.
2.2. Make your JFrame invisible.
2.3. Make your JWindow visible.
When your unmaximize-panel button's ActionListener executes, it must:
3.1. Update the (invisible) JFrame's location and size to match the (visible) JWindow's.
3.2. Make your JWindow invisible.
3.3. Make your JFrame visible
Example:
package stackoverflow;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MaximizingPanelApp extends JFrame {
private JPanel framePanel;
private JPanel windowPanel;
private JFrame maximizedFrame;
public static void main(String[] args) {
JFrame appFrame = new MaximizingPanelApp();
appFrame.setVisible( true );
}
public MaximizingPanelApp() throws HeadlessException {
super( "Application" );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
initialize();
}
private void initialize() {
// JFrame
{
Container container = getContentPane();
container.setLayout( new BorderLayout() );
framePanel = new JPanel();
framePanel.setBackground( Color.ORANGE );
container.add( framePanel, BorderLayout.CENTER );
JButton button = new JButton( new MaximizeAction() );
container.add( button, BorderLayout.SOUTH );
setSize( 400, 300 );
}
// JWindow
{
maximizedFrame = new JFrame();
Container container = maximizedFrame.getContentPane();
container.setLayout( new BorderLayout() );
windowPanel = new JPanel();
windowPanel.setBackground( Color.ORANGE );
container.add( windowPanel, BorderLayout.CENTER );
JButton button = new JButton( new UnMaximizeAction() );
container.add( button, BorderLayout.SOUTH );
maximizedFrame.setSize( getSize() );
maximizedFrame.setUndecorated( true );
}
}
private class MaximizeAction extends AbstractAction {
private MaximizeAction() {
super( "Maximize" );
}
public void actionPerformed(ActionEvent e) {
maximizedFrame.setSize( getSize() );
maximizedFrame.setLocation( getLocation() );
setVisible( false );
maximizedFrame.setVisible( true );
}
}
private class UnMaximizeAction extends AbstractAction {
private UnMaximizeAction() {
super( "Un-Maximize" );
}
public void actionPerformed(ActionEvent e) {
setLocation( maximizedFrame.getLocation() );
setSize( maximizedFrame.getSize() );
maximizedFrame.setVisible( false );
maximizedFrame.dispose();
setVisible( true );
}
}
}
This depends on the layout manager you use. If you add a JPanel to a JFrame using the default layout manager, and the JFrame only contains the JPanel and nothing else, you'll achieve what you describe.
Here's an example. The JPanel is green; notice how it resizes as you resize the JFrame.
import javax.swing.*;
import java.awt.*;
public class ScratchSpace {
public static void main(String[] args) {
JFrame frame = new JFrame("Stretchy panel demo");
final JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.GREEN);
panel.setPreferredSize(new Dimension(600, 400));
final JComponent contentPane = (JComponent) frame.getContentPane();
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}