JTextField actionListener
Hi,
I'm having quite an issue I hope someone can help me with. I want to add an actionlistener to a textField. But I want it respond not only to when press the return key. I want it to respond as soon as i press any button when the jtextfield is in focus.
Can anyone help me?
I think it makes more sense to install a document listener:
import javax.swing.*;
import javax.swing.event.*;
public class DocumentListenerExample implements Runnable, DocumentListener {
private JTextField field;
@Override
public void run() {
field = new JTextField(40);
field.getDocument().addDocumentListener(this);
JFrame f = new JFrame("DocumentListenerExample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(field);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
@Override
public void changedUpdate(DocumentEvent e) {
reactToTextFieldChange();
@Override
public void insertUpdate(DocumentEvent e) {
reactToTextFieldChange();
@Override
public void removeUpdate(DocumentEvent e) {
reactToTextFieldChange();
void reactToTextFieldChange() {
System.out.println("field.text is now " + field.getText());
public static void main(String[] args) {
SwingUtilities.invokeLater(new DocumentListenerExample());
}By the way, Swing questions should be posted to the swing forum.
Similar Messages
-
JTextField actionListener does not work
I am writing an application, and I am using Swing and consequently JTextFields. There is a JTextField whose actionListener works when I use the compiling environment to run the application, but it is not working when I run it from a piece of code written in Visual Basic. All the others JTextFields work properly.
Any idea coming up?
May it be any conflict with Microsoft?Veena,
Always mention your JDev version.
When used in combination, the actionListener is either ignored or the popwarning.show does not work.Can you elaborate the above? Does this happen everytime? Can you also check what is the value for validator.addWarningIfCityNotApproved() - you can run the app in Debug mode to see where exactly it fails ?
-Arun -
JTextField ActionListener Help
Hallo Guys,
I have an JTextField . when the user inputs the number and clicks the InsertString button i generate that many JTextField for the user to insert some Strings.
if the user enters 10 and clicks the InsertString Button then 10 JTextFields appear. it works fine
but my problem is how to access the text entered in the different JTextFields.
i can access only the last textField
Here is the piece of code
if(cmd.equals("InsertString"))
if(numvaluesField.getText().equals(""))
ImageIcon icon = new ImageIcon("Images/warning_large.gif");
JOptionPane.showConfirmDialog(null,"Please Input the Number of Values and then Press the InsertString Button","Alert",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,icon);
else
stringButton.setEnabled(false);
deleteButton.setEnabled(true);
Container contentPane = valueFrame.getContentPane();
GridBagLayout gridbag = new GridBagLayout();
sub1 = new JPanel(gridbag);
GridBagConstraints c = new GridBagConstraints();
GridBagConstraints d = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(5, 5, 5, 5);
c.weightx = 1.0;
c.weighty = 1.0;
try{
numValue = Integer.parseInt(numvaluesField.getText());
catch(NumberFormatException exception){};
if(numvaluesField.equals(""))
JOptionPane.showConfirmDialog(null,"The number of values field Cannot be NULL","Alert",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE);
else{
for(int i = 1; i <= numValue ; i++)
c.gridx = 2 ;
c.gridy = i ;
lengthField.setText(String.valueOf(Integer.parseInt(lengthField.getText()) + 2));
JLabel stringLabel= new JLabel("String"+i+":");
sub1.add(stringLabel,c);
//stringField = new JTextField[numValue];
stringField = new JTextField(10);
stringField.addActionListener(this);
stringField.setToolTipText("Enter the String name for Parameter Acquisition");
c.gridx = 3;
c.gridy = i;
sub1.add(stringField,c);
d.gridx = 1;
d.gridy = 0;
main.add(sub1,GridBagConstraints.RELATIVE);
contentPane.add(main);
valueFrame.setContentPane(contentPane);
valueFrame.pack();
}here is the code where i access the JTextFields
for(int i = 1 ; i <= numValue1 ; i++)
StringBuffer buff = new StringBuffer();
buff.append(stringField.getText());
value = messageString.createStringField(value,buff.toString());
buff.setLength(0);
}Hi freedomjava,
Torajirou is right you'r overwrite the reference so the only textfield available is the last one..
For simple example you just think what should be the out put of the following ?? and you should got your mistake..
int i=0;
i=1;
i=100;
System.out.println("Value of i = "+i);You should got the last value.... -
NullPointerException, how do i get rid of?
Hey guys,
I'm totally puzzled by this one. All i'm trying to do is to change the content of JTextField(), but every time i do i get a NullPointerException. Here's the code:
public class PrivateMessageWindow extends JFrame
private Container container;
private JTextArea textArea;
private JTextField inputField;
private String windowId, messageDestination;
private Message m;
public PrivateMessageWindow(String Id)
super("Private Message");
Container container = getContentPane();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
JTextField inputField = new JTextField();
//ActionListener for inputField
ActionListener k = new PrivateWindowListener();
inputField.addActionListener(k);
//Placement of element on Panel
container.setLayout(new BorderLayout(5,5));
container.add(textArea, BorderLayout.CENTER);
container.add(inputField, BorderLayout.SOUTH);
//Initializes a message of type private Message
setSize( 300, 150);
setVisible(true);
}//end of constructor
private class PrivateWindowListener implements ActionListener
public void actionPerformed(ActionEvent event)
inputField.setText("");
}// end of private class PrivateMessageWindowThe problem occurs anytime i access a variable outside the actionPerformed method i get a NullPointerException. I'm not sure if it helps but this class gets triggered by a JButton object.
any clue of wats happening here?
Tanx.You are not initializing your JTextField inputField. Instead, you instantiate a local variable. The same applies to your JTextArea. You should have:textArea = new JTextArea();
textArea.setEditable(false);
inputField = new JTextField();Moreover, I don't think you really need the field container. -
Didn't add actionListener to JTextField, but it works anyway. Why?
Now this is a new one. I'm not asking why it doesn't work, but why it does work. I wrote up the following code:
red = new JTextField (5);
red.addActionListener (new inputListener());
green = new JTextField(3);
blue = new JTextField(3);
private class inputListener implements ActionListener
public void actionPerformed (ActionEvent event)
String rText = red.getText();
redInput = Integer.parseInt(rText);
String gText = green.getText();
greenInput = Integer.parseInt(gText);
String bText = blue.getText();
blueInput = Integer.parseInt(bText);
c = new Color(redInput, greenInput, blueInput);
}I was planning to add listeners for the green and blue text field, but I ran the program first to make sure it was working so far. The strange thing is that the green and blue text fields were listening, even though I hadn't added listeners to them. I don't get it. How are they working?
Edited by: codinatrix on Jan 11, 2008 4:52 PM
Because...my cat came onto the keyboard and pressed tab and enter so it posted before I was done writing. Damn cat.Okay, I guess I should do a compilable example. What I'm trying to do is let the user input a number into each of the three text fields: red, green, blue, which will then be used to change the background colour of the panel. I added the listener to the red text field, but not the green and blue. Putting in 0 into red, 255 into green, and 0 into blue, for example succeeds in turning the background green, even though the green text field doesn't have a listener.
public class ColorDisplayPanelTest extends JPanel {
JPanel displayPanel, textPanel, buttonPanel;
JLabel displayLabel, redText, greenText, blueText;
JTextField red, green, blue;
Color c;
JButton button;
int redInput = 0;
int greenInput = 0;
int blueInput = 0;
public ColorDisplayPanelTest() {
displayPanel = new JPanel();
textPanel = new JPanel();
buttonPanel = new JPanel();
add(displayPanel);
add(textPanel);
add(buttonPanel);
// Display Panel.
displayLabel = new JLabel("Colour Display");
displayPanel.add(displayLabel);
// Text Panel.
red = new JTextField (5);
red.addActionListener (new inputListener());
green = new JTextField(3);
blue = new JTextField(3);
redText = new JLabel("R?d");
greenText = new JLabel("Gr?n");
blueText = new JLabel("Bl?");
textPanel.add(redText);
textPanel.add(red);
textPanel.add(greenText);
textPanel.add(green);
textPanel.add(blueText);
textPanel.add(blue);
// Button Panel.
button = new JButton("Visa f?rg");
buttonPanel.add(button);
button.addActionListener (new colorButtonListener());
// Button Listener class.
private class colorButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
displayPanel.setBackground(c);
private class inputListener implements ActionListener
public void actionPerformed (ActionEvent event)
String rText = red.getText();
redInput = Integer.parseInt(rText);
String gText = green.getText();
greenInput = Integer.parseInt(gText);
String bText = blue.getText();
blueInput = Integer.parseInt(bText);
c = new Color(redInput, greenInput, blueInput);
} -
ActionListener and the JTextField
Hi, I'm fairly new to java and to this forum. This is my first posting actually. I apologise that this may be a long one but if anyone can help I'd be most appreciative.
I'm having trouble using the ActionListener on the JTextField. What I would like for this program to do is when the user types "high" into the input JTextField the output JTextField displays "LOW". Here's what I have.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldAp extends JFrame
JPanel pane01 = new Pane01();
public void buildUI(Container container)
//Sets border and layout of pane
pane01.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pane01.setLayout(new BoxLayout(pane01,BoxLayout.Y_AXIS));
//add pane to container
container.add(pane01);
class Pane01 extends JPanel implements ActionListener
JTextField input;
JTextField output;
Pane01()
input = new JTextField("input");
input.addActionListener(this);
output = new JTextField("output");
add(Box.createRigidArea(new Dimension(0,60)));
add(input);
add(Box.createRigidArea(new Dimension(0,80)));
add(output);
add(Box.createRigidArea(new Dimension(0,60)));
public void actionPerformed(ActionEvent evt)
String text = input.getText();
if(text=="high")
output.setText("LOW");
public static void main(String args[])
JFrame f = new JFrame("Tex Ap");
TextFieldAp example = new TextFieldAp();
//Builds the pane into the frame
example.buildUI(f.getContentPane());
f.addWindowListener (new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
f.pack();
f.setSize(200,300);
f.show();
...So how come typing high into the input field does nothing??
This seems like it should be really easy but for the life of me I can't seem to get the two fields to communicate. I've gone through the java tutorial and the API documentation but I couldn't seem to find any answers. Does anyone know what I should be doing??
humphersFor String comparisons use .equals() rather than ==
-
How to capture the event on changing focus from a JTextField?
Hi All,
I have got a problem...
I want to do something (say some sort of validations/calculations) when I change the focus by pressing tab from a JTextField. But I am not able to do that.
I tried with DocumentListener (jtf01.getDocument().addDocumentListener(this);). But in that case, it's calling the event everytime I ke-in something in the text field. But that's not what I want. I want to call that event only once, after the value is changed (user can paste a value, or even can key-in).
Is there any way for this? Is there any method (like onChange() in javascript) that can do this.
Please Help me...
Regards,
UjjalHi Michael,
I am attaching my code. Actual code is very large containing 'n' number of components and ActionListeners. I am attaching only the relevant part.
//more codes
public class PaintSplitDisplay extends JApplet implements ActionListener
JFrame jf01;
JPanel jp01;
JTextField jtf01, jtf02;
//more codes
public void start()
//more codes
jtf01 = new JTextField();
jtf01.setPreferredSize(longField);
jtf01.setFont(new Font("Courier new",0,12));
jtf01.setInputVerifier(new InputVerifier(){public boolean verify(JComponent input)
//more codes
System.out.print("updating");
jtf02.setText("updated value");
System.out.print("updated");
return true;
//more codes
jtf02 = new JTextField();
jtf02.setPreferredSize(mediumField);
jtf02.setEditable(false);
jp01.add(jtf02, gbc);
//more codes
jf01.add(jp01);
jf01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf01.setVisible(true);
//more codes
public static void main(String args[])
PaintSplitDisplay psp = new PaintSplitDisplay();
psp.start();
public void actionPerformed(ActionEvent ae)
//more codes
}As you can see I want to update the second JTextField based on some calculations. That should happen when I change the focus from my frist JTextField. I have called jtf02.setText() method inside InputVerifier. But it's giving error...
Please suggest...
Ujjal -
ActionListener not working with JFrame
Hi,
I've just rehashed an old bit of code to work with a new application but for some reason the JButton ActionListeners aren't working. However if I extend JDialog they work ok. The current code for JDialog is:-
* File: GUI.java
* @author ODL 3xx Distributed Systems - Team x
* @description This class provides a means for the user to
* interact with file server.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class GUI extends JDialog implements ActionListener, ApplicationConstants {
private JLabel label1, label2, label3, label4, label5;
private JTextField field1, field2, field3, field4, field5;
private JButton button1, button2, button3, button4, button5;
private Container container;
private Message sendFile;
private String id;
private String defaultText = "Enter file name here";
private ClientForGUI client;
private long timeStart, timeEnd;
public GUI(JFrame frame) {
super(frame, "File Server Actions", true);
client = new ClientForGUI(this);
try{
InetAddress addr = InetAddress.getLocalHost();
id = addr.getHostName() + Long.toString((new java.util.Date()).getTime());
if(client.connectToServer())
initGUI();
else{
JOptionPane.showMessageDialog(this, "Unable to connect to server", "Error", JOptionPane.WARNING_MESSAGE);
System.exit(0);
catch(UnknownHostException uhe){
System.out.println("Unknown Host Exception");
initGUI();
* Create the GUI
private void initGUI() {
container = this.getContentPane();
container.setLayout(null);
label1 = new JLabel("Upload File");
label2 = new JLabel("Rename File");
label3 = new JLabel("Delete File");
label4 = new JLabel("Create File");
label5 = new JLabel("Download File");
field1 = new JTextField();
field2 = new JTextField();
field3 = new JTextField();
field4 = new JTextField();
field5 = new JTextField();
button1 = new JButton("Upload");
button2 = new JButton("Rename");
button3 = new JButton("Delete");
button4 = new JButton("Create");
button5 = new JButton("Download");
label1.setBounds(10,10,80,20);
label2.setBounds(10,40,80,20);
label3.setBounds(10,70,80,20);
label4.setBounds(10,100,80,20);
label5.setBounds(10,130,80,20);
field1.setBounds(100,40,200,20);
field1.setText("Old name");
field2.setBounds(310,40,200,20);
field2.setText("New name");
field3.setBounds(100,70,410,20);
field3.setText(defaultText);
field4.setBounds(100,100,410,20);
field4.setText(defaultText);
field5.setBounds(100,130,410,20);
field5.setText(defaultText);
button1.setBounds(100,10,100,20);
button1.addActionListener(this);
button2.setBounds(520,40,100,20);
button2.addActionListener(this);
button3.setBounds(520,70,100,20);
button3.addActionListener(this);
button4.setBounds(520,100,100,20);
button4.addActionListener(this);
button5.setBounds(520,130,100,20);
button5.addActionListener(this);
container.add(label1);
container.add(button1);
container.add(label2);
container.add(field1);
container.add(field2);
container.add(button2);
container.add(label3);
container.add(field3);
container.add(button3);
container.add(label4);
container.add(field4);
container.add(button4);
container.add(label5);
container.add(field5);
container.add(button5);
setSize(640,200);
setResizable(false);
//Centre on the screen
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((d.getWidth() - getWidth()) / 2);
int y = (int) ((d.getHeight() - getHeight()) / 2);
setLocation(x,y);
setVisible(true);
private void sendMessageToServer(Message message){
message.setId(id);
timeStart = new java.util.Date().getTime();
try{
client.sendMessageToServer(message);
catch(IOException ioe){
System.out.println("Unable to send message to server");
* Perform some action based on user interaction
* @param ae - ActionEvent
public void actionPerformed(ActionEvent e){
Object o = e.getSource();
String name;
if(o == button1){
try{
JFileChooser fc = new JFileChooser();
fc.setVisible(true);
//return value is what the user presses in the open File dialog
int returnVal = fc.showOpenDialog(null);
//if they choose OK
if (returnVal == JFileChooser.APPROVE_OPTION) {
//file now references the selected
File file = fc.getSelectedFile();
//create a FileInputStream from file location
FileInputStream fis = new FileInputStream(file);
// Create the byte array to hold the data, the same size as the file
byte [] fileBytes = new byte[(int)file.length()];
// Read in the bytes from the file into the byte array
int offset = 0;
int numRead = 0;
while (offset < fileBytes.length &&
(numRead=fis.read(fileBytes, offset, fileBytes.length-offset)) >=
0) {
offset += numRead;
// Ensure all the bytes have been read in
if (offset < fileBytes.length) {
throw new IOException("Could not completely read file "+file.getName());
fis.close();
sendFile = new Message(SEND_FILE, fileBytes);
sendFile.setId(id);
sendFile.setFileName(file.getName());
byte [] myarray = ConvertData.messageToBytes(sendFile);
Message sendWarning = new Message(SEND_FILE_WARNING);
sendWarning.setFileName(file.getName());
sendWarning.setFileSize(myarray.length);
try{
sendMessageToServer(sendWarning);
catch(Exception excep){
System.out.println(excep);
catch(FileNotFoundException fnfe){
System.out.println("File Not Found Exception");
catch(java.io.IOException ioe){
System.out.println("IO Exception");
else if(o == button2){
name = field1.getText();
String name2 = field2.getText();
Message renameMessage = new Message(RENAME_FILE);
renameMessage.setFileName(name);
renameMessage.setFileRename(name2);
sendMessageToServer(renameMessage);
field1.setText("Old name");
field2.setText("New name");
else if(o == button3){
name = field3.getText();
Message deleteMessage = new Message(DELETE_FILE);
deleteMessage.setFileName(name);
sendMessageToServer(deleteMessage);
field3.setText(defaultText);
else if(o == button4){
name = field4.getText();
Message createMessage = new Message(CREATE_FILE);
createMessage.setFileName(name);
sendMessageToServer(createMessage);
field4.setText(defaultText);
else if(o == button5){
name = field5.getText();
Message downloadMessage = new Message(REQUEST_FILE);
downloadMessage.setFileName(name);
sendMessageToServer(downloadMessage);
field5.setText(defaultText);
public void processServerMessage(Message message){
switch(message.getMessageHeader()){
case SEND_FILE_WARNING:
//change the download size to file size plus max message size
client.setDownload((int)message.getFileSize(),true);
//turn message back around with acknowledgement header
message.setMessageHeader(SEND_FILE_ACK);
//send the message
try{
sendMessageToServer(message);
catch(Exception e){
System.out.println(e);
break;
//server has acknowledged that the client wishes to send a message
//so send the message
case SEND_FILE_ACK:
//send the message
try{
sendMessageToServer(sendFile);
catch(Exception e){
System.out.println(e);
break;
//server is sending the file to the client.
case SEND_FILE:
//reset the download size to default
client.setDownload(DEFAULT_MESSAGE_SIZE,false);
//get the file name
File f = new File(message.getFileName());
//create the file chooser
JFileChooser fc = new JFileChooser();
//set selected file as thoe one downloaded
fc.setSelectedFile(f);
//get the button hit by the user
int returnVal = fc.showSaveDialog(null);
//if button is OK
if (returnVal == JFileChooser.APPROVE_OPTION){
File temp = fc.getCurrentDirectory();
String [] files = temp.list();
java.util.List alist = java.util.Arrays.asList(files);
f = fc.getSelectedFile();
if(alist.contains(message.getFileName())){
if(JOptionPane.showConfirmDialog(null,
message.getFileName() + " already exists. Are you sure you want to overwrite this file?",
"Instant Messenger: Quit Program",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null) == JOptionPane.YES_OPTION) {
//f = fc.getSelectedFile();
System.out.println(f.toString());
//this is where the file is copied
try{
FileOutputStream fs = new FileOutputStream(f);
fs.write(message.getFile());
fs.close();
catch(IOException e){
System.out.println(e);
else fc.hide();
else{
System.out.println("Here " + f.toString());
try{
FileOutputStream fs = new FileOutputStream(f);
fs.write(message.getFile());
fs.close();
catch(IOException e){
System.out.println(e);
else fc.hide();
break;
case INFORMATION:
timeEnd = new java.util.Date().getTime();
Long rtrip = timeEnd - timeStart;
String str = Long.toString(rtrip);
double d = Double.valueOf(str).doubleValue();
String fullMessage = message.getMessage();
fullMessage += " The total time taken for the last request was " +
rtrip + " milliseconds" + " or roughly " + d/1000 + " seconds";
JOptionPane.showMessageDialog(null,fullMessage,"Information",JOptionPane.INFORMATION_MESSAGE);
break;
class TestGUI{
public static void main(String [] args){
JFrame frame = new JFrame();
GUI myGUI = new GUI(frame);
} If I change the GUI constructor to empty and extend JFrame instead of JDialog and change the call to super the ActionListener stops working. I've never known this problem before (i.e. I always use e.getSource()). I've even cast the object to a JButton to ensure that the right button is pressed and it is all ok.
Is there something fundamentally wrong when I make those simple changes to JFrame?
Regards,
ChrisI think rather the approach is your action handling in terms of the buttons. The giant actionPerformed method is difficult to read and maintain.
I would recommend the following things:
1. Split your ActionListener into multiple smaller listeners. There's not really even a reason for the GUI class to be an action listener. Instead of having GUI implement ActionListener and trying to keep all of the functionality in one place, use anonymous classes:
button3.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
name = field3.getText();
Message deleteMessage = new Message(DELETE_FILE);
deleteMessage.setFileName(name);
sendMessageToServer(deleteMessage);
field3.setText(defaultText);
button4.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
name = field4.getText();
Message createMessage = new Message(CREATE_FILE);
createMessage.setFileName(name);
sendMessageToServer(createMessage);
field4.setText(defaultText);
2. Only use the == operator on primitives. There are very few cases in which you can properly use the == operator on objects and, in every one of those cases I have experienced, the equals(Object) method produces the same result.
3. Name your variables more descriptively. There is really very little reason for your buttons to be named button1, button2, and so on. Give them names that mean something. For example, button1 should be named something like uploadFileButton or buttonUpload. That will give us significant information about what it is expected to do, whereas button1 does not. You may be able to remember what button1 does, but you wrote the code. I keep having to refer back to the instantiation of the button to get a hint as to what it does and, in a few months' time, so will you. :) The same goes for your labels and fields, as well.
I'm not sure why you aren't getting the behavior you want. However, have you checked to determine that the event source of the button click is actually the button when the whole thing is inside of a JFrame? I would expect it to be, but you never know. This is why I recommend using different ActionListeners for each button. That way, you can be sure of what caused the event.
Just my 2c. Good luck to you. :) -
Getting values from a JTextField on a JPanel in another class
I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldChooser extends JPanel{
int val;
public TextFieldChooser(String str){
val = 0;
setLayout(new FlowLayout());
add(new JLabel(str));
JTextField txtf = new JTextField(5);
txtf.addActionListener(new TextFieldListener());
add(txtf);
}//end constructor
private class TextFieldListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
val = Integer.parseInt(e.getActionCommand());
}//end text field listener
public int getValue(){
return val;
}//classThe problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
I have created a class which extends a JPanel and
added a JTextField to it, which has an
addActionListener for getting the values typed in the
JTextField. I want to use the class created in
another class and retrieve the values typed in the
JTextField, so how do i go about that? I have the
class created below so the problem is how to retrieve
content of val[val] in another class?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldChooser extends JPanel{
int val;
public TextFieldChooser(String str){
val = 0;
setLayout(new FlowLayout());
add(new JLabel(str));
JTextField txtf = new JTextField(5);
txtf.addActionListener(new TextFieldListener());
add(txtf);
}//end constructor
private class TextFieldListener implements
s ActionListener{
public void actionPerformed(ActionEvent e) {
val = Integer.parseInt(e.getActionCommand());
}//end text field listener
public int getValue(){
return val;
}//class -
Reading values from JTextField and using them?
Hello,
I am trying to make a login screen to connect to an oracle database. Im pretty new to creaing GUI. I need help with reading the values from the JTextField and to be able to use them for my connection. So do I need to apply a listener? How do I go about doing that in this project. Thanks for any code or advice.
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
public class UserDialog
String databaseURL;
String driver;
String database;
String username;
String password;
String hostname;
String port;
UserDialog() {
getInfo();
static String[] ConnectOptionNames = { "Login", "Cancel" };
static String ConnectTitle = "Login screen";
public void getInfo() {
JPanel connectionPanel;
JLabel databaseURLLabel = new JLabel("Database URL: ", JLabel.LEFT);
JTextField databaseURLField = new JTextField("");
JLabel driverLabel = new JLabel("Driver: ", JLabel.LEFT);
JTextField driverField = new JTextField("");
JLabel databaseLabel = new JLabel("Database: ", JLabel.LEFT);
JTextField databaseField = new JTextField("");
JLabel usernameLabel = new JLabel("User Name: ", JLabel.LEFT);
JTextField usernameField = new JTextField("");
JLabel passwordLabel = new JLabel("Password: ", JLabel.LEFT);
JTextField passwordField = new JPasswordField("");
JLabel hostnameLabel = new JLabel("Host Name: ", JLabel.LEFT);
JTextField hostnameField = new JTextField("");
JLabel portLabel = new JLabel("Port: ", JLabel.LEFT);
JTextField portField = new JTextField("");
connectionPanel = new JPanel(false);
connectionPanel.setLayout(new BoxLayout(connectionPanel,
BoxLayout.X_AXIS));
JPanel namePanel = new JPanel(false);
namePanel.setLayout(new GridLayout(0, 1));
namePanel.add(databaseURLLabel);
namePanel.add(driverLabel);
namePanel.add(databaseLabel);
namePanel.add(usernameLabel);
namePanel.add(passwordLabel);
namePanel.add(hostnameLabel);
namePanel.add(portLabel);
JPanel fieldPanel = new JPanel(false);
fieldPanel.setLayout(new GridLayout(0, 1));
fieldPanel.add(databaseURLField);
fieldPanel.add(driverField);
fieldPanel.add(databaseField);
fieldPanel.add(usernameField);
fieldPanel.add(passwordField);
fieldPanel.add(hostnameField);
fieldPanel.add(portField);
connectionPanel.add(namePanel);
connectionPanel.add(fieldPanel);
// Connect or quit
databaseURL = databaseURLField.getText();
driver = driverField.getText();
database = databaseField.getText();
username = usernameField.getText();
password = passwordField.getText();
hostname = hostnameField.getText();
port = portField.getText();
int n = JOptionPane.showOptionDialog(null, connectionPanel,
ConnectTitle,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, ConnectOptionNames,
ConnectOptionNames[0]);
if (n == 0) {
System.out.println("Attempting login: " + username);
String url = databaseURL+hostname+":"+port+":"+database;
// load the JDBC driver for Oracle
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection (url, username, password);
System.out.println("Congratulations! You are connected successfully.");
con.close();
System.out.println("Connection is closed successfully.");
catch(SQLException e){
System.out.println("Error: "+e);
else if (n == 1)
System.exit(0);
public static void main (String args []) {
UserDialog ud = new UserDialog();
}thanks again,
Jamesthe reason why you can't get the text is because you are reading the value before some actually inserts anything in any fields.
Here is what you need to do:
Create a JDialog/JFrame. Create a JPanel and set that panel as contentPane (dialog.setContentPane(panel)). Insert all the components, ie JLabels and JTextFields. Add two buttons, Login and Cancel to the panel as well. Now get the username and password field values using getText() inside the ActionListener of the Login.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginDialog extends JDialog
String username, password;
public LoginDialog( ){
setTitle( "Login" );
JPanel content = new JPanel(new GridLayout(0, 2) ); // as many rows, but only 2 columns.
content.add( new JLabel( "User Name" ) );
final JTextField nameField = new JTextField( "" );
content.add( nameField );
content.add( new JLabel( "Password" ) );
final JTextField passField = new JTextField( "" );
content.add( passField );
JButton login = new JButton( "Login" );
login.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
username = nameField.getText();
password = passField.getText();
// call a method or write the code to verify the username and login here...
content.add( login );
JButton cancel = new JButton( "Cancel" );
cancel.addActionListener( new ActionListener( ){
public void actionPerformed( ActionEvent ae ){
dispose(); // close the window or write any code that you want here.
content.add( cancel );
pack( ); // pack everything in the dialog for display.
show(); // show the dialog. -
Memory problem with JTextFields
Hello,
I have a wierd problem with JTextField and the memory.
I need to fill a JPanel with different Components (including JTextFields), then do some calculation, remove the Components and filling the JPanel again.
When i so this too often my i get an OutOfMemory Exception. I narrowed to problem down and wrote a small sample program to demonstrate the problem.
When i call the method doIT (where the Panel is repeatedly filled) from the main-function everything works fine, but when it is called as a result from the GUI-Button-Event the memory for the JTextFields is not freed (even the call of the Garbage collector changes nothing)
When i only use JButtons to fill the Panel everything works fine.
Has anyone an idea why this problem occurs and how i can work around it?
[Edit] I tested it whith java 1.5.0_06, 1.5.0_11, 1.6.0_02
Thanks
Marc
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MemoryTestDLG extends JDialog {
public MemoryTestDLG(Frame owner) {
// create Dialog with one Button that calls the testMethod
super(owner);
JButton b = new JButton("doIT ...");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doIT();
setVisible(false);
getContentPane().add(b);
pack();
public void doIT() {
// Testmethod that fills a JPanel 20 times with Components and clears it
// again
JPanel p = new JPanel();
long memUse1 = 0;
long memUse2 = 0;
long memUseTemp = 0;
for (int count = 0; count < 20; count++) {
// Clear the panel
p.removeAll();
// Get memory usage before the task
Runtime.getRuntime().gc();
memUse1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
.getUsed();
// Fill Panel with components
for (int i = 0; i < 200; i++) {
// The Buttons seem to be released without any problem
p.add(new JButton("test" + Math.random()));
// JTextFields are not released when used from the dialog.
p.add(new JTextField("test " + Math.random()));
// get memory usage after the task
Runtime.getRuntime().gc();
memUseTemp = memUse2;
memUse2 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
.getUsed();
// print Memory results
System.out.println("Memory Usage: " + f(memUse1) + " ->"
+ f(memUse2) + " [ Used:" + f(memUse2 - memUse1)
+ " ] [ Freed: " + f(memUseTemp - memUse1) + "]");
public String f(long m) // formats the output
String s = "" + m;
while (s.length() < 8)
s = " " + s;
return s;
public static void main(String[] args) {
MemoryTestDLG d = new MemoryTestDLG(null);
System.out
.println("------------------ Direct Call (all is OK) -------------------");
d.doIT(); // Memory is freed with every call to JPanel.removeAll()
System.out
.println("------------ Call from Dialog (memory is not freed) -------------");
// The Memory keeps blocked
d.setModal(true);
d.setVisible(true);
System.exit(0);
}Message was edited by:
marcvomorcThank you for your answer,
In this sample the programm does not run out of memory. But when you look at the output you see, that in the first run (direct call) the memory ist freed immediately when tha panel is cleared but in the second run (from the Button) the memory usage is getting bigger and bigger. Wenn you change the number of components to 2000 (4000)
// Fill Panel with components
for (int i = 0; i < 2000; i++) {
// The Buttons seem to be released without any problem
//... ...and use the default memory settings (69mb heap) the programm runns out of memory.
I get the following output:
------------------ Direct Call (all is OK) -------------------
Memory Usage: 445504 -> 8121016 [ Used: 7675512 ] [ Freed: -445504]
Memory Usage: 617352 -> 8114336 [ Used: 7496984 ] [ Freed: 7503664]
Memory Usage: 810488 -> 8491768 [ Used: 7681280 ] [ Freed: 7303848]
Memory Usage: 943704 -> 8114976 [ Used: 7171272 ] [ Freed: 7548064]
Memory Usage: 836760 -> 8505072 [ Used: 7668312 ] [ Freed: 7278216]
Memory Usage: 978352 -> 8114784 [ Used: 7136432 ] [ Freed: 7526720]
Memory Usage: 835552 -> 8498288 [ Used: 7662736 ] [ Freed: 7279232]
Memory Usage: 977096 -> 8114312 [ Used: 7137216 ] [ Freed: 7521192]
Memory Usage: 835640 -> 8498376 [ Used: 7662736 ] [ Freed: 7278672]
Memory Usage: 977296 -> 8115000 [ Used: 7137704 ] [ Freed: 7521080]
Memory Usage: 835392 -> 8504872 [ Used: 7669480 ] [ Freed: 7279608]
Memory Usage: 976968 -> 8115192 [ Used: 7138224 ] [ Freed: 7527904]
Memory Usage: 836224 -> 8501624 [ Used: 7665400 ] [ Freed: 7278968]
Memory Usage: 977840 -> 8115120 [ Used: 7137280 ] [ Freed: 7523784]
Memory Usage: 835664 -> 8498256 [ Used: 7662592 ] [ Freed: 7279456]
Memory Usage: 976856 -> 8114384 [ Used: 7137528 ] [ Freed: 7521400]
Memory Usage: 835784 -> 8502848 [ Used: 7667064 ] [ Freed: 7278600]
Memory Usage: 977360 -> 8114592 [ Used: 7137232 ] [ Freed: 7525488]
Memory Usage: 835496 -> 8502720 [ Used: 7667224 ] [ Freed: 7279096]
Memory Usage: 976440 -> 8115128 [ Used: 7138688 ] [ Freed: 7526280]
------------ Call from Dialog (memory is not freed) -------------
Memory Usage: 866504 -> 8784320 [ Used: 7917816 ] [ Freed: -866504]
Memory Usage: 7480760 ->14631152 [ Used: 7150392 ] [ Freed: 1303560]
Memory Usage: 14245264 ->22127104 [ Used: 7881840 ] [ Freed: 385888]
Memory Usage: 19302896 ->27190744 [ Used: 7887848 ] [ Freed: 2824208]
Memory Usage: 27190744 ->35073944 [ Used: 7883200 ] [ Freed: 0]
Memory Usage: 31856624 ->39740176 [ Used: 7883552 ] [ Freed: 3217320]
Memory Usage: 39740176 ->47623040 [ Used: 7882864 ] [ Freed: 0]
Memory Usage: 44410480 ->52293864 [ Used: 7883384 ] [ Freed: 3212560]
Memory Usage: 52293864 ->58569304 [ Used: 6275440 ] [ Freed: 0]
Memory Usage: 58569304 ->64846400 [ Used: 6277096 ] [ Freed: 0]
Exception occurred during event dispatching:
java.lang.OutOfMemoryError: Java heap spacewhen I outcomment the adding of the JButtons the amount of freed memory is 0 in the second run. So my guess is, that there is a problem with freeing the memory for the JTextFields.
Memory Usage: 447832 -> 6509960 [ Used: 6062128 ] [ Freed: 6332768]
Memory Usage: 722776 -> 6785632 [ Used: 6062856 ] [ Freed: 5787184]
------------ Call from Dialog (memory is not freed) -------------
Memory Usage: 468880 -> 6770240 [ Used: 6301360 ] [ Freed: -468880]
Memory Usage: 6770240 ->13016264 [ Used: 6246024 ] [ Freed: 0]
Memory Usage: 13016264 ->19297080 [ Used: 6280816 ] [ Freed: 0]
Memory Usage: 19297080 ->25570152 [ Used: 6273072 ] [ Freed: 0]
Memory Usage: 25570152 ->31849160 [ Used: 6279008 ] [ Freed: 0]
Memory Usage: 31849160 ->38124368 [ Used: 6275208 ] [ Freed: 0]
Memory Usage: 38124368 ->44402072 [ Used: 6277704 ] [ Freed: 0]
Memory Usage: 44402072 ->50677928 [ Used: 6275856 ] [ Freed: 0]
Memory Usage: 50677928 ->56955880 [ Used: 6277952 ] [ Freed: 0]
Memory Usage: 56955880 ->63232152 [ Used: 6276272 ] [ Freed: 0]
Exception occurred during event dispatching:
java.lang.OutOfMemoryError: Java heap spaceAdditionally the JPanel I am using is not displayed on the screen. It stays invisible the whole time, but i cannot work around that, because the calculation is depending on the values being in components on the JPanel)
Marc -
JTextField does not redraw properly
Hi,
I have a JPanel that displays some buttons amongst some textfields and labels. One of my buttons is labeled Add Customer. When the user clicks on Add Customer he is presented with a number of JTextFields and JLabels which are all displayed fine.
However, when the user clicks on Cancel or closes the InternalFrame in which the JTextFields and JLabels are displayed and then clicks on Add Customer again, then the JTextFields are not redrawn properly. I image of this behavior can be seen at
http://www.grosslers.com/totals.07.png
As soon as I start to type text into the textfield then the whole textfield redraws itself as it should, but when it looses focus then the textfield becomes invisible once again.
// Some textfields
private JTextField textField_customerEditCompanyName = new JTextField(10);
private JTextField textField_customerEditContactName = new JTextField(10);
* Panel that will hold all the buttons for the quote request details tabbed panel
public JPanel createQuoteRequestDetailsButtons() {
// Panel to act as a container for the buttons
JPanel panel_quoteRequestDetailsButtons = new JPanel();
// Create, register action listeners and add buttons to the panel
JButton button_addCustomer = new JButton("Add Customer");
button_addCustomer.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent actionEvent) {
// Add a new customer
addCustomerListener();
panel_quoteRequestDetailsButtons.add(button_addCustomer);
return panel_quoteRequestDetailsButtons;
* Display a new internal frame when the user wants to add a new customer
public void addCustomerListener() {
// Master panel for the add customer details
JPanel panel_addCustomerMaster = new JPanel();
// Add the customer details panel to the master panel
panel_addCustomerMaster.add(customerDetailsPanel());
// Ensure that all the textfields are blank
resetCustomerDetailsPanelTextFields();
// Add the buttons panel to the master panel
panel_addCustomerMaster.add(addCustomerButtons());
// Add the master panel to the internal frame
internalFrame_addCustomer.add(panel_addCustomerMaster);
// Add the internal frame to the desktop pane
JupiterMainGUI.desktopPane.add(internalFrame_addCustomer);
// Set the size of the internal frame
internalFrame_addCustomer.setSize(500,420);
// Set other properties of the internal frame
internalFrame_addCustomer.setClosable(true);
internalFrame_addCustomer.setIconifiable(false);
internalFrame_addCustomer.setMaximizable(false);
// Set the location of the internal frame to the upper left corner
// of the current container
internalFrame_addCustomer.setLocation(0,0);
// Set the internal frame resizable
internalFrame_addCustomer.setResizable(false);
// Show the internal frame
internalFrame_addCustomer.setVisible(true);
* Panel that displays the textfields and labels when the user clicks on
* add or view customer details
public JPanel customerDetailsPanel() {
// Create master container for this panel
JPanel panel_customerDetailsMaster = new JPanel();
// Create the container that will hold all the textfields/labels for
// the creation of a new customer
JPanel panel_customerDetails = new JPanel(new SpringLayout());
// Add the details panel to the master panel
panel_customerDetailsMaster.add(panel_customerDetails);
// Set the border for the panel
panel_customerDetails.setBorder(BorderFactory.createTitledBorder("Customer Details"));
// Create textfields/labels, add them to the internalFrame
JLabel label_customerCompanyName = new JLabel("Company Name : ");
JLabel label_customerContactName = new JLabel("Contact Name : ");
panel_customerDetails.add(label_customerCompanyName);
panel_customerDetails.add(textField_customerEditCompanyName);
panel_customerDetails.add(label_customerContactName);
panel_customerDetails.add(textField_customerEditContactName);
//Lay out the panel.
SpringUtilities.makeCompactGrid(panel_customerDetails,
2, 2, //rows, cols
5, 5, //initX, initY
5, 5); //xPad, yPad
return panel_customerDetailsMaster;
* Panel holding the buttons when the user clicks on add customer
public JPanel addCustomerButtons() {
// Container for the buttons
JPanel panel_addCustomerButtons = new JPanel();
// Create the buttons for the panel
JButton button_customerOk = new JButton("Ok");
JButton button_customerCancel = new JButton("Cancel");
button_customerOk.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent actionEvent) {
// Closing the internal frame. When i re-open this internal frame again
// the labels are re-drawn properly but not the textfields.
button_customerCancel.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent actionEvent) {
try {
// close and remove the internal frame from the desktop pane
internalFrame_addCustomer.setClosed(true);
} catch (PropertyVetoException exception) {
JupiterMainGUI.desktopPane.remove(internalFrame_addCustomer);
panel_addCustomerButtons.add(button_customerOk);
panel_addCustomerButtons.add(button_customerCancel);
return panel_addCustomerButtons;
}So far I have a solution, and that is to use the GTK look and feel, but it is not really an option. Another way that I have managed to get the textfields to display properly is to create them in the same method, where I create the labels. Again, this is not really an option as i need to access the textfields outside the method scope.
Any help would be greatly appreciated
-- PokkieI added the following :
* Panel that displays the textfields and labels when the user clicks on
* add or view customer details
public JPanel customerDetailsPanel() {
// Create master container for this panel
JPanel panel_customerDetailsMaster = new JPanel();
// Create the container that will hold all the textfields/labels for
// the creation of a new customer
JPanel panel_customerDetails = new JPanel(new SpringLayout());
// Add the details panel to the master panel
panel_customerDetailsMaster.add(panel_customerDetails);
// Set the border for the panel
panel_customerDetails.setBorder(BorderFactory.createTitledBorder("Customer Details"));
// Create textfields/labels, add them to the internalFrame
JLabel label_customerCompanyName = new JLabel("Company Name : ");
JLabel label_customerContactName = new JLabel("Contact Name : ");
panel_customerDetails.add(label_customerCompanyName);
panel_customerDetails.add(textField_customerEditCompanyName);
panel_customerDetails.add(label_customerContactName);
panel_customerDetails.add(textField_customerEditContactName);
// Added this line , but doesn't seem to make a difference. also called revalidate() on the
// internalFrame in which this panel is displayed but no luck either. Called revalidate()
// on panel_customerDetailsMaster but nothing :(
panel_customerDetails.revalidate();
//Lay out the panel.
SpringUtilities.makeCompactGrid(panel_customerDetails,
2, 2, //rows, cols
5, 5, //initX, initY
5, 5); //xPad, yPad
return panel_customerDetailsMaster;
Thanks for the response thou, much appreciated -
How can I display JTextFields correctly on a JPanel using GridBagLayout?
I had some inputfields on a JPanel using the boxLayout. All was ok. Then I decided to change the panellayout to GridBagLayout. The JLabel fields are displayed correctly but the JTextField aren't. They are at the JPanel but have a size of 0??? So we cannot see what we type in these fields... Even when I put some text in the field before putting it on the panel.
How can I display JTextFields correctly on a JPanel using GridBagLayout?
here is a shortcut of my code:
private Dimension sFieldSize10 = new Dimension(80, 20);
// Create and instantiate Selection Fields
private JLabel lSearchAbrText = new JLabel();
private JTextField searchAbrText = new JTextField();
// Set properties for SelectionFields
lSearchAbrNumber.setText("ABR Number (0-9999999):");
searchAbrNumber.setText("");
searchAbrNumber.createToolTip();
searchAbrNumber.setToolTipText("enter the AbrNumber.");
searchAbrNumber.setPreferredSize(sFieldSize10);
searchAbrNumber.setMaximumSize(sFieldSize10);
public void createViewSubsetPanel() {
pSubset = new JPanel();
// Set layout
pSubset.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Add Fields
gbc.gridy = 0;
gbc.gridx = GridBagConstraints.RELATIVE;
pSubset.add(lSearchAbrNumber, gbc);
// also tried inserting this statement
// searchAbrNumber.setText("0000000");
// without success
pSubset.add(searchAbrNumber,gbc);
pSubset.add(lSearchAbrText, gbc);
pSubset.add(searchAbrText, gbc);
gbc.gridy = 1;
pSubset.add(lSearchClassCode, gbc);
pSubset.add(searchClassCode, gbc);
pSubset.add(butSearch, gbc);
}import java.awt.*;
import java.awt.event.*;
import javax .swing.*;
public class GridBagDemo {
public static void main(String[] args) {
JLabel
labelOne = new JLabel("Label One"),
labelTwo = new JLabel("Label Two"),
labelThree = new JLabel("Label Three"),
labelFour = new JLabel("Label Four");
JLabel[] labels = {
labelOne, labelTwo, labelThree, labelFour
JTextField
tfOne = new JTextField(),
tfTwo = new JTextField(),
tfThree = new JTextField(),
tfFour = new JTextField();
JTextField[] fields = {
tfOne, tfTwo, tfThree, tfFour
Dimension
labelSize = new Dimension(125,20),
fieldSize = new Dimension(150,20);
for(int i = 0; i < labels.length; i++) {
labels.setPreferredSize(labelSize);
labels[i].setHorizontalAlignment(JLabel.RIGHT);
fields[i].setPreferredSize(fieldSize);
GridBagLayout gridbag = new GridBagLayout();
JPanel panel = new JPanel(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(5,5,5,5);
panel.add(labelOne, gbc);
panel.add(tfOne, gbc);
gbc.gridwidth = gbc.RELATIVE;
panel.add(labelTwo, gbc);
gbc.gridwidth = gbc.REMAINDER;
panel.add(tfTwo, gbc);
gbc.gridwidth = 1;
panel.add(labelThree, gbc);
panel.add(tfThree, gbc);
gbc.gridwidth = gbc.RELATIVE;
panel.add(labelFour, gbc);
gbc.gridwidth = gbc.REMAINDER;
panel.add(tfFour, gbc);
final JButton
smallerButton = new JButton("smaller"),
biggerButton = new JButton("wider");
final JFrame f = new JFrame();
ActionListener l = new ActionListener() {
final int DELTA_X = 25;
int oldWidth, newWidth;
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
oldWidth = f.getSize().width;
if(button == smallerButton)
newWidth = oldWidth - DELTA_X;
if(button == biggerButton)
newWidth = oldWidth + DELTA_X;
f.setSize(new Dimension(newWidth, f.getSize().height));
f.validate();
smallerButton.addActionListener(l);
biggerButton.addActionListener(l);
JPanel southPanel = new JPanel(gridbag);
gbc.gridwidth = gbc.RELATIVE;
southPanel.add(smallerButton, gbc);
gbc.gridwidth = gbc.REMAINDER;
southPanel.add(biggerButton, gbc);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.getContentPane().add(southPanel, "South");
f.pack();
f.setLocation(200,200);
f.setVisible(true); -
How to add words from a JTextField to a JList
Im working on my final project for Java programming class using JApplet.
Im trying to create a spelling test/wordfind
I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.
then click the "Start" Button and have the all the words from the JList be put in random stops in a panel and fill around all the words with random letters.
then when the user clicks on the letter of the words they are finding it will change colors if they click on it again it will change back to its original color.
So far I have my layout set up its adding the proper Listeners and events to achieve the desired results.
I know this is way more advanced than what My Instructor is even teacher but I am very interested in Java and want to learn a lot more about it.
If anyone has suggestions or know where i can find the information Im looking for please let me know.
Thanks
Code I have so Far:
* @(#)SpellingTest.java
* SpellingTest Applet application
* @author
* @version 1.00 2010/11/10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SpellingTest extends JApplet implements ActionListener {
Image img;
ImageIcon icon;
private Image title;
JTextField word;
JButton addWord;
JLabel label;
JList wordList;
public void init() {//opening init
getContentPane().setLayout(null);
getContentPane().setBackground(Color.WHITE);
title = getImage(getDocumentBase(), "title.jpg");
//The text field
word = new JTextField();
word.setLocation(190,100);
word.setSize(85,30);
getContentPane().add(word);
word.addActionListener(this);
//The addWord button
addWord = new JButton("ADD");
addWord.setLocation(295, 100);
addWord.setSize(90,30);
getContentPane().add(addWord);
addWord.setBackground(new Color(146, 205, 220));
addWord.addActionListener(this);
//The label
label = new JLabel("Type your spelling words:");
label.setLocation(25, 65);
label.setSize(250,100);
getContentPane().add(label);
label.setForeground(new Color(146, 205, 220));
//The List
wordList = new JList();
JScrollPane scrollPane = new JScrollPane(wordList,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setLocation(25,150);
scrollPane.setSize(150,300);
getContentPane().add(scrollPane);
}//closing init
public void actionPerformed (ActionEvent ae){
Object obj = ae.getSource();
String text = word.getText();
if (obj == addWord){
if (text.length()>0);
wordList.addString("");
public void paint(Graphics g) {
super.paint(g);
}Read the first posting titled "Welcome to the new home" to learn how to use code tags. Then you can edit your posting so the code is formatted and readable.
I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.Read the JList API and follow the link to the Swing tutoral on "How to Use Lists" where you will find a working example.
So far I have my layout Actually you haven't. You should learn how to use layout managers. Again the Swing tutorial explains what layout managers are and provides working example of using them.
I am very interested in Java and want to learn a lot more about it.A great place to start is by read tutorials because they always contain working example. Here are some [url http://download.oracle.com/javase/tutorial/]Java tutorrial. -
How can I associate an ActionListener with a specific button
I modified the code a lot. Everything works except that it does not associate the actionListener with the button. It will do the action when the window is minimized or maximized, but not when the button is clicked.
//July 2, 2011
//Multiplication Tables
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultTables extends JApplet implements ActionListener
//Create Variables for Multiplication Problems
int factorX = 1;
int factorY = 1;
int productZ = 1;
int productReply;
//Create the TextField
JTextField answer = new JTextField(10);
//Create Labels and buttons
JLabel productZLabel = new JLabel(factorX + " * " + factorY + " = ");
JButton checkAnswer = new JButton("Check Answer");
//Create a container
Container con = getContentPane();
FlowLayout flow = new FlowLayout();
public void init()
//What goes init? What needs to be added to the interface?
con.setLayout(flow);
//Add Components and create interface
con.add(productZLabel);
con.add(answer);
con.add(checkAnswer);
//Add ActionListener to button
checkAnswer.addActionListener(this);
public void actionPerformed(ActionEvent e)
productZ = factorX * factorY;
String productReplyString = (answer.getText());
productReply = (Integer.valueOf(productReplyString));
for(int sub = 1; sub <= 9; ++sub);
if (productReply == productZ)
JLabel correct = new JLabel("That is correct!");
con.remove(productZLabel);
con.remove(answer);
con.remove(checkAnswer);
con.add(correct);
++factorX;
else
JLabel incorrect = new JLabel("The correct answer is " + productZ);
con.remove(productZLabel);
con.remove(answer);
con.remove(checkAnswer);
con.add(incorrect);
++factorX;
}EJP wrote:
Are you sure you're running that code? It should work. ActionListeners don't respond to min/max events.Yup. But the repaint triggered by resizing updates the display.
db
Maybe you are looking for
-
Need help setting up my d-link wireless router to my imac
I need some help trying to set up my D-Link WBR 2310 wireless router to my iMac. I currently have Bell Sympatico high speed. The reason I want to set up the wireless router is because my girlfriend works from home sometimes with her office computer d
-
I bought a new laptop over the holidays and decided to finally get my itunes set up on it. I went to itunes and purchased four new songs all excited. I plugged in my...I think..fifth generation ipod touch to the computer. I had the usually update box
-
In a document library Show time in seconds also for a created column
HI i created a sitecollection with DocumentCenter Template and created documentlibrary, after i upload documents i want to see created column should display seconds with created time how it is possible to show seconds also with time. adil
-
Show debit and credit of documents
Hi, what is the transaction with which i can show the debit and the credit of each document. for e.g with FBL3N we can show documents but we must enter inside for showing details (debit and credit). for having a quick consultation of documents how to
-
How do I reduce the database size that teststand creates
Currently the test report access database file is growing like crazy. Its now around 500mb. I forcast in a month or two is will be 1 Gig. Currently things are stored in verbose (complete mode). What does one need to do to make it store in terse m