More than one JFrame - java

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.

Related

How do I stop JFrame/JPanel from auto-formatting the distances between my components?

So I'm writing a program which utilizes a GUI. The GUI is built from a JFrame and a JPanel in Java. I have a JTextArea() and a JButton() that appears beside the JTextArea on the left. I also have an image which I imported locally using the method call below ("f" is the variable name of my JFrame):
f.setIconImage(ImageIO.read(new File("image.png")));
I don't mind allowing the users to resize the JFrame but what I dislike is that JFrame automatically reformats the components on my JFrame - specifically the distance between my image and the JTextArea(). I'd like, if possible, to keep the distance between my image and the JTextArea the same regardless of the size the user resizes the JFrame to. Here's the rest of my code if that helps:
public class GUI {
private JFrame f;
private JPanel p;
private JButton b1;
private JLabel lab;
private JTextArea tf;
private static final String FileName = "schedule.txt";
private static final String FileName2 = "schedule2.txt";
public void show()
{
f = new JFrame("Scheduler");
f.setSize(600, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
//p.setPreferredSize(new Dimension(200, 400));
b1 = new JButton("Run");
p.add(b1);
f.add(p);
f.add(p, BorderLayout.SOUTH);
f.add(new JLabel(new ImageIcon("image.png")));
try {
f.setIconImage(ImageIO.read(new File("image.png")));
} catch(Exception z){
System.out.println("Trouble reading file");
}
tf = new JTextArea();
tf.setPreferredSize(new Dimension(300, 200));
p.add(tf);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
try {
FileWriter fw = new FileWriter(FileName);
fw.write(text);
fw.close();
parseInfo();
}
catch(Exception ex)
{
}
}
});
f.setVisible(true);
}
There are any number of ways you "might" achieve this, but the basic answer is, you need to choose one or more layout managers which better meets your needs.
For example, using a GridBagLayout, you can do something like...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class JavaApplication1 {
public static void main(String[] args) {
new JavaApplication1();
}
public JavaApplication1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
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.insets = new Insets(8, 8, 8, 8);
JLabel label = new JLabel("Image placeholder") {
// This is done only for demonstration purposes
#Override
public Dimension getPreferredSize() {
return new Dimension(128, 128);
}
};
label.setBorder(new LineBorder(Color.DARK_GRAY));
add(label, gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
// This will cause the text area to occupy all the avalilable free space
//gbc.weightx = 1;
//gbc.weighty = 1;
JTextArea ta = new JTextArea(10, 20);
add(new JScrollPane(ta), gbc);
JButton btn = new JButton("Run");
gbc.gridy++;
// Reset the constraints
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.weighty = 0;
add(btn, gbc);
}
}
}
Take a look at Laying Out Components Within a Container for more details and ideas
Recommendations...
There are a few things in your code that are, "off", but this...
tf = new JTextArea();
tf.setPreferredSize(new Dimension(300, 200));
p.add(tf);
is probably the most striking.
Generally speaking, JTextArea will benefit from been wrapped in a JScrollPane. Also, due to the inconsistencies in how text is rendered across multiple platforms, you should avoid using setPreferredSize (in fact, you should avoid using it in general) and instead rely in the rows, columns constructor, which will make calculations based on the current font and graphics properties.

Java GUI Opening a new JFrame

I've looked around online at how to open a new JFrame from an existing JFrame. I've found that apparently the best way to do this is dispose of the existing JFrame and open the new JFrame - however this is a problem.
I have a login form, one the users logs in, the login frame is disposed and the main frame is set visible.
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class client {
public static void main(String[] args) {
initialize();
}
private static void initialize() {
JFrame loginFrame = new JFrame("Login");
loginFrame.setBounds(100, 100, 300, 300);
loginFrame.setResizable(false);
loginFrame.setLocationRelativeTo(null);
loginFrame.setDefaultCloseOperation(loginFrame.HIDE_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
JFrame mainFrame = new JFrame("Main");
mainFrame.setBounds(100, 100, 300, 197);
mainFrame.setResizable(false);
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().setLayout(null);
JButton loginButton = new JButton("Login");
loginButton.setBounds(102, 133, 89, 23);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loginButton.setEnabled(false);
loginFrame.dispose();
mainFrame.setVisible(true);
}
});
loginFrame.getContentPane().add(loginButton);
loginFrame.setVisible(true);
}
}
However if the user launches the client and then decides not to login and closes it, the process remains running in the background?
I feel like this is a really stupid question and I am sorry if so, but I've looked around and couldn't find any workarounds for this. Am I ok to not dispose of the login frame and just hide it and set them both to EXIT_ON_CLOSE?
Thanks in advance!
So, the primary issue is, you have two frames, while not visible, both have been "realised", meaning that until ALL the application windows are disposed of, the Event Dispatching Thread won't exit, which means the JVM won't exit.
So, I suggest a slight change in approach. Rather then using two frames this way, the login "window" should be based on a modal dialog and the application frame shouldn't be created until you need it.
A modal dialg will stop the execution of the code at the point it's made visible in away that won't block the Event Dispatching Thread (it's black magic), this means you can use it a loop to keep prompting the user for credentials until they are either authenticated or the close/cancel the dialog.
I would also strongly encourage the use of JPanels as the base component, allowing the window based classes to just be containers, this isolates responsibility, decouples the code and makes for a more re-usable solution overall.
You can have a look at How to Make Dialogs for more details
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
LoginPane loginPane = new LoginPane();
boolean authenticated = false;
boolean exit = false;
do {
int option = JOptionPane.showOptionDialog(null,
loginPane,
"login",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
new Object[]{"Login", "Cancel"},
"Login");
if (option == 0) {
// Authenticate
authenticated = true;
} else if (option == JOptionPane.CLOSED_OPTION || option == 1) {
exit = true;
}
} while (!authenticated && !exit);
if (authenticated) {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
});
}
public class LoginPane extends JPanel {
private JTextField userName;
private JPasswordField password;
public LoginPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("User name: "), gbc);
gbc.gridy++;
add(new JLabel("Password: "), gbc);
gbc.gridx++;
gbc.gridy = 0;
userName = new JTextField(10);
password = new JPasswordField(10);
add(userName, gbc);
gbc.gridy++;
add(password, gbc);
}
public String getName() {
return userName.getText();
}
public char[] getPassword() {
return password.getPassword();
}
}
public class MainPane extends JPanel {
public MainPane() {
setBorder(new EmptyBorder(50, 50, 50, 50));
add(new JLabel("Super awesome app"));
}
}
}
I would also encourage DISPOSE_ON_CLOSE instead of HIDE_ON_CLOSE, it will release the native peer and remove the window from the applications window cache
Now, if you're really up for a more challenging methodology, you could have a look at Java and GUI - Where do ActionListeners belong according to MVC pattern?, which presents a MVC based login implementation

Adding textfields to jframe using graphics2d

public class Contact {
int x0,x1,y2=1500,x3=1500,a=0;
JFrame jf;
private JTextField name = new JTextField();
private JTextField phone;
private JButton start;
boolean clicked=false;
static Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
static int w=(int)dim.getWidth(); static int h=(int)dim.getHeight();
IntroInner d=new IntroInner(); int c;
public Contact() {
}
public void build() throws Exception{
jf=new JFrame("THE COUNTRY CLUB");
jf.getContentPane().add(d);
jf.setSize(w,h);
jf.setVisible(true);
jf.setAlwaysOnTop(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class IntroInner extends JPanel{
public void paintComponent(Graphics g1){
Graphics2D g=(Graphics2D) g1;
FontMetrics metrics = g.getFontMetrics();
int xpos=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2-215;
setFont(new Font("serif",Font.ITALIC,40));
g.setColor(Color.black);
g.fillRect(0,0,this.getWidth(),this.getHeight());
Image im1=new ImageIcon("Images/bg.jpg").getImage();
g.drawImage(im1,0,0,this);
//g.rotate(a);
Image im=new ImageIcon("Images/logo.png").getImage();
g.drawImage(im,xpos,50,this);
g.setColor(Color.white);
g.drawString("Please Enter Your Details",400,400);
g.drawString("Name:",400,475);
g.drawString("Contact No:",400,550);
}
}
public static void main(String[] args) throws Exception{
new Contact().build();
}
}
I reffered alot about implementing textfield to java frame using graphics2d in java. But didn't get any useful opinion. I have found something here in stackoverflow also. But that too didn't helped me. Can anybody help me in this. The expected output of this program isgiven below: Thanks in advance.
OK, so you probably need to take a step back and see the two aspects here:
One aspect is that you can directly draw on a Graphics2D object, printing strings, draw lines, fill rectangles, etc... While this can be very interesting in some situations (if you want to perform very custom drawings, for example), this is a very low level approach. You're in charge of doing a lot of things. If you would consider handling a text field, this would mean that you would have to draw a background, a border, a string as it get typed, make a blinking caret, etc... This can easily become very cumbersome and tedious to maintain
The other aspect is that Swing provides a bunch of component which does already all the tedious work I just talked about. While it cannot handle all cases, simple cases such as labels, textfield, images, etc... already have a built-in implementation which basically avoids you the cumbersome work to do it yourself. The only thing left for you is to explain how and where you want your components to appear. This is where LayoutManager's come into play.
Here is a small example (amongst many other) which shows you the gist of doing such thing:
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BasicSwingTest {
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel image = new JLabel(new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Duke3D.png/220px-Duke3D.png")));
frame.setLayout(new BorderLayout());
frame.add(image, BorderLayout.WEST);
JPanel mainPanel = new JPanel(new GridBagLayout());
JPanel panel = new JPanel(new GridLayout(0, 2));
panel.add(new JLabel("Name: "));
JTextField name = new JTextField(20);
panel.add(name);
panel.add(new JLabel("Contact no: "));
JTextField contactNumber = new JTextField(15);
panel.add(contactNumber);
panel.setBorder(BorderFactory.createTitledBorder("Enter your details"));
mainPanel.add(panel);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new BasicSwingTest().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
And the outcome:
Here is a second example (looking a bit more like your image, although it needs a few tweaks):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BasicSwingTest2 {
private static final Font FONT = new Font("Times New Roman", Font.PLAIN, 18);
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JLabel contentPane = new JLabel(new ImageIcon(new URL("http://www.pd4pic.com/images/blue-background-simple.jpg")));
contentPane.setLayout(new BorderLayout());
frame.add(contentPane, BorderLayout.CENTER);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
JPanel panel = new JPanel(new GridBagLayout());
panel.setOpaque(false);
JTextField name = new JTextField(20);
JTextField contactNumber = new JTextField(15);
panel.add(getLabel("Name: "), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(name, gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
panel.add(getLabel("Contact no: "), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(contactNumber, gbc);
JLabel topLabel = getLabel("Please enter you details");
topLabel.setHorizontalAlignment(JLabel.CENTER);
contentPane.add(topLabel, BorderLayout.NORTH);
contentPane.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JLabel getLabel(String text) {
JLabel label = new JLabel(text);
label.setFont(FONT);
label.setForeground(Color.WHITE);
return label;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new BasicSwingTest2().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}

How can I attach the progress bar to when the JFrame Opens?

I want to attached the progress bar to the Frame and not the test start button that I have currently. The progress bar works but I want it run when the window is opened for the time being and then I can attach it to whatever I want later on.
Code:
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.JProgressBar;
import javax.swing.JButton;
public class ProgressBarWindow extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProgressBarWindow frame = new ProgressBarWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ProgressBarWindow() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) { }
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 183);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(22, 77, 386, 27);
contentPane.add(progressBar);
JButton btnNewButton = new JButton("Cancel");
btnNewButton.setBounds(319, 111, 89, 23);
btnNewButton.addMouseListener(new myMouseListener2());
contentPane.add(btnNewButton);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new btnDoAction(progressBar));
btnStart.setBounds(220, 111, 89, 23);
contentPane.add(btnStart);
}
}
class myClose implements MouseListener {
myClose() { }
#Override
public void mouseClicked(MouseEvent e) {
final Component source = e.getComponent();
final JFrame frame = (JFrame) SwingUtilities.getRoot(source);
frame.dispose();
}
#Override
public void mousePressed(MouseEvent e) {
final Component source = e.getComponent();
final JFrame frame = (JFrame) SwingUtilities.getRoot(source);
frame.dispose();
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class btnDoAction implements ActionListener{
JProgressBar temp = new JProgressBar();
btnDoAction(JProgressBar p) {
this.temp = p;
}
public void actionPerformed (ActionEvent e){
new Thread(new thread1(temp)).start(); //Start the thread
}
}
class thread1 implements Runnable{
JProgressBar pBar = new JProgressBar();
thread1(JProgressBar u) {
this.pBar = u;
}
public void run(){
for (int i=0; i<=100; i++){ //Progressively increment variable i
pBar.setValue(i); //Set value
pBar.repaint(); //Refresh graphics
try{Thread.sleep(50);} //Sleep 50 milliseconds
catch (InterruptedException err){}
}
}
}
If I understand correctly, instead of using a JFrame as you base component, extend your class from a JPanel, this way you can add it to anything you want.
You could then provide setter and getter methods to adjust the progress bar, but I'd do this via some kind of interface contract .
Don't use null layouts. You don't control aspects like fonts, font metrics, rendering pipelines and other properties which effect the amount of space components need in order to be rendered properly across multiple systems (even those running the same OS)
Don't use MouseListeners on buttons, use ActionListeners instead. To takes into account when the use clicks on the button and presses space/Zener
Don't update the UI from any thread other then the a Event Dispatching Thread. See Concurrency in Swing for more details. Consider using a SwingWorker instead, it has functionality to sync the background thread with the EDT and in built progress support
Updated
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
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.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutExample {
public static void main(String[] args) {
new LayoutExample();
}
public LayoutExample() {
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 ProgressPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ProgressPane extends JPanel {
private JProgressBar pb;
private JButton start;
private JButton cancel;
public ProgressPane() {
pb = new JProgressBar();
start = new JButton("Start");
cancel = new JButton("Cacnel");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(50, 10, 5, 10);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.gridwidth = 2;
add(pb, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(0, 0, 0, 5);
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.EAST;
add(start, gbc);
gbc.weightx = 0;
gbc.gridx = 1;
gbc.insets = new Insets(0, 0, 0, 10);
gbc.anchor = GridBagConstraints.WEST;
add(cancel, gbc);
}
}
}

How to set Text like Placeholder in JTextfield in swing

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.

Categories