I have a program that will make a JFrame with a JTextField. How do I get it to wait for text to be in the JTextField / the enter key is pressed?
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
JFrame frame = new JFrame();
frame.getContentPane().add(new Text());
JTextField field = new JTextField(10);
frame.add(field, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width,height-55);
frame.setVisible(true);
// There is a keylistener here called listener. It was 100 lines. Did not want to copy
frame.addKeyListener(listener);
double x = 0;
x = Double.parseDouble(field.getText());
System.out.println(x);
I want
x = Double.parseDouble(field.getText());
to run only when someone types something in the JTextField in the JFrame.
Don't use a KeyListener
Add a DocumentListener to your JTextField's Document.
Inside of this listener check to see if the Document is empty or not.
If not empty, change the state of your program to allow the calculation, perhaps by enabling or disabling a JButton or Action.
For example:
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class DisbleButton extends JPanel {
private JTextField field = new JTextField(10);
private ButtonAction buttonAction = new ButtonAction();
private JButton button = new JButton(buttonAction);
public DisbleButton() {
add(field);
add(button);
buttonAction.setEnabled(false);
field.getDocument().addDocumentListener(new FieldDocListener());
}
private class FieldDocListener implements DocumentListener {
#Override
public void changedUpdate(DocumentEvent dEvt) {
testDoc(dEvt);
}
#Override
public void insertUpdate(DocumentEvent dEvt) {
testDoc(dEvt);
}
#Override
public void removeUpdate(DocumentEvent dEvt) {
testDoc(dEvt);
}
private void testDoc(DocumentEvent dEvt) {
Document doc = dEvt.getDocument();
buttonAction.setEnabled(doc.getLength() > 0);
}
}
private class ButtonAction extends AbstractAction {
public ButtonAction() {
super("Press Me");
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO do calculation here!
}
}
private static void createAndShowGui() {
DisbleButton mainPanel = new DisbleButton();
JFrame frame = new JFrame("DisbleButton");
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();
}
});
}
}
Related
am trying to add a button to Jframe from other class but it does not work
public class ShowMain {
public static void main(String[] args) throws Throwable {
//My JFrame
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setLayout(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.GRAY);
}
My other Class
public class Commands {
public static void main(String[] args) throws Throwable {
//JButtons
JButton button1 = new JButton();
button1.setText("");
button1.setBounds(120, 350, 400, 20);
button1.setVisible(true);
}
frame.add(button1) is not working
You've got all your code within two static main methods, meaning that the two classes can hardly interact at all. I suggest that you create true OOP-compliant classes, with instance fields ("state"), instance methods ("behavior"), and that you have one class call the method of another if you wish to change its state. For instance, if the Commands class is to add a JButton, then give your ShowMain class a method for this: public void addCommandButton(JButton button).
Having said this, I wouldn't do this at all if this were my code, but rather would follow a more MVC or "Model-View-Controller" program structure, where one set of classes would represent the program logic, another the user interactions (the listeners) and a 3rd set of classes for the GUI or "view".
For example, run this code that shows how to connect classes without them knowing about the other class (loose coupling):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ShowMain {
private static void createAndShowGui() {
MainPanel mainPanel = new MainPanel();
JScrollPane scrollPane = new JScrollPane(mainPanel);
CreateActionPanel actionPanel = new CreateActionPanel();
new Controller(actionPanel, mainPanel);
JFrame frame = new JFrame("ShowMain");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(actionPanel, BorderLayout.PAGE_START);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MainPanel extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 80;
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
public MainPanel() {
setBorder(BorderFactory.createTitledBorder("Main Panel"));
}
public void addButtonAction(Action action) {
add(new JButton(action));
// so the button will be displayed properly
revalidate();
repaint();
}
}
class Controller {
public Controller(final CreateActionPanel actionPanel, final MainPanel mainPanel) {
actionPanel.addPropertyChangeListener(CreateActionPanel.ACTION_NAME, pcEvt -> {
mainPanel.addButtonAction(new AbstractAction((String) pcEvt.getNewValue()) {
{
int mnemonic = (int) pcEvt.getNewValue().toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent evt) {
System.out.printf("Button %s pressed!%n", evt.getActionCommand());
}
});
});
}
}
class CreateActionPanel extends JPanel {
public static final String ACTION_NAME = "action name";
private JTextField actionNameField = new JTextField(10);
public CreateActionPanel() {
actionNameField.addActionListener((e -> {
String text = actionNameField.getText();
firePropertyChange(ACTION_NAME, null, text);
actionNameField.selectAll();
}));
add(new JLabel("Button Text to Add:"));
add(actionNameField);
}
}
I am using a self made toolbar to navigate through my application and the toolbar is present on all pages. Each time a new page is displayed I am closing the current frame and opening a new one, using the following code:
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
I am doing it this way as the ActionListeners are declared in the toolbar class, whilst the frames for each page are declared at runtime and are not static.
This all works fine except for one particular case-the "cancel" button, where the first time the frame is accessed it will close once. The second time it will close and re open 2 times, the third 3 and so on. I have tracked this using the "counter" in the code.
I have minimised the code to recreate the same behaviour, as below:
Toolbar Class
public class Toolbar {
static JButton buttonCancel = new JButton("Cancel");
static int counter;
public static JPanel Toolbar(String panelname){
FlowLayout layout = new FlowLayout();
JPanel Toolbar = new JPanel(new BorderLayout());
Toolbar.setLayout(layout);
GridLayout GLayout = new GridLayout(2,1);
GLayout.setVgap(0);
JPanel container2 = new JPanel();
if(panelname.matches("Customers")){
container2.setLayout(GLayout);
JButton buttonAddCust = new JButton("Add Cust");
container2.add(buttonAddCust, BorderLayout.PAGE_START);
buttonAddCust.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
Customers.AddCustomersGui();
}
});
}
JPanel container21 = new JPanel();
if(panelname.matches("Add Customers")){
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter ++;
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
}
Toolbar.add(container2);
Toolbar.add(container21);
return Toolbar;
}
}
GUI class
public class Customers extends Toolbar{
public static void CustomersGui(){
final JFrame frame = new JFrame("Customers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel customers = new JPanel();
customers.add(Toolbar.Toolbar(frame.getTitle()));
frame.setContentPane(customers);
frame.setSize(1200,500);
frame.setVisible(true);
}
public static void AddCustomersGui(){
final JFrame frame1 = new JFrame("Add Customers");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Addcustomers = new JPanel();
Addcustomers.add(Toolbar.Toolbar(frame1.getTitle()));
frame1.setContentPane(Addcustomers);
frame1.setSize(1200,500);
frame1.setVisible(true);
}
}
main class
public static void main(String[] args) {
Customers.CustomersGui();
}
You are adding a new ActionListener to the buttonCancel, with each iteration of your code and this is the reason for your program's behavior.
Also, as per my comment, you state,
Each time a new page is displayed I am closing the current frame and opening a new one.
A better design is probably not to swap windows which can be annoying, but rather to swap JPanel views using a CardLayout. Please read The Use of Multiple JFrames, Good/Bad Practice?.
For example, add this line of code to your program:
if (panelname.matches("Add Customers")) {
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
java.awt.Window win[] = java.awt.Window.getWindows();
for (int i = 0; i < win.length; i++) {
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
// ***** add this here **********
System.out.println("buttonCancel ActionListener count: "
+ buttonCancel.getListeners(ActionListener.class).length);
}
and you'll see that the ActionListeners get added multiple times to this button.
An example of swapping views:
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwapPanels extends JPanel {
public static final String CUSTOMER = "customer";
public static final String ADD_CUSTOMER = "Add Customer";
protected static final int PREF_W = 800;
protected static final int PREF_H = 600;
public static final String CANCEL = "Cancel";
private CardLayout cardLayout = new CardLayout();
public SwapPanels() {
setLayout(cardLayout);
add(createCustomerPanel(CUSTOMER), CUSTOMER);
add(createAddCustomerPanel(ADD_CUSTOMER), ADD_CUSTOMER);
}
public void showCard(String key) {
cardLayout.show(this, key);
}
public JPanel createAddCustomerPanel(String name) {
JPanel addCustPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
addCustPanel.setName(name);
addCustPanel.setBorder(BorderFactory.createTitledBorder(name));
addCustPanel.add(new JButton(new AbstractAction(CANCEL) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (CANCEL.equals(e.getActionCommand())) {
SwapPanels.this.showCard(CUSTOMER);
}
}
}));
return addCustPanel;
}
private JPanel createCustomerPanel(String name) {
JPanel custPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
custPanel.setName(name);
custPanel.setBorder(BorderFactory.createTitledBorder(name));
custPanel.add(new JButton(new AbstractAction(ADD_CUSTOMER) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (ADD_CUSTOMER.equals(e.getActionCommand())) {
SwapPanels.this.showCard(ADD_CUSTOMER);
}
}
}));
return custPanel;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SwapPanels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SwapPanels());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
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 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.