JLabel not updating - java

so thanks for looking at my question,Well anyways im trying to make a cookie clicker clone (if you could call it that) where you click the button and the JPanel updates, unfortunately the JPanel doesn't update and I just cant find an answer anywhere else, Any help is valuable help, thank you! Here is my code:
public int numCookies;
public main(){
//JButton
JButton click = new JButton("Click");
click.setLayout(null);
click.setLocation(50, 50);
click.setSize(80, 50);
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
}
});
//JLabel
JLabel cookies = new JLabel();
cookies.setLayout(null);
cookies.setText("Cookies:" + numCookies);
cookies.setLocation(480/2,10);
cookies.setSize(200, 50);
//JPanel
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setLocation(10, 0);
panel.setSize(260, 30);
panel.add(click);
panel.add(cookies);
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String args[]){
new main();
}

Three things...
One...
Use of null layouts. Don't be surprised when things go wrong. When using JLabel or JButton, unless you intend to actually add something to them, you don't need to touch there layout managers.
Make use of approriate layout managers
Two...
Calling setVisible on your frame before you've finished filling it out...
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
// No idea what you expect this to be doing...
pack();
//frame.setVisible(true);
frame.add(panel);
// This belongs here...and you shouldn't pack a window until
// it's ready to be made visible...
frame.setVisible(true);
Three...
You seem to expect that the lable will magically now that the value numCookies has changed...
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
// ??????
}
You need to reassign the value to the label in order for the label to be updated...
For example...
public main(){
//JLabel
// Make the lable final...so we can access from witin
// the listener...
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
//JButton
JButton click = new JButton("Click");
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});
Bonus
Make sure you read through and understand Initial Threads
...And just because null layouts annoy me so much...
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.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public int numCookies;
public Main() {
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cookies.setText("Cookies:" + (++numCookies));
}
});
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(cookies, gbc);
frame.add(click, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
new Main();
}
});
}
}

Set the text of the JLabel in the actionPerformed method like this:
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});

Related

How to use setOpaque(true/false) in an if statement

My JLabel won't change to a blue background. The JLabel is already set to the blue background but it is not opaque until you press the button. Why is it still not opaque?
Does setOpaque work for if statements?
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.*;
public class TestOpaque {
public static void main (String args[])
{
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label with blue background");
label.setBackground(Color.BLUE);
label.setOpaque(false);
frame.add(label, BorderLayout.WEST);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (label.isOpaque() == false) {
label.setOpaque(true);
label.revalidate();
}
}
});
frame.add(button, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
}
The if statement works fine, although better to use if (!label.isOpaque()) {
You need to redraw the GUI component via repaint() for the background to show:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!label.isOpaque()) {
label.setOpaque(true);
label.revalidate();
label.repaint();
}
}
});

Replace ImageIcon with JButton pressed

I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.

How to execute a .java file on clicking a jbutton in jframe?

On clicking the jbutton in a jframe, I want Start.java file to be executed;what to do?
The Start.java is executing well. I want the same execution to be done when clicked on jbutton in jframe, please help me out.
My jframe code has jbutton
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
// i want to execute Start.java file on clicking the button
Start s = new Start();
String in = s.getTxt;
System.out.println(in);
repaint();
}
My Start.java file is :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Start extends JPanel{
public String getTxt;
public Start()
{
final JTextField jf = new JTextField(20);
jf.setBounds(30, 30, 250, 30);
final JButton j1 = new JButton("OK");
j1.setBounds(80, 80, 100, 30);
setLayout(null);
add(jf);
add(j1);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310,250));
f.setMaximumSize(new Dimension(310,250));
f.setMinimumSize(new Dimension(310,250));
f.pack();
f.setVisible(true);
}
}
So, based on what you seem to be doing in your code, I would strongly recommend that you have a look at How to Make Dialogs, the main reason for this is, a modal dialog will cause the execution of your program to stop at the point where the dialog is made visible and resume when it's closed, this way, allowing you to inspect the values the user might have changed.
So, when I first tried to get your program to work, this is what happened...
So, after digging into your code, I noticed you'd done setLayout(null);. This is going to keep on coming back to haunt you and I strongly recommend that you don't do this and learn how to use the layout management API.
So, I jumped into you code and add a layout manager...
public class Start extends JPanel {
public String getTxt;
public Start() {
final JTextField jf = new JTextField(20);
final JButton j1 = new JButton("OK");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
add(j1, gbc);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
Now I get...
Okay, but now there's two buttons, and unless the user clicks the middle button, the text is never set!
The fact is, for this kind of thing, you don't need the button! You just need a method which can return the current text of the JTextField, for example...
public class Start extends JPanel {
final JTextField jf = new JTextField(20);
public Start() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
}
public String getText() {
return jf.getText();
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
And then I can use...
import java.awt.Dimension;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
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();
}
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());
JButton btn = new JButton("Surprise");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Start start = new Start();
JOptionPane.showMessageDialog(TestPane.this, start, "Surprise", JOptionPane.PLAIN_MESSAGE);
System.out.println(start.getText());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
to show it!
I'd strongly recommend that you take the time to have a look at Laying Out Components Within a Container

I need to listen to a JFrame button and get it to update a boolean value

I have no idea how to do this and have spent 2 days researching the Java APIs and on these forums and I have found nothing, if someone could please tell me how to use action listener to do so that would be great, most everything I have found has been for JUST a button and not with a bunch of other stuff. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Skeleton extends JFrame implements ActionListener{
public static void addComponentsToPane(Container pane) {
pane.setLayout(null);
JButton b1 = new JButton("Login");
JTextField field2 = new JTextField(2);
JTextField field = new JTextField(1);
pane.add(field);
pane.add(field2);
pane.add(b1);
Insets insets = pane.getInsets();
Dimension size = field.getMaximumSize();
field.setBounds(25 + insets.left, 5 + insets.top,
200, 20);
size = field2.getPreferredSize();
field2.setBounds(25 + insets.left, 40 + insets.top,
200, 20);
size = b1.getPreferredSize();
b1.setBounds(75 + insets.left, 75 + insets.top, 100, 40);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("User Login"); // GUI gui = new GUI() as well
// default value JFrame.HIDE_ON_CLOSE
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
addComponentsToPane(frame.getContentPane());
//Create the menu bar. Make it have a Blue background.
JMenuBar blueMenuBar = new JMenuBar();
blueMenuBar.setOpaque(true);
blueMenuBar.setBackground(new Color(211, 221, 222));
blueMenuBar.setPreferredSize(new Dimension(300, 20));
//Create a grey label to put in the content pane.
JLabel greyLabel = new JLabel();
greyLabel.setOpaque(true);
greyLabel.setBackground(new Color(205, 209, 209));
greyLabel.setPreferredSize(new Dimension(300, 400));
//Adding a custom BorderLayout
JPanel panel = new JPanel(new BorderLayout());
Container contentPane = frame.getContentPane();
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(blueMenuBar);
frame.getContentPane().add(greyLabel, BorderLayout.CENTER);
//Display the window.
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
You simply add an ActionListener to the button:
boolean state = false;
JButton b1 = new JButton("Login");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// some action to perform
state = true;
}
});

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