Java: Not able to print on TextArea from other class - java

I have one frame in which one TestArea is there. When I append some string from this class then String is appended but when I want to append String from other class then String is not appended. I created one method to append string in TextArea, when I call this method in this class then string is appended on text Area. But when I call this method from other Class then String is not appended on TextArea.
Code (MainClass):
public class MainClass {
private JFrame frame;
private TextArea textArea;
private Font font;
private JButton button1;
private JButton button2;
private SecondClass secondClass;
public MainClass() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new JFrame("XXX");
frame.setBounds(200, 200, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
button1 = new JButton("Button1");
font = new Font("Arial", Font.BOLD, 13);
button1.setFont(font);
button1.setBounds(4, 4, 289, 30);
button2 = new JButton("Button2");
button2.setFont(font);
button2.setBounds(300, 4, 289, 30);
font = null;
textArea = new TextArea();
textArea.setBounds(4, 38, 585, 322);
textArea.setEnabled(true);
font = new Font("Arial", Font.PLAIN, 13);
textArea.setFont(font);
frame.add(button1);
frame.add(button2);
frame.add(textArea);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
textArea.append("*** I am in actionPerformed() ***\n");
appendToTextArea("Call from actionPerformed() method\n");
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
secondClass = new SecondClass();
secondClass.printOnTextArea();
}
});
} catch (Exception e) {
textArea.append(e.toString());
}
}
public void appendToTextArea(String str) {
System.out.println(str+"\n");
textArea.append(str+"\n"); //this line not work when I call this method from other class
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainClass window = new MainClass();
window.frame.setVisible(true);
}
});
}
}
Code(SecondClass):
import com.grissserver.MainClass;
public class SecondClass extends MainClass{
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
super.appendToTextArea("call from Second Class in printOnTextArea()");
}
}
Please give some Idea, why this is not working.

I think the problem is that the way you try to paint to the text area is wrong.
In your action method you create a new object of SecondClass which extends MainClass. This means this object has its own textarea object. But this new object (frame) is not displayed, because you only call setVisibile in MainClass#main, and hence you cannot see the displayed text!
In short: There are two different text areas! And one of them is not visible

The SecondClass has its own textArea. So you may need to pass MainClass's textArea to SecondClass.
public class SecondClass {
private TextArea tArea;
SecondClass(TextArea ta) {
tArea = ta;
}
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
tArea.append("call from Second Class in printOnTextArea()");
}
}
You should change your MainClass like this.
....
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
secondClass = new SecondClass(textArea);
secondClass.printOnTextArea();
}
});
....
hope this helps...

Related

Manage JFrame Instances

In my project I've one instance of jframe1 and two instance of jframe2. Then I want to update from jframe1 txt2 component of first instance of jframe2. But when I invoke perfomaction() method it was to update the second instance of jframe2.
public class Jframe1 extends Jframe {
public jframe1() {
Performedaction() {
jframe2.txt2.setText("do it");
}
}
public class jframe2 extends Jframe {
public static JtextFiedl txt2;
public jframe2() {
}
Here is an example.. The example uses two JFrame window's and on clicking a button in one jframe, the second one's JLabel is updated. The example uses a JLabel instead of JTextField.
The mechanism uses java.util.Observer interface and Observable class to update from one window to the other one.
The example's code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TwoFramesExample {
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TwoFramesExample().start();
}
});
}
private void start() {
Frame1 f1 = new Frame1();
new Frame2(f1);
}
}
class Frame1 implements Observer {
private JLabel label;
#Override // Observer interface's implemented method
public void update(Observable o, Object data) {
label.setText((String) data); // displays new text in JLabel
}
Frame1() {
JFrame f1 = new JFrame("Frame-1");
f1.getRootPane().setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
label = new JLabel("Click button in frame-2...");
label.setFont(new Font("Dialog", Font.PLAIN, 20));
f1.add(label);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(350, 150);
f1.setLocation(200, 200);
f1.setVisible(true);
}
}
class Frame2 {
private int clicks;
Frame2(Frame1 f1) {
// Create Observable and add Observer
final MessageObservable observable = new MessageObservable();
observable.addObserver(f1);
// Display frame
JFrame f2 = new JFrame("Frame-2");
JButton button = new JButton("Press me");
button.setFont(new Font("Dialog", Font.PLAIN, 20));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "button clicks in frame-2: [" + ++clicks + "]";
observable.changeData(data);
}
});
f2.add(button);
f2.setSize(250, 150);
f2.setLocation(600, 200);
f2.setVisible(true);
}
}
class MessageObservable extends Observable {
MessageObservable() {
super();
}
void changeData(Object data) {
// the two methods of Observable class
setChanged();
notifyObservers(data);
}
}

Open a JFrame into another JFrame

I am creating a program, and I have my main class that works with all the JButtons, but I can't get my second class that calls the first class launch with the buttons. The JFrame will launch, but the buttons won't.
I am using eclipse just for the information.
Here is the code of my main class:
public class Unescapable extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private static final Font font1 = new Font("FONT", Font.BOLD, 75);
protected JButton b1;
protected JButton b2;
protected JButton b3;
protected JButton b5;
protected JTextField t1;
public Unescapable()
{
t1 = new JTextField("Unescapable");
t1.setText("Unescapable");
t1.setBounds(225, 50, 750, 100);
t1.setForeground(Color.LIGHT_GRAY);
t1.setOpaque(true);
t1.setVisible(true);
t1.setEditable(false);
t1.setBackground(Color.BLACK);
t1.setFont(font1);
b1 = new JButton("Open Window");
b1.setActionCommand("open");
b1.setBackground(Color.GRAY);
b1.setForeground(Color.white);
b1.setOpaque(true);
b1.setBorderPainted(false);
b1.setBounds(280, 200, 390, 40);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.GRAY);
}
});
b2 = new JButton("Delete File");
b2.setActionCommand("delete");
b2.setBackground(Color.GRAY);
b2.setForeground(Color.white);
b2.setOpaque(true);
b2.setBorderPainted(false);
b2.setBounds(280, 255, 390, 40);
b2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.GRAY);
}
});
b3 = new JButton("Info...");
b3.setActionCommand("info");
b3.setBackground(Color.GRAY);
b3.setForeground(Color.white);
b3.setOpaque(true);
b3.setBorderPainted(false);
b3.setBounds(278, 330, 185, 40);
b3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b3.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b3.setBackground(Color.GRAY);
}
});
b5 = new JButton("Quit Game");
b5.setActionCommand("close");
b5.setBackground(Color.GRAY);
b5.setForeground(Color.white);
b5.setOpaque(true);
b5.setBorderPainted(false);
b5.setBounds(485, 330, 185, 40);
b5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b5.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b5.setBackground(Color.GRAY);
}
});
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b5.addActionListener(this);
b1.setToolTipText("Opens Another JWindow");
b2.setToolTipText("Deletes \"text.txt\"");
b3.setToolTipText("Give's some information.");
add(b1);
add(b2);
add(b3);
add(b5);
add(t1);
System.out.println("Main Window Is Running");
}
public void actionPerformed(ActionEvent e)
{
if ("open".equals(e.getActionCommand()))
{
File f = new File("text.txt");
try
{
PrintWriter out = new PrintWriter(f);
out.println("TheBestMacTutorials");
out.close();
}
catch (Exception e2)
{
}
}
else if ("delete".equals(e.getActionCommand()))
{
File f = new File("text.txt");
f.delete();
}
else if ("info".equals(e.getActionCommand()))
{
InfoBook add = new InfoBook();
add.call();
}
else
{
System.out.println("Window Is Now Closing");
System.exit(0);
}
}
private static void createAndShowGUI()
{
JFrame program = new JFrame("My Program");
program.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Unescapable newContentPane = new Unescapable();
program.setContentPane(newContentPane);
program.setLayout(null);
program.setVisible(true);
program.setLocation(850, 445);
program.setSize(900, 580);
program.setTitle("Unescapable 1.0");
program.setBackground(Color.GREEN);
program.isOpaque();
program.isForegroundSet();
program.getContentPane().setBackground(Color.BLACK);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
The code for the "Info Book":
public class InfoBook extends JFrame
{
private static final long serialVersionUID = 1L;
private static final Font font1 = new Font("FONT", Font.BOLD, 75);
protected JButton b1;
protected JButton b2;
protected JTextField t1;
public InfoBook()
{
b1 = new JButton("Cancel");
b1.setActionCommand("cancel");
b1.setBackground(Color.GRAY);
b1.setForeground(Color.white);
b1.setOpaque(true);
b1.setBorderPainted(false);
b1.setBounds(280, 200, 390, 40);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.GRAY);
}
});
b2 = new JButton("More Info");
b2.setBackground(Color.GRAY);
b2.setForeground(Color.WHITE);
b2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.GRAY);
}
});
t1 = new JTextField("Info");
t1.setText("Info...");
t1.setBounds(225, 50, 750, 100);
t1.setForeground(Color.LIGHT_GRAY);
t1.setOpaque(true);
t1.setVisible(true);
t1.setEditable(false);
t1.setBackground(Color.BLACK);
t1.setFont(font1);
b1.setToolTipText("Opens Another JWindow");
b2.setToolTipText("Gives More Infomation");
add(b1);
add(b2);
add(t1);
System.out.println("Info is now running");
}
public static void creatAndShowGUI()
{
JFrame frame = new JFrame("Info Panel");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
InfoBook newContentPane = new InfoBook();
frame.setLayout(null);
frame.setVisible(true);
frame.setLocation(850, 445);
frame.setSize(900, 580);
frame.setTitle("Unescapable 1.0");
frame.setBackground(Color.GREEN);
frame.isOpaque();
frame.isForegroundSet();
frame.getContentPane().setBackground(Color.BLACK);
}
public static void call()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
creatAndShowGUI();
}
});
}
}
I believe thats all the code, and I am not very used to how to format the code in stack overflow, so I might of messed something up. I am probably just getting something messed up, so i am sorry for that but thanks in advance.
The main problem is in your createAndShowGUI in your InfoBook class...
public static void creatAndShowGUI() {
JFrame frame = new JFrame("Info Panel");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
InfoBook newContentPane = new InfoBook();
frame.setLayout(null);
frame.setVisible(true);
frame.setLocation(850, 445);
frame.setSize(900, 580);
frame.setTitle("Unescapable 1.0");
frame.setBackground(Color.GREEN);
frame.isOpaque();
frame.isForegroundSet();
frame.getContentPane().setBackground(Color.BLACK);
}
Essentially, you create an instance of newContentPane, but you never use it.
But, you're about to run into a second problem...
} else if ("info".equals(e.getActionCommand())) {
InfoBook add = new InfoBook();
add.call();
Here you create an instance of InfoBook, but this instance will have no relationship to the one that is created in your creatAndShowGUI and which I assume you want to show on the screen, so getting information from the class will be impossible
I suspect, you actually want to use a JDialog of some kind instead, which will allow you to present a window to the user, BUT which will block the execution of the code until the user closes the window, at which time you could then interrogate the object for it's information.
See How to Make Dialogs for more details
As a general rule of thumb, you don't want to extend from top level containers like JFrame or JDialog, instead, you want to use a JPanel as the base component and add these to what ever container you need.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
You might also like to have a look at The Use of Multiple JFrames, Good/Bad Practice?

Populating JList,attribute of class with JFrame from a JDialog

I have a MainForm class that extends JFrame and has a JList in it.
Now on clicking a button a JDialog pops up, to enter credentials, which in turn downloads a list of values which is to be populated in the Jlist of the parent window.
Now how do I populate my mainForm attribute from my child class ?
MainForm.java
public class MainForm extends JFrame {
static MainForm mainForm;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainForm = new MainForm();
mainForm.setVisible(true);
}
});
}
public MainForm() {
loadUI();
}
private void loadUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
final JList<String> jList = new JList<String>();
final JButton settings = new JButton(settingImage);
settings.setBorder(new EmptyBorder(3, 0, 3, 0));
settings.setBounds(50, 60, 100, 30);
vertical.add(settings);
settings.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LoginDialog loginDlg = new LoginDialog(mainForm);
loginDlg.setVisible(true);
// if logon successfully
if(loginDlg.isSucceeded()){
settings.setText("Hi " + loginDlg.getUsername() + "!");
}
}
});
add(vertical, BorderLayout.WEST);
add(jList, BorderLayout.CENTER);
DialogWindow.java
public LoginDialog(final Frame parent) {
super(parent, "Login", true);
//
JPanel panel = new JPanel(new GridBagLayout());
//some more lines of code
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ftpAuthenticationVO.setIp(urlIP.getText());
ftpAuthenticationVO.setUsername(tfUsername.getText());
ftpAuthenticationVO.setPassword(pfPassword.getText());
FileUtils.saveFTPDetails(ftpAuthenticationVO);
if(ftpConnect.startFTP(CommonConstants.TEMP_TXT_FILE));
{
List<String> list = readSplitTextFiles.readTextFile(CommonConstants.TEMP_TXT_FILE);
//This is the value that is to be populated in the Jlist inside the parent window.
}
Just make your JList as attribute of the MainForm
public class MainForm extends JFrame {
private JList jlist;
.
.
.
private void loadUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
jList = new JList<String>();
final JButton settings = new JButton(settingImage);
settings.setBorder(new EmptyBorder(3, 0, 3, 0));
settings.setBounds(50, 60, 100, 30);
vertical.add(settings);
.
.
}
public void setJListModel(List<String> list){
jlist.setModel(new Vector(list));
}
}
And in JDialog
public void actionPerformed(ActionEvent e) {
ftpAuthenticationVO.setIp(urlIP.getText());
ftpAuthenticationVO.setUsername(tfUsername.getText());
ftpAuthenticationVO.setPassword(pfPassword.getText());
FileUtils.saveFTPDetails(ftpAuthenticationVO);
if(ftpConnect.startFTP(CommonConstants.TEMP_TXT_FILE));
{
List<String> list = readSplitTextFiles.readTextFile(CommonConstants.TEMP_TXT_FILE);
(MainForm)parent.setJListModel(list);
}
Also parent must be declared as final.

Action Listener: sending a text input to an object in Java

I don't know how to send a text input to an object in Java, from a button pressed on an interface using the action Listener() method.
import javax.swing.*;
import java.awt.event.*;
public class Preassessment extends javax.swing.JFrame implements ActionListener {
static JTextField concept = new JTextField(15);
JButton enter = new JButton("Enter");
JLabel conceptLabel = new JLabel("Concept: ");
public Preassessment() {
super("Preassessment Sys");
setSize(350, 180);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(conceptLabel);
pane.add(concept);
pane.add(enter);
add(pane);
enter.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == enter){
conceptLabel.setText(concept.getText());
}
}
public static void main(String[] arguments) {
Preassessment preassess = new Preassessment();
Preassessment agInterface = new Preassessment(); //object to receive the text
}
}
Your question is not concrete enough. In any case you need a reference to the targetobject somewhere in your code, so one way to do it is:
public class Preassessment extends javax.swing.JFrame implements ActionListener {
static JTextField concept = new JTextField(15);
JButton enter = new JButton("Enter");
JLabel conceptLabel = new JLabel("Concept: ");
public Preassessment(ActionListener listener) {
super("Preassessment Sys");
setSize(350, 180);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(conceptLabel);
pane.add(concept);
pane.add(enter);
add(pane);
enter.addActionListener(listener);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == enter){
conceptLabel.setText(concept.getText());
}
}
public static void main(String[] arguments) {
Preassessment agInterface = new Preassessment(); //object to receive the text
Preassessment preassess = new Preassessment(agInterface);
}
}

How do I use Listener to pass a string to another class

Am am writing a simple browser, which has two classes, SimpleBrowser and MyTabbedPane.
SimpleBrowser has some Gui components such as JButton and TextField, while MyTabbedPane has tabbedpane which has JEditorPane.
I want to pass the Search string entered in SimpleBrowser JTextField into JEditorPane which is in MyTabbedPane
i don't how to use getter and setter
Here some of my code
package com.mysimplebrowser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class SimpleBrowser extends JFrame{
private JTextField myField;
private JButton myButton;
private JPanel myPanel;
private MyTabbedPane myTabbedPane;
public SimpleBrowser(){
setSize(400, 400);
myPanel = new JPanel(); // panel
myField = new JTextField();
myPanel.add(myField);
myButton = new JButton("Search");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// how do i go about here
}
});
myPanel.add(myButton);
// i have left out some code
add(myPanel);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
class MyTabbedPane extends JTabbedPane{
private String searchWord;
private JEditorPane myEditorPane;
public MyTabbedPane(){
// i have left some code out
myEditorPane = new JEditorPane();
// i have left out some code for the HTML kit
// i want later to add google Ajax api code or the depreciated
// google SOAP jar apis but am stuck on how to pass the String
// entered in the class SimpleBrowser JTextField into
// MyTabbedPane private String SearchWord
String myUrl = "http://localhost/Good" + searchWord + "html";
myEditorPane.setPage(myUrl); // left out some try ... catch code
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleBrowser().setVisible(true);
}
});
}
}
You are correct -- use getters and setters and you are also correct that you don't want SimpleBrowser's button's ActionListener creating a new MyTabbedPane object inside its actionPerformed since your program should only have one MyTabbedPane object. In my example below I called the "setter" method sendUrlText(...) since that's what it does (in my mind anyway). Passing information between classes is no different for Swing code as it is for non-GUI code:
class SimpleBrowser extends JFrame {
private JTextField myField;
private JButton myButton;
private JPanel myPanel;
private MyTabbedPane myTabbedPane = new MyTabbedPane(this);
public SimpleBrowser() {
setSize(400, 400); // should be setting preferredSize!
myPanel = new JPanel(); // panel
myField = new JTextField();
myPanel.add(myField);
myButton = new JButton("Search");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String urlText = myField.getText();
myTabbedPane.sendUrlText(urlText);
}
});
myPanel.add(myButton);
// i have left out some code
add(myPanel);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
class MyTabbedPane extends JTabbedPane {
private String searchWord;
private JEditorPane myEditorPane = new JEditorPane();
private SimpleBrowser simpleBrowser; // you'll need this later,
// if you separate these two classes -- which you should do.
public MyTabbedPane(SimpleBrowser simpleBrowser) {
this.simpleBrowser = simpleBrowser;
}
public void sendUrlText(String urlText) {
// TODO set editor pane's page here using urlText
try {
myEditorPane.setPage(urlText);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void createAndShowGui() {
SimpleBrowserTest mainPanel = new SimpleBrowserTest();
JFrame frame = new SimpleBrowser();
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Make two method inside your SimpleBrowserclass like
String searchText = new String();
public void setSearchText(String text)
{
searchText = text;
}
public String getSearchText()
{
return searchText;
}
And call this method from the actionPerformed(...), inside SimpleBrowser class, before making an object of MyTabbedPane class, like setSearchText(myField.getText()). And inside the constructor of the MyTabbedPane, the first line would be searchWord = getSearchText();

Categories

Resources