What I am trying to do is keep the user from inputting an empty string into my input. Right now, the user is restricted to typing only numbers. However, nothing keeps them from leaving the text field blank. I want to restrict them from hitting my button to start the program when it is blank.
Right now, my text field is initially left blank and the button is grayed out initially. But when I type something in, the button stays greyed. Keep in mind all this code is in the constructor.
private JTextField plays = new JTextField(7);
DocumentFilter filter = new NumberFilter();
((AbstractDocument)plays.getDocument()).setDocumentFilter(filter);
plays.setToolTipText("Please input an integer.");
if(plays.getText().equals(""))
play.setEnabled(false);
private class NumberFilter extends DocumentFilter
{
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException
{
fb.insertString(offset, text.replaceAll("[^0-9]", ""), attrs);
}
}
Right now your filter code just edits to make sure only integer digits are entered into the document.
After the insert you will also need to add an additional check to see if any data has been entered and then enable/disable the text field as required.
Here is an example that uses a DocumentListener to do this:
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;
public class DataEntered implements DocumentListener
{
private JButton button;
private List<JTextField> textFields = new ArrayList<JTextField>();
public DataEntered(JButton button)
{
this.button = button;
}
public void addTextField(JTextField textField)
{
textFields.add( textField );
textField.getDocument().addDocumentListener( this );
}
public boolean isDataEntered()
{
for (JTextField textField : textFields)
{
if (textField.getText().trim().length() == 0)
return false;
}
return true;
}
#Override
public void insertUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void removeUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void changedUpdate(DocumentEvent e) {}
private void checkData()
{
button.setEnabled( isDataEntered() );
}
private static void createAndShowUI()
{
JButton submit = new JButton( "Submit" );
submit.setEnabled( false );
JTextField textField1 = new JTextField(10);
JTextField textField2 = new JTextField(10);
DataEntered de = new DataEntered( submit );
de.addTextField( textField1 );
de.addTextField( textField2 );
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textField1, BorderLayout.WEST);
frame.add(textField2, BorderLayout.EAST);
frame.add(submit, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
The concept would be the same for a DocumentFilter. You need to do the check when you insert or remove text.
Related
I have a JDialog with two JTextFields, one ButtonGroup with two RadioButtons and an OK-Button. The button has to be disabled until the TextFields are filled and at least one of the RadioButtons clicked. I'm not sure how to do this.
It works for with the JTextFields using this code:
public class Test {
public static void main(String... args) {
ButtonTest.show();
}
}
class ButtonTest {
private ButtonTest() {
JFrame frame = new JFrame("Button Test");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel mainPanel = new JPanel(new GridLayout(4, 1));
JTextField field1 = new JTextField(20);
JTextField field2 = new JTextField(20);
JLabel text = new JLabel();
JButton printButton = new JButton("Print");
printButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text.setText(field1.getText() + " - " + field2.getText());
}
});
printButton.setEnabled(!field1.getText().isEmpty() && !field2.getText().isEmpty());
for (JComponent c : Arrays.asList(field1, field2, text, printButton)) {
mainPanel.add(c);
}
setDocumentListener(field1, field2, printButton);
setDocumentListener(field2, field1, printButton);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
private void setDocumentListener(JTextField field, JTextField other, JButton button) {
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
changed();
}
#Override
public void insertUpdate(DocumentEvent e) {
changed();
}
#Override
public void changedUpdate(DocumentEvent e) {
changed();
}
private void changed() {
setButtonStatus(button, field.getText(), other.getText());
}
});
}
private void setButtonStatus(JButton button, String field1, String field2) {
button.setEnabled(!field1.isEmpty() && !field2.isEmpty());
}
public static void show() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest();
}
});
}
}
But what about the RadioButtons? I guess I have to somehow implement an ItemListener?
Greetings
You need two tests:
Does the JTextField contain non-whitespace text, tested like so, !textField.getText().trim().isEmpty(), and
Is one JRadioButton selected, which can be tested by seeing if the ButtonGroup contains a non-null ButtonModel selection via buttonGroup.getSelection() != null
Combined, it could look something like:
private void testToActivateButton() {
boolean value = !textField.getText().trim().isEmpty() && buttonGroup.getSelection() != null;
submitButton.setEnabled(value);
}
Then simply call the above method in ActionListeners added to the JRadioButtons and your JTextField's DocumentListener. For example:
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ActivateButton extends JPanel {
private static final String[] RADIO_TEXTS = {"Hello", "Goodbye"};
private ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textField = new JTextField(10);
private JButton submitButton = new JButton("Submit");
public ActivateButton() {
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
testToActivateButton();
}
#Override
public void insertUpdate(DocumentEvent e) {
testToActivateButton();
}
#Override
public void changedUpdate(DocumentEvent e) {
testToActivateButton();
}
});
for (String radioText : RADIO_TEXTS) {
JRadioButton radioButton = new JRadioButton(radioText);
radioButton.addActionListener(e -> testToActivateButton());
buttonGroup.add(radioButton);
add(radioButton);
}
submitButton.setEnabled(false);
add(textField);
add(submitButton);
}
private void testToActivateButton() {
boolean value = !textField.getText().trim().isEmpty() && buttonGroup.getSelection() != null;
submitButton.setEnabled(value);
}
private static void createAndShowGui() {
ActivateButton mainPanel = new ActivateButton();
JFrame frame = new JFrame("ActivateButton");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
You can use isSelected() to check whether the radio button is selected.
Eg:
printButton.setEnabled(!field1.getText().isEmpty() && !field2.getText().isEmpty() && (radioBtn1.isSelected() || radioBtn2.isSelected()) );
Check out: Validation of text fields and contact no text field
It provides a general solution for enabling a button when data is entered in all text fields.
You can enhance that solution to also support radio buttons.
But what about the RadioButtons? I guess I have to somehow implement an ItemListener?
You can modify the DataEntered class found in the link above to do the following:
implement an ItemListener to simply invoke the isDataEntered() method.
create a new addButtonGroup(...) method. This method would save the ButtonGroup and then iterate through all the radio buttons in the group to add the ItemListener to the radio button.
then you would need to modify the isDataEntered() method to iterate through each ButtonGroup and invoke the getSelection() method on the ButtonGroup. If the value is null that means no radio button has been selected and you just return false.
I'm making a small java program where I have two JTextFields labeled field1, field2. I have a calculate button as well which initially set to disabled. I want the button only to be enabled when the 2 text boxes have values in them. Currently what i have for the key listener is:
field1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
if (field1.getDocument().getLength() > 0) {
bt1.setEnabled(true);
}
else {
bt1.setEnabled(false);
}
}
});
Is there a way to include field 2 into the above block? I've tried just copying and pasting the same code block twice but changing the field1 to field2 but that still doesn't work.
Thanks for the help
You really never want to use a KeyListener with a JTextField as this can mess up the JTextField's function. Much better is to use a DocumentListener and give it to both JTextField's Documents.
For example please check out this similar question
Or if you need to be notified of text changes before they are validated, use a DocumentFilter. For more on that, please see this question.
e.g.,
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DocListenerEg extends JPanel {
private JTextField field1 = new JTextField(10);
private JTextField field2 = new JTextField(10);
private JButton button = new JButton("Button");
public DocListenerEg() {
add(field1);
add(field2);
add(button);
button.setEnabled(false);
DocumentListener docListener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
checkForText();
}
#Override
public void insertUpdate(DocumentEvent e) {
checkForText();
}
#Override
public void changedUpdate(DocumentEvent e) {
checkForText();
}
private void checkForText() {
boolean textOK = !field1.getText().trim().isEmpty() && !field2.getText().trim().isEmpty();
button.setEnabled(textOK);
}
};
field1.getDocument().addDocumentListener(docListener);
field2.getDocument().addDocumentListener(docListener);
}
private static void createAndShowGui() {
DocListenerEg mainPanel = new DocListenerEg();
JFrame frame = new JFrame("DocListenerEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You current requirement may be for only two text fields, but you should always design to be more flexible and allow any number of text fields. This also allows the code to be reusable.
Something like:
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;
public class DataEntered implements DocumentListener
{
private JButton button;
private List<JTextField> textFields = new ArrayList<JTextField>();
public DataEntered(JButton button)
{
this.button = button;
}
public void addTextField(JTextField textField)
{
textFields.add( textField );
textField.getDocument().addDocumentListener( this );
}
public boolean isDataEntered()
{
for (JTextField textField : textFields)
{
if (textField.getText().trim().length() == 0)
return false;
}
return true;
}
#Override
public void insertUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void removeUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void changedUpdate(DocumentEvent e) {}
private void checkData()
{
button.setEnabled( isDataEntered() );
}
private static void createAndShowUI()
{
JButton submit = new JButton( "Submit" );
submit.setEnabled( false );
JTextField textField1 = new JTextField(10);
JTextField textField2 = new JTextField(10);
DataEntered de = new DataEntered( submit );
de.addTextField( textField1 );
de.addTextField( textField2 );
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textField1, BorderLayout.WEST);
frame.add(textField2, BorderLayout.EAST);
frame.add(submit, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
I would like the user to enter a value into the JTextField and use a listener to listen to the textfield and print the value to the console straightaway without pressing a key.
textfield1.addChangeListener(new ChangeListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(textfield1);
}
});
error:
<anonymous textfield$2> is not abstract and does not override abstract method stateChanged(ChangeEvent) in ChangeListener
Put this private class into your public class. Just like a method.
private class textChangedListener implements KeyListener
{
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e)
{
System.out.print(textField1.getText());
}
}
And then call it to your JTextField in your main method like so:
private JTextField textField1; // just showing the name of the JTextField
textField1.addKeyListener(new textChangedListener());
Yes, just use the KeyListener class, see the example below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Main extends JFrame {
public Main() throws HeadlessException {
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel("Write something: ");
JTextField input = new JTextField();
input.setPreferredSize(new Dimension(100, 20));
final JTextField output = new JTextField();
output.setPreferredSize(new Dimension(100, 20));
add(label);
add(input);
add(output);
input.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
output.setText(text);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
});
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
You can set a addlistener to textproperty of the text field.
textField.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println("textfield changed to "+ newValue);
}
});
I have a problem, I have been making a Swing application.
My question is about how to handle Jbutton like a JOptionPane, if it's possible?
I want handle all of the buttons similarly to JOptionpane button, but our message written in main function System.out.println("this line executes...how to prevent..");
This function is to display the message, until Jframe is visible.
Can anyone let me know how to prevent & how to handle button functionality? Especially when it executes further when I click the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
JLabel name=new JLabel("Name:");
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(false);
JPanel namePanel = new JPanel();
namePanel.add(name);
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
warningLabel.setForeground(Color.red);
add(warningLabel, BorderLayout.NORTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty :"+name.getText());
warningLabel.setBackground(WARNING_COLOR);
//firstNameField.setText("sorry");
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setSize(200, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGui();
System.out.println("this line executes...how to prevent..");
}
}
Basically, you have something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
System.err.println("Executed once the button has been clicked");
}
}
And you want the line System.err.println("Executed once the button has been clicked"); to be executed when the button is pressed (which is not the case here above).
The solution is actually very simple: you move the code to execute after the button click in another method (see below the proceed() method) and you invoke that line from an ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
proceed();
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
protected void proceed() {
System.err.println("Executed once the button has been clicked");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
}
}
Well, the question is not very much clear,but from your comment,you dont want to do any thing till a JButton is clicked? Or you want to preform a task after clicking of a button?
If that is so, dont put your further code inside your main block, call a function from actionPerformed block.Something like this:
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
display();///////////this is the function containing further code
}
}
//this is display
public void display()
{
System.out.println("this line executes...how to prevent..");
}
I have a JFrame which contains 3 JPanels. I want to pass the JTextField value of one panel to other. Each panel is shown using JTabbedPane. I am getting null when i access the value of other text field. How can i access?
You don't show any code, and so it's impossible to know why you're getting "null" values. Two possible solutions if you want all three JPanels to hold JTextFields with the same content:
Put the shared JTextField outside of the JPanels held by the JTabbedPane and instead in a JPanel that holds the JTabbedPane, so that the field is always visible no matter what tab is displayed, or
Use several JTextFields but have them share the same Document or "model".
e.g.,
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.PlainDocument;
public class SharedField extends JTabbedPane {
private static final int TAB_COUNT = 5;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
PlainDocument doc = new PlainDocument();
public SharedField() {
for (int i = 0; i < TAB_COUNT; i++) {
JTextField tField = new JTextField(10);
tField.setDocument(doc);
JPanel panel = new JPanel();
panel.add(tField);
add("Panel " + i, panel);
// to demonstrate some of the JTextFields acting like
// a label
if (i % 2 == 1) { // if i is odd
tField.setEditable(false);
tField.setBorder(null);
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField");
frame.getContentPane().add(new SharedField());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Edit 1
I see that you've cross-posted this on java-forums.org/ where you show some of your code:
pacage Demotool;
Class:MainFrame
This is the actionPerformed code of first panel
both str and scrTxt is (public static)
public void actionPerformed(ActionEvent e)
{
String act=e.getActionCommand();
if(act.equals("ADD"))
{
str=scrnTxt.getText();
System.out.println("Hi :"+str);
Demotool.DemoTool.jtp.setSelectedIndex(1);
}
}
using the belove code i tried to access the data but I am getting null String:
System.out.println("Hello:"+Demotool.MainFrame.str);
Problems:
Don't use static variables or methods unless you have a good reason to do so. Here you don't.
You're may be trying to access the MainFrame.str variable before anything has been put into it, making it null, or you are creating a new MainFrame object in your second class, one that isn't displayed, and thus one whose str variable is empty or null -- hard to say.
Either way, this design is not good. You're better off showing us a small demo program that shows your problem with code that compiles and runs, an sscce, so we can play with and modify your code and better be able to show you a decent solution.
One such decent solution is to add a DocumentListener to the JTextField so that changes to the text held by the JTextField are "pushed" into the observers that are listening for changes (your other classes).
For example, using DocumentListeners:
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
public class SharedField2 extends JTabbedPane {
private static final int LABEL_PANEL_COUNT = 4;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
public SharedField2() {
TextFieldPanel tfPanel = new TextFieldPanel();
LabelPanel[] labelPanels = new LabelPanel[LABEL_PANEL_COUNT];
add("TextFieldPanel", tfPanel);
for (int i = 0; i < labelPanels.length; i++) {
labelPanels[i] = new LabelPanel();
// add each label panel's listener to the text field
tfPanel.addDocumentListenerToField(labelPanels[i].getDocumentListener());
add("Label Panel " + i, labelPanels[i]);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField2");
frame.getContentPane().add(new SharedField2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class TextFieldPanel extends JPanel {
private JTextField tField = new JTextField(10);
public TextFieldPanel() {
add(tField);
}
public void addDocumentListenerToField(DocumentListener listener) {
tField.getDocument().addDocumentListener(listener);
}
}
class LabelPanel extends JPanel {
private DocumentListener myListener;
private JLabel label = new JLabel();
public LabelPanel() {
add(label);
myListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
try {
label.setText(e.getDocument().getText(0,
e.getDocument().getLength()));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
};
}
public DocumentListener getDocumentListener() {
return myListener;
}
}
One simple solution will be making JTextField global so all panel can access it.
Make sure all your panel can access JTextField that is textField is globally accessible.
Following code demonstrate this:
JTextField textField = new JTextField(25);
JLabel labelForPanel2 = new JLabel(),labelForPanel3 = new JLabel();
private void panelDemo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", panel1);
tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);
panel1.add(textField);
panel2.add(labelForPanel2);
panel3.add(labelForPanel3);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
labelForPanel2.setText(textField.getText());
labelForPanel3.setText(textField.getText());
}
});
frame.add(tabbedPane);
frame.setVisible(true);
}
I don't know what exactly are you going to achieve, but maybe try data binding?
Take a look at BetterBeansBinding library.