Prompt for JTextField makes it shade gray - java

I am playing around with Prompt's with JTextFields,
Just one problem:
As you can see, The background is shaded gray a little, I even tried to set the background color to white and it is still gray. Heres my current code for setting a prompt:
final JTextField aText = new JTextField(6);
final JTextField bText = new JTextField(6);
PromptSupport.setPrompt("Digit", aText);
Is this correct? Thanks.

This seems to be a bug between PromptSupport and MaxOS X (or at least that's where I had problems)
I tried using PromprtSupport.setBackground but that didn't seem to work, so I ended up using PromptSupport.setBackgroundPainter instead
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.painter.Painter;
import org.jdesktop.swingx.prompt.PromptSupport;
public class TestPrompt {
public static void main(String[] args) {
new TestPrompt();
}
public TestPrompt() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTextField prompt = new JTextField(20);
PromptSupport.setPrompt("Go ahead, make my day", prompt);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, prompt);
PromptSupport.setBackgroundPainter(new Painter() {
#Override
public void paint(Graphics2D g, Object object, int width, int height) {
g.setColor(UIManager.getColor("TextField.background"));
g.fillRect(0, 0, width, height);
}
}, prompt);
prompt.setOpaque(true);
JTextField noPrompt = new JTextField(20);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
frame.add(prompt, gbc);
frame.add(noPrompt, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
This is a work around, not a solution as there are still some issues...

Related

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 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.

Java - is it possible to apply setEditable(boolean b) to JSlider/

in my program I need to disable my JSlider under certain circumstances, but do not know how. I tried setFocusable(false) but that did not work... Thanks in advance!
You change/restrict user interactions with the JSlider through the use of the enabled property.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SliderTest {
public static void main(String[] args) {
new SliderTest();
}
public SliderTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JSlider slider = new JSlider();
final JCheckBox checkBox = new JCheckBox();
checkBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
slider.setEnabled(checkBox.isSelected());
}
});
checkBox.setSelected(true);
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(slider, gbc);
frame.add(checkBox, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Try the setEnabled(boolean) method. All JComponents inherit it by default.

Incorrect JPanel position in GridBagLayout

im using GridBag to display some JPanels with images inside a JScrollPane.
When there are 3 or more images the GridBagConstraints work ok but when i have 1 or 2, they get aligned to the center of the JScrollPane instead of being in their position in the top (like in a gallery)
Here is my code:
JPanel jPanel1 = new JPanel();
GridBagLayout layout = new GridBagLayout();
jPanel1.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
JPanel photo = new JPanel();
Dimension d = new Dimension(100,100);
photo.setPreferredSize(d);
gbc.insets = new Insets(0,3,3,3);
gbc.gridx = i;
gbc.gridy = j;
jPanel1.add(photo, gbc);
jScrollPane1.setViewportView(jPanel1);
I have omitted the part where i assign an image to the photo Jpanel.
I want the JPanels to stay static in their places and do not align if there is free space.
If im not being clear i can upload a few snaps.
Thanks!
GridBagLayout layouts its components out around the center of the container, this is it's (and sometimes annoying) default functionality.
You could try adding an empty "filler" component (say a JLabel) with the GridBagConstraints of weightx=1 and weighty=1 at a position right of and below the other components in the container. This will force them to the top/left corner of the container...
Updated...
Centered/default...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GridBagLayoutTest {
public static void main(String[] args) {
new GridBagLayoutTest();
}
public GridBagLayoutTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(600, 600);
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;
JLabel picture = new JLabel();
try {
picture.setIcon(new ImageIcon(ImageIO.read(new File("/path/to/your/picture"))));
} catch (IOException ex) {
ex.printStackTrace();
picture.setText("Bad picture");
}
add(picture, gbc);
}
}
}
Aligned...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GridBagLayoutTest {
public static void main(String[] args) {
new GridBagLayoutTest();
}
public GridBagLayoutTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(600, 600);
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;
JLabel picture = new JLabel();
try {
picture.setIcon(new ImageIcon(ImageIO.read(new File("/path/to/your/picture"))));
} catch (IOException ex) {
ex.printStackTrace();
picture.setText("Bad picture");
}
add(picture, gbc);
JLabel filler = new JLabel();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
add(filler, gbc);
}
}
}

How to make the component to respect column and row Weights?

public class Tester {
public static class Frame extends JFrame {
public Frame() {
// Layout
GridBagLayout layout=new GridBagLayout();
layout.columnWeights=new double[] { 0.5, 0.5 };
layout.rowWeights=new double[] { 1 };
// Frame
setLayout(layout);
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Constraints
GridBagConstraints c=new GridBagConstraints();
c.fill=GridBagConstraints.BOTH;
// Panel 1
JPanel p1=new JPanel();
p1.setBackground(Color.green);
c.gridx=0;
c.gridy=0;
add(p1,c);
// Panel 2
JLabel l1=new JLabel("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST" +
"TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST");
l1.setBackground(Color.yellow);
c.gridx=1;
c.gridy=0;
add(l1,c);
}
}
public static void main(String[] args) {
new Frame().setVisible(true);
}
}
In this case l1 takes whole space, I want it to take half, as this one says:
layout.columnWeights=new double[] { 0.5, 0.5 };
I put c.fill=GridBagConstraints.BOTH; because I want: if the frame get resized, i want also the component to be resized, but to take maximum 50% space.
You could add a "filler" component to the "empty" side...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout24 {
public static void main(String[] args) {
new TestLayout24();
}
public TestLayout24() {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 0.5f;
gbc.weighty = 0.1f;
gbc.fill = GridBagConstraints.BOTH;
JPanel left = new JPanel();
left.setBackground(Color.RED);
JPanel right = new JPanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(left, gbc);
frame.add(right, gbc);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Or
You could use GridLayout instead...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout24 {
public static void main(String[] args) {
new TestLayout24();
}
public TestLayout24() {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel left = new JPanel();
left.setBackground(Color.RED);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(left);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I figure it out, setting this for the Label, it makes your life much easier!!!!
l1.setMinimumSize(new Dimension(0,0));
l1.setPreferredSize(new Dimension(0, 0));
Thanks for help...

Categories