This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to print the user input on screen from a TextField using Java Swing
Please see the code below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swingtest extends JFrame implements ActionListener{
JTextField txtdata;
JButton calbtn = new JButton("Calculate");
public Swingtest()
{
JPanel myPanel = new JPanel();
add(myPanel);
myPanel.setLayout(new GridLayout(3, 2));
myPanel.add(calbtn);
calbtn.addActionListener(this);
txtdata = new JTextField();
myPanel.add(txtdata);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == calbtn) {
String data = txtdata.getText(); //perform your operation
System.out.println(data);
}
}
public static void main(String args[])
{
Swingtest g = new Swingtest();
g.setLocation(10, 10);
g.setSize(300, 300);
g.setVisible(true);
}
}
What I want to do is display the text entered in the field by the user in the same window. Kinda like with paint(Graphics g) and repaint() when the text is changed. Please help. Thanks.
Add a JLabel, JTextField, JTextArea or whatever component able to display text. Get the document of the JTextField where the user enters text, and add a DocumentChangeListener to this document. Each time a DocumentEvent is received, get the text from the JTextField and update the text in the JLabel, JTextField, JTextArea or whatever component you chose.
This can be done through redirecting the I/O/E streams:
I would have given you an elaborated answer, but the answerer of the answer selected for this question explains it better.
See this question: How could I read Java Console Output into a String buffer
After reading it into a StringBuffer, you can print it onto a JTextField or JTextArea.. etc
Related
This question already has answers here:
Need to read input of two JTextfields after a button is clicked
(2 answers)
Closed 8 years ago.
So I made a fully functional credit card validator which uses Luhn's Algorithm and all that jazz to validate the card type and number. It currently only uses Scanner and the console to print out stuff, but I wanted to take my program to the next level.
I wanted to make an application with Java graphics that can take in a credit card number entered into my applet/japplet/whatever you suggest and can essentially do the same process as the previously mentioned program, but I want to give it the aesthetic appeal of graphics.
So I'm honestly a little overwhelmed with the graphics in Java (not sure if that's weird), but here's what I want advice on.
How should I approach my graphics project? Should I use JApplet, Applet, JFrame, or something else?
I want to make a text field that the user enters his or her credit card into, what is the method of doing that? I looked up JTextFields but I'm at a loss on how to use it. I looked at the API but it doesn't do a very good job of explaining things in my opinion.
My main problem is the textfield, can someone give me an example of a textfield that can take in data that the user types? Sort of like Scanner in the console but in my graphics application.
Sorry for my word wall, you guys have been very helpful to me in the past :)
Tips, tricks, and anything else you think would help me out would be greatly appreciated.
Here is an example of a text field using swing:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame { // The JFrame is the window
JTextField textField; // The textField
public GUI() {
textField = new JTextField(10); // The user can enter 10 characters into the textField
textField.addActionListener(new ActionListener() { // This will listen for actions to be performed on the textField (enter button pressed)
#Override
public void actionPerformed(ActionEvent e) { // Called when the enter button is pressed
// TODO Auto-generated method stub
String inputText = textField.getText(); // Get the textField's text
textField.setText(""); // Clear the textField
System.out.println(inputText); // Print out the text (or you can do something else with it)
}
});
JPanel panel = new JPanel(); // Make a panel to be displayed
panel.add(textField); // Add the textField to the panel
this.add(panel); // Add the panel to the JFrame (we extend JFrame)
this.setVisible(true); // Visible
this.setSize(500, 500); // Size
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // Exit when the "x" button is pressed
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
jframe 1: the user will input the information that is asked on the text fields and when they click the get started button, the input should show in another jframe.
jframe 2: the information that was inputted in the text fields on jframe1 should appear on the jlabels.
Is it considered good practice to use two multiple frames? NO
Are there alternatives to using two frames? Yes
What are the alternatives? CardLayout, modal JDialog, among others
Will I still help you solve this query? Sure, why not?
Have an instance of the second frame in the first frame. Pass the information to the second JFrame constructor. It's that simple.
public class Frame1 extends JFrame {
String text1;
String text2;
Frame2 frame2; <--- second frame
....
public void actionPerformed(ActionEvent e) {
text1 = textField1.getText();
text2 = textField2.getText();
frame2 = new Frame2(text1, text2);
}
}
public class Frame2 extends JFrame {
String text1;
String text2;
public Frame2(String text1, String text2){
this.text1 = text1;
this.text2 = text2;
}
}
When the second frame is instantiated in the actionPerformed, It will make the second frame appear. It is also being passed the information from the text fields. You may also want to dispose of the first frame.
A modal JDialog is just as easy to make as a JFrame it's the same structure. Only difference is you can set it up to be modal (meaning nothing else that it not the JDialog) can be accessed. See this answer to see hoe to set up a JDialog for a login
Here's a very simple program using a JDialog with your requirements
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JDialogDemo {
MyDialog dialog;
JLabel label;
JFrame frame;
public JDialogDemo() {
label = new JLabel(" ");
frame = new JFrame("Hello World");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
dialog = new MyDialog(frame, true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new JDialogDemo();
}
});
}
class MyDialog extends JDialog {
private JButton button = new JButton("Submit");
private JTextField jtf1;
private JTextField jtf2;
public MyDialog(final Frame frame, boolean modal) {
super(frame, true);
jtf1 = new JTextField(15);
jtf2 = new JTextField(15);
add(button, BorderLayout.SOUTH);
add(jtf1, BorderLayout.CENTER);
add(jtf2, BorderLayout.NORTH);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text1 = jtf1.getText();
String text2 = jtf2.getText();
label.setText(text1 + " " + text2);
dispose();
frame.revalidate();
frame.repaint();
frame.setVisible(true);
}
});
pack();
setVisible(true);
}
}
}
It should be fairly easy to follow. Let me know if you have any questions about it
If jframe 1 call jframe 2, then u can create a constructor in jframe 2, and pass this values.
Or you can do that by haveing a object contains jframe 1, then get in the second frame, get them by getter methods.
But for a good practice you should use single jframe and dialogs.
JFrame frame1 = new JFrame("frame1");
JPanel panel = new JPanel();
final JTextField textField = new JTextField("Text Here");
JButton button = new JButton("Copy label to other frame");
panel.add(textField);
panel.add(button);
frame1.add(panel);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack();
frame1.setLocationByPlatform(true);
frame1.setVisible(true);
JFrame frame2 = new JFrame("frame2");
final JLabel label2 = new JLabel("Label 2 Text");
frame2.add(label2);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.pack();
frame2.setLocationRelativeTo(null);
frame2.setVisible(true);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label2.setText(textField.getText());
}
});
Of course, your question isn't worded very well to show what you're really trying to accomplish or better yet, what you've already tried. Nevertheless, this code does what your specifications ask for.
If you want to put on jlabels the text that the user has inputted, you must create first the jframe1, and then jframe1 will create jframe2 passing it the text. The jframe2 will create the jlabels setting the text in the constructor.
If you want that jframe1 desappears, I think you can't close it (because if you close it, like jframe1 created jframe2, this one will be closed too). You can hide the jframe1 setting it as not visible when the user has clicked the get started button.
jframe1.setVisible(false);
Total re-edit with compilable example that clarifies my issue.
Overall program: Class MainFrame displays a JTable with results from a SQL query. MainFrame also has JButtons for refreshing, adding, updating, and querying the table. Clicking the Update button makes visible a text area and submit button. Users can enter an id number into the text area. When they click submit a new frame, UpdateFrame, opens with all the data from the record the corresponds to the id number.
Stripped-down versions of MainFrame and UpdateFrame are below.
UpdateFrame2.java
package kft1task4;
import javax.swing.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.JScrollPane;
public class UpdateFrame2 extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JTextArea jta = new JTextArea("This is a text area");
UpdateFrame2() {
setVisible(true);
setBounds(1000,400,1000,500);
pane.setLayout(null);
add(pane);
jta.setBounds(110,100,100,15);
pane.add(jta);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
} //End actionListener
} //End class
Very simple. One frame with one panel with one JTextArea. The JTextArea should be editable; I should be able to type in it.
MainFrame2.java
package kft1task4;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
public class MainFrame2 extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton closeButt = new JButton("Push me to close the program");
JButton updateButt = new JButton("Push me to update a record");
JButton submitUpdButt = new JButton("Submit");
JLabel updateLabel = new JLabel("Select student id to update");
JTextArea updateTA = new JTextArea();
MainFrame2(){
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(1000,200,1500,1000);
pane.setLayout(null);
add(pane);
updateButt.setBounds(620,550,200,100);
updateButt.addActionListener(this);
pane.add(updateButt);
closeButt.setBounds(1290,550,200,100);
closeButt.addActionListener(this);
pane.add(closeButt);
submitUpdButt.setBounds(820,735,200,25);
submitUpdButt.addActionListener(this);
submitUpdButt.setVisible(false);
pane.add(submitUpdButt);
updateLabel.setBounds(620,700,200,15);
updateLabel.setVisible(false);
pane.add(updateLabel);
updateTA.setBounds(820,700,200,15);
updateTA.setVisible(false);
pane.add(updateTA);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == closeButt){
System.exit(0);
}
if(source == updateButt){
updateLabel.setVisible(true);
updateTA.setVisible(true);
submitUpdButt.setVisible(true);
}
if(source == submitUpdButt){
//submitUpdButt.setVisible(false);
new UpdateFrame2();
updateTA.setText(null);
updateTA.setVisible(false);
updateLabel.setVisible(false);
submitUpdButt.setVisible(false);
}
}
}
Note the three fields: updateLabel, updateTA, and submitUpdButt (and please forgive the poor naming). When new MainFrame2() is first instantiated, those three fields are .setVisible(False). Clicking updateButt makes them visible.
Click submitUpdButt performs five actions: First, it instantiates a new UpdateFrame2(). Second, it clears the text from UpdateTA. Finally, it makes the three fields invisible. Those 5 actions complete with no problem.
Now here's the oddity: Notice that I've listed "submitUpdButt.setVisible(false)" twice. Once before "new UpdateFrame2()" and once after. I comment out one and leave other in place. If "submitUpdButt.setVisible(false)" appears before "new UpdateFrame2()," the UpdateFrame appears, and its text area is editable.
If "submitUpdButt.setVisible(false)" appears after "new UpdateFrame2()," as it's written above, the UpdateFrame appears. But its text area is not editable.
To clarify: Every other element of the program behaves exactly the same. The 3 fields appear and disappear as expected. The window open and close correctly. The text "This is a text area" appears where it should. No errors are produced. But the text area in UpdateFrame2 is editable or not based on where I put "submitUpdButt.setVisible(false)".
I hope this description is more clear than my last one.
SO i am working on a project and i was trying to disable the frame and the field from the program so that only the window is front is this one being active
here is my code :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class password
{
private static String password = "pass";
public static void main(String[]args) {
JFrame frame = new JFrame("Password");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,100);
JLabel label = new JLabel("Enter password");
JPanel panel = new JPanel();
frame.add(panel);
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.WEST);
}
static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char [] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password)){
JOptionPane.showMessageDialog(null, "Correct");
System.out.print("Welcome to Adam's Quirky program.");
}
else
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
the program i am currently using to program is Eclipse.
I'd take a look at a modal dialog.
Either use a JOptionPane or roll your own.
If these don't suit your needs, try taking a look at JLayer (Java 7) or JXLayer (Java 6 and below)
Have a look at LockableUI (It's a little out of date, but the basic idea is the same)
If that doesn't appeal, you could use a "blocking glass pane"
Take a look at
glassPane is not blocking input
Is there a problem with this blocking GlassPane?
as some examples
I'm trying to set the text in a label dynamically by calling the setText method whenever a button is clicked. Here is my code:
import java.awt.*;
import java.awt.event.*;
class Date {
public static void main(String[] args) {
new MainWindow();
}
}
class MainWindow {
static Label month = new Label();
static Label day = new Label();
static Button submit = new Button("Submit");
MainWindow() {
Frame myFrame = new Frame("Date Window");
myFrame.setLayout(new FlowLayout());
myFrame.add(month);
myFrame.add(day);
myFrame.add(submit);
submit.addActionListener(new ButtonListener());
myFrame.addWindowListener(new WindowListener());
myFrame.setSize(200, 200);
myFrame.setVisible(true);
}
}
class WindowListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == MainWindow.submit) {
MainWindow.month.setText("12");
MainWindow.day.setText("31");
}
}
}
When I initialize the two Label objects without any arguments, the strings "12" and "31" that are passed to the setText method aren't visible on the screen when the submit button is clicked until I click on the window and drag to resize it. I've noticed this on a Mac only. On a PC, the strings are are visible but obscured until I resize the window. However, if I initialize the labels like this:
static Label month = new Label("0");
static Label day = new Label("0");
On the Mac, the strings appear as intended, however, they're obscured until the window is resized. What am I missing?
Calling validate() on the Frame as mentioned here solved the problem.
Try repainting the frame or/and set enough space(setPreferredSize, setMininumSize)
Well, most of your posting are over a year old so I'll give you the benefit of the doubt. I never use AWT so I don't know what the problem is, but I'll suggest:
1) Name you classes properly. "Date" is already a class in the JDK. Choose a better name.
2) Try using Swing components instead of AWT.
3) Get rid of static variables from your class.
4) Get rid of the WindowListener to close the frame.
The code example you posted here is 10-15 years old. Try something newer. Start with the Swing tutorial for more recent examples.