Java Swing Jtextfield Set Placeholder

java swing JTextField set PlaceHolder

Try this class:

package playground;

import java.awt.*;

import javax.swing.*;
import javax.swing.text.Document;

@SuppressWarnings("serial")
public class PlaceholderTextField extends JTextField {

public static void main(final String[] args) {
final PlaceholderTextField tf = new PlaceholderTextField("");
tf.setColumns(20);
tf.setPlaceholder("All your base are belong to us!");
final Font f = tf.getFont();
tf.setFont(new Font(f.getName(), f.getStyle(), 30));
JOptionPane.showMessageDialog(null, tf);
}

private String placeholder;

public PlaceholderTextField() {
}

public PlaceholderTextField(
final Document pDoc,
final String pText,
final int pColumns)
{
super(pDoc, pText, pColumns);
}

public PlaceholderTextField(final int pColumns) {
super(pColumns);
}

public PlaceholderTextField(final String pText) {
super(pText);
}

public PlaceholderTextField(final String pText, final int pColumns) {
super(pText, pColumns);
}

public String getPlaceholder() {
return placeholder;
}

@Override
protected void paintComponent(final Graphics pG) {
super.paintComponent(pG);

if (placeholder == null || placeholder.length() == 0 || getText().length() > 0) {
return;
}

final Graphics2D g = (Graphics2D) pG;
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getDisabledTextColor());
g.drawString(placeholder, getInsets().left, pG.getFontMetrics()
.getMaxAscent() + getInsets().top);
}

public void setPlaceholder(final String s) {
placeholder = s;
}

}

How to set Text like Placeholder in JTextfield in swing

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)

PromptSupport

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

}

Placeholder in JTextField - Java Swing

The SwingX library which can be used alongside normal Swing takes cares of this when you initialize a JXTextField and does the same for JXTextArea too.

JXTextField text = new JXTextField("Your Prompt Here");
text.setPrompt("New Prompt");
frame.add(text, BorderLayout.CENTER);

Java: Add Place Holder on JTextField

Check out Text Prompt for a flexible solution.

You can control when prompt is displayed (always, focus gained or focus lost). You can also customize the style of the text.

Java - placeholder on textfield

I found this on the oracle forums.

public class TextFieldWithPrompt extends JTextField{

@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);

if(getText().isEmpty() && ! (FocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == this)){
Graphics2D g2 = (Graphics2D)g.create();
g2.setBackground(Color.gray);
g2.setFont(getFont().deriveFont(Font.ITALIC));
g2.drawString("zip", 5, 10); //figure out x, y from font's FontMetrics and size of component.
g2.dispose();
}
}

https://forums.oracle.com/forums/thread.jspa?threadID=1349874

How are partial methods used in C# 3.0?

Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.

A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.

The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.

The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.

  • In .Net 1 it was auto-generated code in a #region block
  • In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer

This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.

In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.

The extra bit here is that code needed to provide methods that developers might want to fill in.

As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.

The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.

Empty methods are not optimised out.

So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.

So that it can do this partial methods always return void.

If you create a new Linq DBML file it will auto-generate a partial class, something like

[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]
public partial class MyDataContext : System.Data.Linq.DataContext
{
...

partial void OnCreated();
partial void InsertMyTable(MyTable instance);
partial void UpdateMyTable(MyTable instance);
partial void DeleteMyTable(MyTable instance);

...

Then in your own partial file you can extend this:

public partial class MyDataContext
{
partial void OnCreated() {
//do something on data context creation
}
}

If you don't extend these methods they get optimised right out.

Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.

The example I mentioned before is one possibility:

//this code will get optimised out if no body is implemented
partial void DoSomethingIfCompFlag();

#if COMPILER_FLAG
//this code won't exist if the flag is off
partial void DoSomethingIfCompFlag() {
//your code
}
#endif

Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.



Related Topics



Leave a reply



Submit