Swing/Java: How to use the getText and setText string properly - java

I'm trying to make input nameField appear in a Label called label1 after a Button called button1 is clicked.
Right now it says: 'txt' and I understand why. But I don't know how I can use the string!
Can anyone explain me what I'm doing wrong and how to use this string properly?
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class thisismytest2 {
public static void main(String[] args) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField nameField = new JTextField("...", 2);
JButton button1 = new JButton();
final JLabel label1 = new JLabel();
label1.setText("txt");
label1.setVisible(false);
String txt = nameField.getText();
frame.add(panel);
panel.add(button1);
panel.add(label1);
frame.setSize(200,200);
frame.setVisible(true);
panel.add(nameField);
frame.setSize(600,400);
nameField.setBounds(400, 40, 400, 30);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label1.setVisible(true);
}
});
}
}

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.
Example:
label1.setText(nameField.getText());

in your action performed method, call:
label1.setText(nameField.getText());
This way, when the button is clicked, label will be updated to the nameField text.

the getText method returns a String, while the setText receives a String, so you can write it like label1.setText(nameField.getText()); in your listener.

Setup a DocumentListener on nameField. When nameField is updated, update your label.
http://download.oracle.com/javase/1.5.0/docs/api/javax/swing/JTextField.html

Related

How to receive input from textfield to textarea and a lot more...?

enter image description here
How can I make it like that?
1) If user opens that program, you don't have to click on textfield to receive focus, instead, if you switch to that program, it immediatetly gives you a focus to write instead of clicking for focus.
2) If user writes a ID number or item name to textfield, textarea responds to textfield and shows that ID or name to the user, like, pops up.
3) How to make textarea smaller in case, that even panel shows out in corners? I'd like to make a textarea a little bit smaller like a box and outside a box, its just a gray color.
In order to fully help me, I'll gladly give out the code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
public abstract class Itemlist extends JFrame implements ActionListener, FocusListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
// create JFrame
JFrame frame = new JFrame("small project");
frame.setDefaultCloseOperation(2);
frame.setPreferredSize(new Dimension(400, 600));
frame.setLayout(new BorderLayout());
frame.setResizable(false);
JPanel panel = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 10));
frame.add(panel);
panel.setPreferredSize(new Dimension(100, 50));
JTextField tf = new JTextField(25);
tf.setPreferredSize(new Dimension(100, 35));
Font f = new Font("Times New Roman", Font.BOLD, 18);
tf.setFont(f);
panel.add(tf);
frame.add(tf, BorderLayout.PAGE_END);
tf.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
tf.getText();
}
#Override
public void focusLost(FocusEvent e) {
tf.setText("");
}
});
JTextArea ta = new JTextArea();
frame.add(ta);
Font font = new Font("Times New Roman", Font.PLAIN, 16);
ta.setEditable(false);
ta.setFont(font);
JScrollPane scrollPane = new JScrollPane(ta);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
frame.add(scrollPane);
BufferedReader br;
String contents;
try {
br = new BufferedReader(new FileReader("C:/ItemList.txt"));
contents = br.readLine();
while ((contents = br.readLine()) != null) {
ta.read(br, null);
}
br.close();
} catch (IOException e) {
}
frame.pack();
// frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
}
*All help is appreciated. Have been stuck on it.
I suspect you want to consider using a WindowListener and monitor for the windowActivated event, at which time you can call requestFocusInWindow on the JTextField to transfer focus to it automatically. Focus management is a little bit of a black art, as it tends to work slightly differently on different platforms
I'm not sure entirely what you mean, but I'd look at the ActionListener support. This will require the user to hit the "action" key (typically Enter) to trigger it. If you want real time feedback, the a DocumentListener would be what you're looking for
Make use of the JTextAreas constructor to specify the preferred number of rows and columns. This will define the preferred scrollable size of the component, which will effect the size of the JScrollPane as well
In future, try and constrain you question to single, focused question, they are easier to answer and generally produce more detail

Why is my JPanel empty after button is clicked?

I'm learning how to create event listeners in Java for a button click. I want a panel to popup with form items. I've built the panel in the action listener's contructor, but it's empty when it opens. I thought it makes sense to only build this one, then just show it when the button is clicked (actionPerformed). Obviously not :)
Below is my ActionListener class:
package biz.martyn.budget;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NewTransaction implements ActionListener {
protected JPanel panel = new JPanel(new GridLayout(0, 1));
public void NewTransaction() {
String [] category = {"Internet", "Clothes", "Rent", "Salary", "Groceries"};
JComboBox combo = new JComboBox(category);
panel.add(combo);
panel.add(new JLabel("Description:"));
JTextField desc = new JTextField();
panel.add(desc);
panel.add(new JLabel("Date:"));
JTextField date = new JTextField();
panel.add(date);
panel.add(new JLabel("Amount:"));
JTextField amount = new JTextField();
panel.add(amount);
}
#Override
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.showConfirmDialog(null, panel, "New transaction",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
}
}
Here is how I'm attaching the event:
JButton newTransactionButton = new JButton("New transaction");
newTransactionButton.addActionListener(new NewTransaction());
toolbar.add(newTransactionButton);
I'd appreciate any additional advice on conventions when doing this sort of thing coz I'm quite the beginner, thanks.
I've built the panel in the action listener's contructor, but it's empty when it opens
The following...
public void NewTransaction() {
...is a method, not a Constructor. You need to explicitly call it, or change it to a constructor
public NewTransaction() {

How do i print a line of text when typing a certain number/word with a JTextField and JTextArea (JAVA)

MY CODE
package pack.TAgame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class AL_Test {
public static void main(String[] args){
//JFrame
JFrame Frame = new JFrame("AL Test");
Frame.setSize(720,480);
Frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Frame.setVisible(true);
Frame.setResizable(false);
//Text Area
JTextArea textArea = new JTextArea();
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.GRAY);
JLabel jl = new JLabel();
Frame.add(textArea);
textArea.setEditable(false);
//Text Field
JTextField jt = new JTextField(50);
JPanel jp = new JPanel();
jp.add(jt);
Frame.add(jt, BorderLayout.SOUTH);
class UserInput extends JFrame implements ActionListener{
public UserInput() {
}
public void actionPerformed(ActionEvent e) {
JTextField jt = new JTextField();
JTextArea textArea = new JTextArea();
jt.addActionListener(this);
String text = jt.getText();
textArea.append("\n>What does the scouter say about his power level?");
}
}
}
}
This maybe a little like my other post...(In my code for the actionlistener part I gave up and I might have some useless code in it)
so basically I want a JTextField that when I type a certain command to print something into my JTextArea. (Without the use of a button (i.e. Press enter))
Start with the TextDemo.java code from the Swing tutorial on How to Use Text Fields. This example does exactly what you want:
it adds an ActionListener to the text field. The ActionListener is invoked when Enter is pressed and focus is on the text field.
The ActionListener will take the text from the text field and append it to a text area.
As a bonus you will also learn how to better structure your code by adding the components to a panel and then add the panel to the frame. The variables will be defined in the class as well.

Pass value from one JtextField to another?

//New to java swing and need help getting the text in the first Jtextfield to display in the //second second jtextfield???? Im young and just starting out in java and need some help. below is the code i have done already thanks
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class lab4 extends JFrame implements ActionListener {
int numClicks = 0;
String text = null;
public lab4() {
setSize(1200, 700);
setVisible(true);
JButton button = new JButton("Hello i am a button");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
panel.add(button);
this.add(panel);
JMenuBar menubar = new JMenuBar();
this.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem open = new JMenuItem("Open File");
file.add(open);
final JTextField myField = new JTextField(10);
myField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = myField.getText();
//System.out.println("Hello");
}
});
final JTextField myField2 = new JTextField(10);
yField2.setText(myField.getText());
panel.add(myField);
panel.add(myField2);
setVisible(true);
}
}
public static void main(String[] args) {
new lab4();
}
public void actionPerformed(ActionEvent e) {
numClicks++;
System.out.println("The button has been clicked " + numClicks + " times");
}
}
Yes, you are doing ok. If more then one work going to happen in sequence on one action event, then you need to put the sequence inside the corresponding actionPerformed function. So:
myField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String text = myField.getText();
myField2.setText(text);
}
});
JComponents listeners mean that they will listen and respond only when an action event occur. They will be notified by the instance of ActionListener registered to event source(JCompnent) with addActionListener() function as you have done.
One more thing to note: you can't access a field in any statement before even declaring it. Compiler's need to know the information about the field before doing anything with it. So you must declare myField2 before the accessing-code of it, such as, myField1's anonymous class ActionListener actionPerformed function.
Tutorial Resources:
Writing Event Listeners
Anonymous Class
You can share the model:
JTextField textField1 = new JTextField(...);
JTextField textField2 = new JTextField(...);
textField2.setDocument( textField1.getDocument() ):
Now whenever you type text in either text field the other will also be updated.

get text from jtextarea split it and pass it to jlabel on new line?

hi friends im new here i write a code in two classes where in one class i declare a jtextarea and a button when we click the button then text will split and it display in the jlabel but here is problem is that the text is written in jtext area and button also working but when jlabel frame open it show nothing here is my code
the first class
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
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.JTextArea;
public class Try extends JFrame {
JTextArea text;
String string;
public Try(){
super("survey");
Container container=getContentPane();
container.setLayout(new FlowLayout());
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(350,150));
string=text.getText();
JButton showDialogBtn = new JButton("Add Text");
container.add(text);
container.add( showDialogBtn);
showDialogBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlabel l=new jlabel();
l.setSize(700,700);
l.setVisible(true);
}
});
}
public static void main(String[] args) {
// TODO code application logic here
Try t=new Try();
t.setSize(400,500);
t.setVisible(true);
}
String getArray()
{
return string ;
}
}
But the second class that is jlabel class is not showing the required result plz help in this regard
import java.awt.Container;
import java.awt.Font;
import javax.swing.*;
class jlabel extends JFrame {
Try t=new Try();
public jlabel(){
JFrame frame=new JFrame("jlabel");
JPanel jp1=new JPanel();
String string=t.getArray();
String[] labelStrings = string.split(" \\s*");
for (String labelString : labelStrings)
{
// create JLabels and add
JLabel label = new JLabel(labelString);
jp1.add(label);
frame.add(jp1);
}
}
}
waiting for reply thanks in advance
Regards,
The first class is decent, but the "jLabel" class had so many bugs. Please see below the one that works.
A summary of the issues in the jlabel class:
Another Try object was instantiated and this instance was used
You were creating a new JFrame even though you were subclassing it already.
No layout manager.
And so on...
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Label extends JFrame {
public Label(String string) {
super("jlabel");
JPanel jp1 = new JPanel();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.Y_AXIS));
String[] labelStrings = string.split(" \\s*");
for (String labelString : labelStrings) {
// create JLabels and add
JLabel label = new JLabel(labelString);
jp1.add(label);
}
getContentPane().add(jp1);
}
}
In the Try class, initialize it this way:
Label l = new Label(text.getText());
The problem is that you call the getText() outside the actionPerformed() method. This method is run when the button is pressed, so if you want to get text then, you should call the method getText() within actionPerformed().
Your code gets text as soon as it is run and all it can find is nothing! So, that's what is pastes into the JLabel.

Categories

Resources