Display Jlabel based on JtextArea dynamically without button click - java

I have been wondering if it is possible to update JFrame or JDialogs based on the inputs inside jtextarea without button click. For an example, after i input some text in textarea. it should automatically update jlabel without the need of a button. I have search troughout but all the information i found is only based on button click . For an example ,
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(0, 1));
JTextArea input = new JTextArea();
JLabel output = new JLabel("test");
// Condition
// If user input "abc" inside textfield
// JLabel will automatically display "abc"
frame.add(input);
frame.add(output);
frame.setSize(300,400);
frame.setVisible(true);
Do i need to refresh the entire frame ? will it affect all the other textfield that user have already fill back to empty?
Thanks

Document object contained by JTextArea receives updates.
JTextArea input = new JTextArea();
input .getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {}
#Override
public void insertUpdate(DocumentEvent e) {}
#Override
public void changedUpdate(DocumentEvent arg0) {
//Add logic here to check if particular word is entered.
//if yes show label, else hide the label object
}
});

Related

GUI login system not react while clicking OK button

hope you are ok this evening.
I have a problem with GUI login system. I was able to create frame with labels and fields to input user name and password, however when I'm clicking the OK button it doesn't react to my action and not changing color what I like.
Can you take a look please ?
public class LoginPanel extends JPanel implements ActionListener {
JFrame frame; // frame
static JTextField userField; // field to get user name
JLabel userLabel; // using for printing label on frame
static JPasswordField passwordField; // field where you put your passowrd
JButton loginButton; // add OK button below login
public LoginPanel () {
super();
frame = new JFrame ("Login"); // initial frame, add title
frame.setSize(500, 500); // frame size
frame.setLocation(300, 200); // set where program window should start
frame.setLayout(null); // set layout; you can use (new FlowLayout (FlowLayout.LEFT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closing the program by clicking X
userLabel = new JLabel("enter user name label"); // create Label next to the user field
userLabel.setLocation(10, 10); // set location where label will start to appear
userLabel.setSize (userLabel.getPreferredSize()); //
frame.add(userLabel); // add userLabel to the frame
userField = new JTextField (); // initial text field for user name
userField.setColumns(25);
userField.setSize(userField.getPreferredSize()); // set text field size //
userField.setLocation(150, 10); // set where text field will apear on frame;
userField.setToolTipText("enter user name"); // when you move the mouse on the field, you will get a hint
frame.add(userField); // add userfield to the frame
userLabel = new JLabel("enter password label"); // create Label next to the password field
userLabel.setLocation(10, 40); // set location where label will start to appear
userLabel.setSize (userLabel.getPreferredSize()); //
frame.add(userLabel); // add label to the frame
passwordField = new JPasswordField (); // add password field next to the label
passwordField.setColumns(25); //
passwordField.setSize(userField.getPreferredSize()); // set text field size
passwordField.setLocation(150, 40); // set location where password field will apear
passwordField.setToolTipText("enter password"); // when you move the mouse on the field, you will get a hint
frame.add(passwordField); // add password field to the frame
loginButton = new JButton("OK"); // add OK button
loginButton.setSize(loginButton.getPreferredSize()); //
loginButton.setLocation(150, 80); // set where ok button appears
loginButton.addActionListener(this); // add action listener to the button when click to the button then method actionPerformed
frame.add(loginButton); // add button to the frame
frame.setVisible(true); // frame visibility; ALWAYS at the end, because will not show entire content of frame
} // end of Login Panel code
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(passwordField.equals("1234") && (userField.equals("tomek"))) {
setBackground(Color.GREEN);
}
else {
setBackground(Color.RED);
}
}
public static void main (String [] args) { // adding at the end as every program need to have main method
new LoginPanel(); // run method LoginPanel
}
Try doing this
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (new String(passwordField.getPassword()).equals("1234") && (userField.getText()
.equals("tomek"))) {
frame.getContentPane().setBackground(Color.GREEN);
} else {
frame.getContentPane().setBackground(Color.RED);
}
}
you should call setBackground on the ContentPane of the JFrame not on the actual panel as your are not using it
you should compare your JTextField and JPasswordField contents not the components to the username tomek and password 1234

How to get the values from JPanel components like drop down, text fields which are getting created on a fly

I have a JPanel which consists of a dropdown and a text field inside my JFrame. There is a button in my JFrame, when user clicks on that button, application adds new JPanel with the same components i.e. drop down and a text field. So, for this I have created a function which gets called on clicking on the button using ActionListener.
Everything works fine from GUI side but the problem is when user is done with adding JPanels and entering the values in these drop downs and text fields, it will click on Submit button. Upon clicking on Submit button, I should be able to fetch the values from all drop downs and text fields. This is a challenge, since I am using the same functions to create JPanels, I can't call its name to get the values since that will give me the last JPanel values.
Any suggestion how I should go about this? I have added the screenshot of my JFrame and the function to create the JPanel. Any help is appreciated. Thanks.
public static void AddPanel(final Container pane) {
panel1 = new JPanel();
String text = "<html><b>Property" + nooftimes + " :</b></html>";
JLabel label = new JLabel(text);
label.setPreferredSize(new Dimension(80, 30));
panel1.add(label);
panel1.add(new JLabel("Please enter the property"));
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
model.addElement("value1");
model.addElement("value2");
model.addElement("value3");
model.addElement("value4");
model.addElement("value5");
final JComboBox<String> comboBox1 = new JComboBox<String>(model);
AutoCompleteDecorator.decorate(comboBox1);
comboBox1.setPreferredSize(new Dimension(120, 22));
panel1.add(comboBox1);
final JTextField txtfield1 = new JTextField(
"Please enter your value here");
txtfield1.setPreferredSize(new Dimension(200, 22));
panel1.add(txtfield1);
txtfield1.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
txtfield1.setText("");
}
public void focusLost(FocusEvent e) {
// nothing
}
});
container.add(panel1);
nooftimes++;
frame.revalidate();
frame.validate();
frame.repaint();
}
Screenshot:
}
You could return the JPanel and store it in a List<JPanel>. When you click your submit-Button you are able to iterate through the JPanels and its Components.
public class Application {
private static List<JPanel> panels = new ArrayList<>();
private static Container someContainer = new Container();
public static void main(String[] args) {
panels.add(addPanel(someContainer));
panels.add(addPanel(someContainer));
panels.add(addPanel(someContainer));
submit();
}
public static JPanel addPanel(final Container pane) {
JPanel panel1 = new JPanel();
// shortened code
final JComboBox<String> comboBox1 = new JComboBox<String>();
panel1.add(comboBox1);
final JTextField txtfield1 = new JTextField("Please enter your value here");
txtfield1.setText(String.valueOf(Math.random()));
panel1.add(txtfield1);
return panel1;
}
private static void submit() {
for (JPanel panel : panels) {
Component[] components = panel.getComponents();
for (Component comp : components) {
// Cast comp to JComboBox / JTextField to get the values
if (comp instanceof JTextField) {
JTextField textField = (JTextField) comp;
System.out.println(textField.getText());
}
}
}
}
}
You could simply have a class (extending JPanel) with specific methods to add your components , and to get inputs from user (i.e. get the combo box selected index and text from textfield ).
Every time you add a panel, you don't call a static method, but you create an instance of this class, keeping the reference somewhere (for example adding it to an arraylist).
But you could consider a different scenario: personally i don't like to add components "on fly", you could have a component (for example another JComboBox), where user can select the number of values he needs.
You decide a default value (for example 4), so at the beginning you create 4 panels of your class, and you can use a simple array containing them.
If the user changes the number of panels, you could dispose frame and create a new one.
Of course this solution does not woork good if you want to keep inputs inserted, or if the frame construction takes a lot of time.
Here there is a screenshot of a gui i created: user can select the number of partials, when the choice changes i just recreate the panels below,containing the textfields (which are memorized in a two-dimensional array).

How to update JTextfield after click SAVE button

I have a main frame : JFrame>contentFrame>ScrollPane>BigPanel>panel_1T
private JPanel contentPane;
private JPanel BigPanel;
private JPanel panel_1T;
In panel_1T, I have put a FOOD button WITH its actionListener:
JButton button_19 = new JButton("FOOD");
button_19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
});
panel_1T.setLayout(new GridLayout(0, 2, 0, 0));
panel_1T.add(button_19);
When user click FOOD button, new JFrame in newFoodUI class will be shown.:
JFrame>contentPane>panel>tabbedPane>panel_3>panel_5
In panel_5, I put a JTextField:
public static JTextField textField_3;
textField_3 = new JTextField();
panel_5.add(textField_3, "9, 4, fill, default");
textField_3.setColumns(10);
User will write some text into textField_3. Then user click SAVE button in panel_3, it will perform this:
JButton button_4 = new JButton("SAVE");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setContentPane(contentPane);
panel_3.revalidate();
panel_3.repaint();
panel_3.updateUI();
panel_5.revalidate();
panel_5.repaint();
panel_5.updateUI();
contentPane.revalidate();
contentPane.repaint();
JOptionPane.showMessageDialog(null, "Saved !");
}
});
button_4.setBounds(873, 396, 75, 33);
contentPane.add(button_4);
}
The result is, when I click SAVE button and close the Frame in newFoodUI, I will reopen back by click the FOOD button to check whether the text I wrote has been saved or not. But its not saving the text I wrote.
You have to save the value from the textfeld textField_3.getText() and set this value manually to textfeld when showing textField_3.setText(value). So you have to keep your value in your project or store persistent somewhere.
There are a couple of things to fix here and I will not give you complete code but I will point out some errors. First let's consider your button_19 listener
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
When this is performed, it creates a totally new object of newFoodUI and gives it no parameters. So how could this frame know about anything that happened before its creation if you give it nothing? Additionally, you explicitly say DISPOSE_ON_CLOSE, when you could use HIDE_ON_CLOSE if you wish to reuse it.
Then in your JButton button_4 = new JButton("SAVE"); listener you want to save the data in the text field, but your implementation does nothing to the text field. You should, for example, get the text from textField_3 and write it to a file or send back to the first JFrame.
Then there is the issue of using multiple JFrames in the first place.

Unable to add text to JTextArea in Java from another function

I made a simple program in Java that contains only one text area and a button. The button is suppose to add a "text". However, it doesn't work for me.
On a side note: I'm trying to keep my functions as short as possible. (I don't want a function with too many line of codes)
First, I create the JFrame
private static void createFrame()
{
//Build JFrame
JFrame frame = new JFrame("Text Frame");
frame.setLayout(null);
frame.setSize(500,400);
Container contentPane = frame.getContentPane();
contentPane.add(textScrollPane());
contentPane.add(buttonAddText());
//Set Frame Visible
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Then the TextArea and the Scrollpane (for adding scrollbar)
private static JTextArea textArea()
{
JTextArea output = new JTextArea();
output.setLineWrap(true); // Text return to line, so no horizontal scrollbar
output.setForeground(Color.BLACK);
output.setBackground(Color.WHITE);
return output;
}
private static JScrollPane textScrollPane()
{
JScrollPane scrollPane2 = new JScrollPane(textArea());
scrollPane2.setBounds(0, 0, 490, 250);
return scrollPane2;
}
And finally, the button
private static JButton buttonAddText()
{
JButton testbutton = new JButton("TEST");
testbutton.setBounds(20, 280, 138, 36);
testbutton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
//action listener here
textArea().insert("TEXT",0);
System.out.println("Button Tested!");
}
});
return testbutton;
}
When I click on the button, it doesn't do anything.
I just want a text to be added in the JTextArea. Did I forget something?
textArea() is returning a new JTextArea everytime it is called. Therefore your buttonAddText() function is calling textArea() and adding text to a newly created text area that is not contained in the scroll pane.
You need to pass a reference of the text area to the textScrollPane() and the buttonAddText() functions.
Something like this would work:
JTextArea jta = textArea();
contentPane.add(textScrollPane(jta));
contentPane.add(buttonAddText(jta));
Change textScrollPane() and buttonAddText() so that they accept a JTextArea parameter and don't call textArea() in these functions anymore to create new text areas. Instead use the JTextArea object which is passed into the functions.

Java- How to add more textfields by clicking a button?

I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).

Categories

Resources