I want to put some texts in text-Field when the form is load which instruct to user and when user click on that text-filed the texts remove automatically.
txtEmailId = new JTextField();
txtEmailId.setText("Email ID");
i have wrote above code but it display the text and keep as it is when user click on that text button i want to remove it.
is there any way to do this task?
I use to override the text fields paint method, until I ended up with more custom text fields then I really wanted...
Then I found this prompt API which is simple to use and doesn't require you to extend any components. It also has a nice "buddy" API
This has now been included in the SwingLabs, SwingX library which makes it even eaiser to use...
For example (this uses SwingX-1.6.4)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.prompt.PromptSupport;
public class PromptExample {
public static void main(String[] args) {
new PromptExample();
}
public PromptExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField bunnies = new JTextField(10);
JTextField ponnies = new JTextField(10);
JTextField unicorns = new JTextField(10);
JTextField fairies = new JTextField(10);
PromptSupport.setPrompt("Bunnies", bunnies);
PromptSupport.setPrompt("Ponnies", ponnies);
PromptSupport.setPrompt("Unicorns", unicorns);
PromptSupport.setPrompt("Fairies", fairies);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, bunnies);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIGHLIGHT_PROMPT, ponnies);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, unicorns);
PromptSupport.setFontStyle(Font.BOLD, bunnies);
PromptSupport.setFontStyle(Font.ITALIC, ponnies);
PromptSupport.setFontStyle(Font.ITALIC | Font.BOLD, unicorns);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(bunnies, gbc);
frame.add(ponnies, gbc);
frame.add(unicorns, gbc);
frame.add(fairies, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
JTextField busqueda = new JTextField(20);
add(busqueda);
busqueda.setHorizontalAlignment(SwingConstants.CENTER);
if (busqueda.getText().length() == 0) {
busqueda.setText("Buscar");
busqueda.setForeground(new Color(150, 150, 150));
}
busqueda.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
busqueda.setText("");
busqueda.setForeground(new Color(50, 50, 50));
}
#Override
public void focusLost(FocusEvent e) {
if (busqueda.getText().length() == 0) {
busqueda.setText("Buscar");
busqueda.setForeground(new Color(150, 150, 150));
}
}
});
You can download this NetBeans plugin which you can use to create a placeholder with just one line.
Related
I have a header on a section of my swing layout, and I want to have text centered horizontally across the whole width of the section, but also have a button on only the right side. It should look like this:
/------Same width------\ /------Same width------\
[------------------------]Text here[----------------[Button]]
I am currently using a BorderLayout, with the text in the center and the button at the line end, but the text is centered not counting the button, as such:
/----Same width----\ /---Same width----\
[--------------------]Text here[-------------------][Button]]
I'm not sure if this is the answer you really want, but you could use a different layout manager, like GridBagLayout
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication295 {
public static void main(String[] args) {
new JavaApplication295();
}
public JavaApplication295() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
// gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(new JLabel("Look ma, no hands"), gbc);
gbc.anchor = GridBagConstraints.EAST;
add(new JButton("No Allowance"), gbc);
}
}
}
Now, the problem with this, is both components are actually positioned at the same location, the difference is, the button is anchored to the right position of the cell, this means that when the layout is been calculated, they will overlap....
Here is an approach using the OverlayLayout which was designed to have multiple components painted on the z axis:
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JLabel label = new JLabel("I'm a Centered Label");
Box labelBox= Box.createHorizontalBox();
labelBox.add(Box.createHorizontalGlue());
labelBox.add(label);
labelBox.add(Box.createHorizontalGlue());
JButton button = new JButton("Button");
Box buttonBox= Box.createHorizontalBox();
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(button);
setLayout( new OverlayLayout(this) );
add(buttonBox);
add(labelBox);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE(), BorderLayout.NORTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
As the width decreases the button will paint over the label.
I am using the Nimbus look and feel.
I have two JCheckBoxes, and by default, the text is black when the JCheckBox is enabled, and greyed out when it is disabled. My new requirement is that the program should ignore the enabled state of the JCheckBox, and instead be greyed out when isSelected() is false, and display the text in a specified colour when isSelected() is true.
I have attempted to do this by:
Extending BasicCheckBoxUI
Overriding the paintText method
Copying the contents of BasicButtonUI.paintText() and modifying the behaviour
Calling setUI on the JCheckBoxes in question with an instance of my new UI class
private static class MyCheckBoxUI extends BasicCheckBoxUI
{
private Color selectedColor;
public MyCheckBoxUI( Color selectedColor )
{
this.selectedColor = selectedColor;
}
#Override
protected void paintText( Graphics g, AbstractButton b, Rectangle textRect, String text )
{
ButtonModel model = b.getModel();
FontMetrics fm = SwingUtilities2.getFontMetrics(b, g);
int mnemonicIndex = b.getDisplayedMnemonicIndex();
if( model.isSelected() )
{
/*** paint the text normally */
g.setColor( selectedColor );
SwingUtilities2.drawStringUnderlineCharAt(b, g,text, mnemonicIndex,
textRect.x + getTextShiftOffset(),
textRect.y + fm.getAscent() + getTextShiftOffset());
}
else
{
/*** paint the text disabled ***/
g.setColor(b.getBackground().brighter());
SwingUtilities2.drawStringUnderlineCharAt(b, g,text, mnemonicIndex,
textRect.x, textRect.y + fm.getAscent());
g.setColor(b.getBackground().darker());
SwingUtilities2.drawStringUnderlineCharAt(b, g,text, mnemonicIndex,
textRect.x - 1, textRect.y + fm.getAscent() - 1);
}
}
}
In the constructor of my JPanel, I have the following:
jCheckBox1.setUI( new MyCheckBoxUI( Color.red ) );
jCheckBox2.setUI( new MyCheckBoxUI( Color.black ) );
This appears to work as expected, except there is a side effect. Now, the check box will not render the tick in the box when it is selected like it used to (I did not expect this as I have only overridden the paintText method). What have I missed?
Additionally, the use of SwingUtilities2 disturbs me, as I am warned that it is an internal proprietary API that could be removed in a future release. Is there a better way to do this?
You need to play with the UIManager color properties...
Object disabledTextForeground = UIManager.get("CheckBox[Disabled].textForeground");
Object enabledTextForeground = UIManager.get("CheckBox.foreground");
UIManager.put("CheckBox[Disabled].textForeground", UIManager.get("CheckBox.foreground"));
UIManager.put("CheckBox[Enabled].textForeground", disabledTextForeground);
UIManager.put("CheckBox[Selected+Enabled].textForeground", enabledTextForeground);
This example will allow you to modify the values at a global level, meaning that every JCheckBox you create will have the same values
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestNimbus {
public static void main(String[] args) {
new TestNimbus();
}
public TestNimbus() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Object disabledTextForeground = UIManager.get("CheckBox[Disabled].textForeground");
Object enabledTextForeground = UIManager.get("CheckBox.foreground");
UIManager.put("CheckBox[Disabled].textForeground", UIManager.get("CheckBox.foreground"));
UIManager.put("CheckBox[Enabled].textForeground", disabledTextForeground);
UIManager.put("CheckBox[Selected+Enabled].textForeground", enabledTextForeground);
JCheckBox cb1 = new JCheckBox("Option #1");
JCheckBox cb2 = new JCheckBox("Option #2");
JCheckBox cb3 = new JCheckBox("Option #3");
cb1.setSelected(true);
cb3.setEnabled(false);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
frame.add(cb1, gbc);
frame.add(cb2, gbc);
frame.add(cb3, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
To affect only given instance of JCheckBoxs, you would need to supply the overrides directly to each instance of the JCheckBox you want to effect...
The top three have their values overridden, while the bottom three remain unaffected and use the UI default values
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestNimbus {
public static void main(String[] args) {
new TestNimbus();
}
public TestNimbus() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
UIDefaults checkBoxDefaults = new UIDefaults();
Object disabledTextForeground = UIManager.get("CheckBox[Disabled].textForeground");
Object enabledTextForeground = UIManager.get("CheckBox.foreground");
checkBoxDefaults.put("CheckBox[Disabled].textForeground", UIManager.get("CheckBox.foreground"));
checkBoxDefaults.put("CheckBox[Enabled].textForeground", disabledTextForeground);
checkBoxDefaults.put("CheckBox[Selected+Enabled].textForeground", enabledTextForeground);
JCheckBox cb1 = new JCheckBox("Option #1");
JCheckBox cb2 = new JCheckBox("Option #2");
JCheckBox cb3 = new JCheckBox("Option #3");
JCheckBox cb4 = new JCheckBox("Normal #1");
JCheckBox cb5 = new JCheckBox("Normal #2");
JCheckBox cb6 = new JCheckBox("Normal #3");
configure(cb1, checkBoxDefaults);
configure(cb2, checkBoxDefaults);
configure(cb3, checkBoxDefaults);
cb1.setSelected(true);
cb4.setSelected(true);
cb3.setEnabled(false);
cb6.setEnabled(false);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
frame.add(cb1, gbc);
frame.add(cb2, gbc);
frame.add(cb3, gbc);
frame.add(cb4, gbc);
frame.add(cb5, gbc);
frame.add(cb6, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void configure(JCheckBox checkbox, UIDefaults uiDefaults) {
checkbox.putClientProperty("Nimbus.Overrides", uiDefaults);
// checkbox.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
}
});
}
}
I would like to develop a form with some text field.
example:
Name
SecondName
the idea is that every text field have inside a text like:
Insert your name
Insert your second name
when you click on the first text field to write your name, the text "Insert your name" have to be deleted... the same have to happen for the second text field (SecondName).
The effect have to be this:
I think that i just need an Action on the text field that have to wake up when the user press on the mouse on the text field, it's possible?
Thank you
Take a look at PromptSupport in SwingLabs SwingX Library
For Example
When the fields have focus, the "prompt" will be hidden, but you can control this, making it shown until the user types something or highlight when focus is gained.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.prompt.BuddySupport;
import org.jdesktop.swingx.prompt.PromptSupport;
public class PromptSupportTest {
public static void main(String[] args) {
new PromptSupportTest();
}
public PromptSupportTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField firstName = new JTextField(10);
PromptSupport.setPrompt("First Name", firstName);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, firstName);
JTextField lastName = new JTextField(10);
PromptSupport.setPrompt("Last Name", lastName);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, lastName);
JTextField picture = new JTextField(10);
PromptSupport.setPrompt("Picture", picture);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, picture);
JButton browse = new JButton("...");
browse.setMargin(new Insets(0, 0, 0, 0));
browse.setContentAreaFilled(false);
browse.setFocusPainted(false);
browse.setFocusable(false);
browse.setOpaque(false);
// Add action listener to brose button to show JFileChooser...
BuddySupport.addRight(browse, picture);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
add(firstName, gbc);
add(lastName, gbc);
add(picture, gbc);
gbc.anchor = GridBagConstraints.CENTER;
add(new JButton("Ok"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
I've also added an example of BuddySupport which is part of the same API, which allows you to "buddy" another component with a text component. Here I've done the classic "file browser" combination, but I do "search" style fields like this all the time...
Take a look at Text Prompt for a simple solution that allows you to control when the text is displayed/hidden as well as the font/color of the text.
It will work with regular text components. In its simplest form you only need one extra line of code:
JTextField firstName = new JTextField(10);
TextPrompt tp = new TextPrompt("First Name", firstName);
see this example
import java.awt.Color;
import java.awt.Font;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JTextField;
public class HintTextField extends JTextField {
Font gainFont = new Font("Tahoma", Font.PLAIN, 11);
Font lostFont = new Font("Tahoma", Font.ITALIC, 11);
public HintTextField(final String hint) {
setText(hint);
setFont(lostFont);
setForeground(Color.GRAY);
this.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
if (getText().equals(hint)) {
setText("");
setFont(gainFont);
} else {
setText(getText());
setFont(gainFont);
}
}
#Override
public void focusLost(FocusEvent e) {
if (getText().equals(hint)|| getText().length()==0) {
setText(hint);
setFont(lostFont);
setForeground(Color.GRAY);
} else {
setText(getText());
setFont(gainFont);
setForeground(Color.BLACK);
}
}
});
}
}
I have worked hard on writing my GUI in swing however I am trying to improve it further since I feel it still looks a little off.
I would ideally like:
the button to snap to the top right,
the textfield to be the same height as the button and stretch from the top left to the button edge
the scrollpane to stretch from the bottom of the textfield and the button to the edges of the window even when stretched.
I'm unsure how to "snap" the components to the top right, top left and rest of the area respectively.
#SuppressWarnings("serial")
class TFrame extends JFrame
{
TFrame()
{
super("Huffman Compression");//setTitle
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setResizable(true);
jPanel = new JPanel();
jTextField = new JTextField("Enter string to compress...");
jButton = new JButton("Compress");
jButton.setFocusable(false);
jTextArea = new JTextArea("LOG AREA", 30, 30);
jTextArea.setWrapStyleWord(true);
jTextArea.setLineWrap(true);
jTextArea.setEditable(false);
jTextArea.setFocusable(false);
jTextArea.setOpaque(false);
jScrollPane = new JScrollPane(jTextArea);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jPanel.add(jTextField, BorderLayout.WEST);
jPanel.add(jButton, BorderLayout.EAST);
jPanel.add(jScrollPane, BorderLayout.SOUTH);
add(jPanel);
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException
| InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
setVisible(true);
}
private JPanel jPanel;
private JTextField jTextField;
private JButton jButton;
private JTextArea jTextArea;
private JScrollPane jScrollPane;
}
public static void main(String[] args)
{
TFrame frame = new TFrame();
frame.pack();
...
This is what it currently looks like:
http://i.imgur.com/90cmDl1.png
Regards.
Basically, you need to take advantage of a series of layout managers (commonly known as "compound layouts").
For example, you can accomplish the requirements for the button and field using a GridBagLayout and the by using a BorderLayout, you can accomplish the rest, for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BrowserWindow {
public static void main(String[] args) {
new BrowserWindow();
}
public BrowserWindow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel topPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
topPane.add(new JTextField(10), gbc);
gbc.weightx = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.gridx++;
topPane.add(new JButton("Compress"), gbc);
JTextArea ta = new JTextArea("Log...", 30, 30);
JScrollPane sp = new JScrollPane(ta);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(topPane, BorderLayout.NORTH);
frame.add(sp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Take a look at Laying Out Components Within a Container for more details
I currently have two frames, when you run the application the first JFrame that shows is a login, it has two input fields and a button. When the user logs in and is verified, I would like to close the frame and start up the second one.
So, the only thing I can think of doing is doing setVisible(false) for the login frame and setVisible(true) for the Main frame.
Is there a better way to do this, or is that the only way?
Personnally, I would start up your second JFrame immediately and replace your first frame with a modal JDialog which would be owned by the JFrame.
See also this answer to The Use of Multiple JFrames, Good/Bad Practice?
Here is a basic demo of what I suggest:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLogin {
private JFrame frame;
private boolean authenticated;
private JTextField login;
private JPasswordField password;
protected void initUI() {
frame = new JFrame(TestLogin.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setVisible(true);
}
protected void showLoginDialog() {
authenticated = false;
final JDialog dialog = new JDialog(frame, "Please provide your credentials");
dialog.setModal(true);
JPanel panel = new JPanel(new GridBagLayout());
JPanel buttonPanel = new JPanel();
login = new JTextField(40);
password = new JPasswordField(20);
JLabel loginLabel = new JLabel("Login:");
JLabel passwordLabel = new JLabel("Password:");
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Here perform authentication and set authentication flag to appropriate value
authenticated = true;
if (authenticated) {
setUpFrame();
dialog.dispose();
}
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
dialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
if (!authenticated) {
System.exit(0);
}
}
});
dialog.getRootPane().setDefaultButton(ok);
buttonPanel.add(ok);
buttonPanel.add(cancel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(loginLabel, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1.0;
panel.add(login, gbc);
gbc.gridwidth = 1;
gbc.weightx = 0;
panel.add(passwordLabel, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1.0;
panel.add(password, gbc);
panel.add(buttonPanel, gbc);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(frame);
while (!authenticated) {
dialog.setVisible(true);
}
}
protected void setUpFrame() {
frame.add(new JLabel("Successfully authenticated"));
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestLogin testLogin = new TestLogin();
testLogin.initUI();
testLogin.showLoginDialog();
}
});
}
}
There are several ways to do that.
E.g. you could reuse your 1st JFrame. Therefore remove the components you got on your 1st frame, add the ones for the 2nd and then repaint() the frame.
But I wouldn't consider that as good practice.
As Andrew Thompson suggested, you could also use a CardLayout to just initialize one JFrame, show your login-card and then switch to the fully initialized 2nd full-application card. This way you will get rid of those repaints.
You could also show your 2nd frame (your application first) and then use a modal JDialog to the let user log in.