How to pass values from one JFrame to another JFrame? - java

I've created two JFrames.
The main JFrame contains the text area. My sub JFrame contains a drop down list.
The task is to pass the value that I've selected in the drop down list and display in the text area in the main JFrame.
Code in the sub JFrame:
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
close();
room=cmbRoom.getSelectedItem().toString();
}
Code in the main JFrame:
private void btnDisplayActionPerformed(java.awt.event.ActionEvent evt) {
roomNo r=new roomNo();
txtArea2.append("\nRoom Number: " + r.getroom());
}

class NextPage extends JFrame
{
NextPage(String st)
{
setLayout(null);
setDefaultCloseOperation(javax.swing. WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
JLabel lab=new JLabel("Welcome "+st);
lab.setBounds(10,10,500,20);
add(lab);
setSize(300, 100);
}
}

This might not be exactly correct answer but this will do the job.
Suppose you have 2 Jframes namely Home.java and Second.java
the code for Second.java as below,
public static String selection = "";//static variable to store seletced value from combobox
Home h = new Home();//instance of Home Jframe
/**
* return selected value (called from Home Jframe)
*/
public static String getSeletced() {
return selection;
}
/**
* get selected value from comboBox event
*/
private void cmbLapActionPerformed(java.awt.event.ActionEvent evt) {
selection = cmbLap.getSelectedItem().toString();
h.isSelected = true;//this is to control data duplication
}
Now for the Home.java file we can use formWindowGainedFocus event to update the jTextArea. Home .java file contains following code,
public static boolean isSelected = false;//flag to check combo box is selected
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
System.out.println(isSelected);
if (isSelected) {
String text = new Second().getSeletced();
System.out.println(text);
txaData.append("Your Laptop: " + text + "\n");//appending data
isSelected = false;//to prevent duplication
}
}
This method can use to update jTextArea using data from another jFrame.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class PassData extends JFrame
{
JTextField text;
PassData(){
JLabel l=new JLabel("Name: ");
text=new JTextField(20);
JButton b=new JButton("Send");
setLayout(null);
l.setBounds(10,10,100,20);
text.setBounds(120,10,150,20);
b.setBounds(120,40,80,20);
add(l);
add(text);
add(b);
setVisible(true);
setSize(300,100);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String value=text.getText();
NextPage page=new NextPage(value);
page.setVisible(true);
}
});
}
public static void main(String[] args)
{
new PassData();
}
}

Related

Java - get JRadioButton cmd with Jbutton listener

I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..
First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).
The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..
Here is my java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class englet{
static public JFrame f;
static public JPanel p;
static class getTypeOfLetter implements ActionListener{
public void actionPerformed( ActionEvent e){
String btnInput = e.getActionCommand();
System.out.println(btnInput);
}
}
public static void askletter(){
JRadioButton btnRadio1;
JRadioButton btnRadio2;
ButtonGroup btngrp;
JButton btnGo = new JButton("Write");
btnRadio1 = new JRadioButton("Write Letter For American Firm");
btnRadio1.setActionCommand("Amer");
btnRadio2 = new JRadioButton("Write Letter For British Firm");
btnRadio2.setActionCommand("Brit");
btngrp = new ButtonGroup();
btnGo.setActionCommand("WriteTest");
btnGo.addActionListener(new getTypeOfLetter());
btngrp.add(btnRadio1);
btngrp.add(btnRadio2);
p.add(btnRadio1);
p.add(btnRadio2);
p.add(btnGo);
}
englet(){
f = new JFrame("English Letter");
p = new JPanel();
askletter();
f.add(p);
f.setSize(400,200);
f.setVisible(true);
}
public static void main (String[] argv ){
englet i = new englet();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse.
**RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..
You've got several issues:
Over-use of static. Most of the fields and methods of your code should be non-static
You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.
You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).
If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GetRadio extends JPanel {
private static final String[] FIRMS = {"American Firm", "British Firm"};
// You need this field to access it in your listener
private ButtonGroup buttonGroup = new ButtonGroup();
public GetRadio() {
// create JButton and add ActionListener
JButton button = new JButton("Select");
button.addActionListener(new ButtonListener());
// JPanel with a grid layout with one column and variable number of rows
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
for (String firm : FIRMS) {
// create radiobutton and set actionCommand
JRadioButton radioButton = new JRadioButton(firm);
radioButton.setActionCommand(firm);
// add to button group and JPanel
buttonGroup.add(radioButton);;
radioButtonPanel.add(radioButton);
}
// add stuff to main JPanel
add(radioButtonPanel);
add(button);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get button model of selected radio button from ButtonGroup
ButtonModel model = buttonGroup.getSelection();
// if null, no country selected
if (model == null) {
Component component = GetRadio.this;
String message = "You must first select a country!";
String title = "Error: No Country Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(component, message, title, type);
} else {
// valid country selected
String country = model.getActionCommand();
System.out.println("Letter to " + country);
}
}
}
private static void createAndShowGui() {
GetRadio mainPanel = new GetRadio();
JFrame frame = new JFrame("Get Radio Btn");
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();
}
});
}
}

about ItemEvent in java GUI

I'm doing a small program with Java GUI
here is mu code:
// DebugFourteen3
// User selects pizza topping and sees price
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//use correct spelling of class name
public class DebugFourteen3 extends JFrame
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
itemStateChanged(this);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = list.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
the compiler gets me error on line 35, it says itemStateChanged() should receive a argument which type is ItemEvent[] but I'm passing "this"(the class it self)
can anyone explain how the itemStateChanged works with the JComboBox?
thanks
You have to add the listener on the combo box instead of calling the itemStateChanged method directly. Adding the listener will enable the callbacks when the click event happens, and jvm will call the itemStateChanged method automatically as combo box is registered for the event. Replace this line
itemStateChanged(this);
with
pizzaBox.addItemListener(this);
At first, you need to implements ItemListener with JFrame. Than add following line with pizzaBox, this will notify overrided public void itemStateChanged(ItemEvent ev) method ItemListener.
pizzaBox.addItemListener(this);
For details, see this tutorial.
Problem :
1.you are not registering itemListener for JComboBox
2.itemStateChanged event takes ItemEvent as argument not ItemEvent[] array
1.Replace this :
itemStateChanged(this);
with this:
pizzaBox.addItemListener(this);
2.Replace This:
public void itemStateChanged(ItemEvent[] list)
With this:
public void itemStateChanged(ItemEvent list)
Complete Code:
// DebugFourteen3
// User selects pizza topping and sees price
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//use correct spelling of class name
public class DebugFourteen3 extends JFrame
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
pizzaBox.addItemListener(this);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent list)
{
Object source = list.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
Here this i.e DebugFourteen3 is not a type ItemEvent. Thats why
itemStateChanged(ItemEvent[] list)
gives error.
If you want to handle itemStateChanged then you need to implement ItemLisntener and add actionListner to it as
pizzaBox.addItemListener(this);
also add Handler method of ItemLisntener as
public void itemStateChanged(....)
{
//Handling Code goes here
}
Or you can implement ActionListner also
For more information on how to use combobox you can visit here

How to parse and get String to Another Jframe - JAVA

I'm trying to parse String to another frame Using JAVA
i have 2 jFrames. jFrame1 have 1 text field and jFrame 2 have 1 text field. i want to parse jFrame1 text filed's text to jframe2's text field.
It's look like this : But this is not code :(
jFrame2.textfield1.setText(jFrame1.textfield1.gettext());
Anyone know how to parse String to another frame Using JAVA?
Thanks in advance!
Assuming that you have two separate GUIs on the screen at the same time because both textFields have the same reference, each JFrame will be a Object in its own right.
Therefore the only way to access another objects variables is with its methods.
Create a setter method in jFrame2 to change the textField in question.
See Working code below.
import java.awt.*;
import javax.swing.*;
import javax.swing.BoxLayout;
import java.awt.event.*;
public class JframeLink {
public static void main(String[] args)
{
new JframeOneGui();
new JframeTwoGui();
}
//JFrame one Object
public static class JframeOneGui extends JFrame implements ActionListener
{
JPanel jPanelOne = new JPanel();
JTextField textField1 = new JTextField("Message for transfer");
JButton buttonOne = new JButton("Transfer");
public JframeOneGui()
{
//setup swing components
textField1.setSize(100,10);
buttonOne.addActionListener(this);
//setup jPanelOne
jPanelOne.setLayout(new BoxLayout(jPanelOne, 1));
jPanelOne.add(textField1);
jPanelOne.add(buttonOne);
//setup JframeOneGui
this.add("Center",jPanelOne);
this.setLocation(25,25);
this.setTitle("JframeOneGui");
this.setSize(200,200);
this.setResizable(false);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonOne)
{
//Here we are calling JframeTwoGui's Setter method
JframeTwoGui.setTextFieldOne(textField1.getText());
}
}
}
//JFrame two Object
public static class JframeTwoGui extends JFrame
{
JPanel jPanelOne = new JPanel();
static JTextField textField1 = new JTextField();
public JframeTwoGui()
{
jPanelOne.setLayout(new BoxLayout(jPanelOne, 1));
jPanelOne.add(textField1);
this.add("Center",jPanelOne);
this.setLocation(300,25);
this.setTitle("JframeTwoGui");
this.setSize(200,200);
this.setResizable(false);
this.setVisible(true);
}
//Setter to change TextFieldOne in this Object
public static void setTextFieldOne(String text)
{
textField1.setText(text);
}
}
}

ActionListener for a specific text inside a JTextArea?

I have in my app a chat component which has a JTextArea on it.
Now, how can I add an ActionListener-like event for a specific text (like student://xxxx)?
So when I click on that text (student://xxxx) something will happen.
Thank you.
Here try this small program, try to click at the start of student://, that will pop up a message Dialog
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaExample extends JFrame
{
private JTextArea tarea = new JTextArea(10, 10);
private JTextField tfield = new JTextField(10);
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tarea.setText("Hello there\n");
tarea.append("Hello student://");
JScrollPane scroll = new JScrollPane(tarea);
tfield.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tarea.append(tfield.getText() + "\n");
}
});
tarea.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
int x = me.getX();
int y = me.getY();
System.out.println("X : " + x);
System.out.println("Y : " + y);
int startOffset = tarea.viewToModel(new Point(x, y));
System.out.println("Start Offset : " + startOffset);
String text = tarea.getText();
int searchLocation = text.indexOf("student://", startOffset);
System.out.println("Search Location : " + searchLocation);
if (searchLocation == startOffset)
JOptionPane.showMessageDialog(TextAreaExample.this, "BINGO you found me.");
}
});
getContentPane().add(scroll, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
pack();
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaExample().createAndDisplayGUI();
}
});
}
}
No, don't even consider this since ActionListeners are for JButtons or anything else derived from AbstractButton but not for JTextComponents (except for JTextFields). Perhaps you want a MouseListener.
Having said this, perhaps you'll be better off with two text components, a JTextArea to display all responses, including the user's, and right below this in a BorderLayout.SOUTH type of position, a JTextField to allow the user to enter text into the chat. Then give that JTextField an ActionListener (this is legal) so that "enter" will actuate the listener.
Edit 1
You state:
Well I have that jtextfield , the text in it is being sent to the server and server sends the message to all clients which appears in the JTextArea. But my problem is here: I want to popup a window when someone clicks on a student://id text .
Yeah, looking at your comments, my vote is for you to display the chats not in a JTextArea but rather in a JList, one with a SelectionListener. You can then respond easily to mouse click events, and will more easily get useful information from the "line" clicked on (if you fill the JList with smart objects). You will need to write a custom cell renderer that allows multiple lines of text to be displayed, probably one that shows a JTextArea, but the tutorial on JLists will get you started on this.
Is hitting ENTER instead of mouse-click ok?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StudentID extends JFrame implements ActionListener
{
private static final String progname = "StudentID 0.1";
private JTextField student;
private JTextArea feedback;
private JButton exit;
public StudentID ()
{
super (progname);
JPanel mainpanel = new JPanel ();
mainpanel.setLayout (new BorderLayout ());
this.getContentPane ().add (mainpanel);
student = new JTextField ("student://");
exit = new JButton ("exit");
student.addActionListener (this);
exit.addActionListener (this);
feedback = new JTextArea ();
mainpanel.add (student, BorderLayout.NORTH);
mainpanel.add (feedback, BorderLayout.CENTER);
mainpanel.add (exit, BorderLayout.SOUTH);
setSize (400, 400);
setLocation (100, 100);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
}
public void actionPerformed (final ActionEvent e)
{
SwingWorker worker = new SwingWorker ()
{
protected String doInBackground () throws InterruptedException
{
String cmd = e.getActionCommand ();
if (cmd.equals ("exit"))
{
System.exit (0);
}
else if (cmd.matches ("student://[0-9]+"))
{
feedback.setText ("student found: " + cmd.replaceAll ("student://([0-9]+)", "$1"));
}
else
{
feedback.setText ("cmd: " + cmd);
}
return "done";
}
protected void done ()
{
feedback.setText (feedback.getText () + "\ndone");
}
};
worker.execute ();
}
public static void main (final String args[])
{
Runnable runner = new Runnable ()
{
public void run ()
{
new StudentID ();
}
};
EventQueue.invokeLater (runner);
}
}

Java button do the same thing, how do I change this?

Alright, I have a simple java applet with two buttons and a screen. Both the buttons do the same thing. I want to change this. I can't find what it is that changes the action that is performed when either one of the buttons is pressed. They both to the same thing and I don't want this. So my question is how would I change the Inventory button to display "Hello world" instead of a line count?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class projectApplet extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private int lineNumber = 0; // this is just to test
public void init() {
JPanel panel = new JPanel();
textArea = new JTextArea();
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.WHITE);
JScrollPane sp = new JScrollPane(textArea);
panel.add(sp);
Container window = getContentPane();
window.setLayout(new BorderLayout());
window.add(sp,BorderLayout.CENTER);
// this is just to test------------------
JButton b = new JButton("Clik to add a line");
b.addActionListener(this);
window.add(b, BorderLayout.SOUTH);
JButton inventory = new JButton("Inventory");
inventory.addActionListener(this);
window.add(inventory, BorderLayout.NORTH);
//---------------------------------------
}
public void actionPerformed(ActionEvent arg0) {
lineNumber++;
textArea.append("\nLine number: " + lineNumber);
}
public void actionPerformed1(ActionEvent arg0) {
lineNumber++;
textArea.append("RPFL");
}
}
Add a new action listener to it. Typically you can use an anonymous inner class:
inventory.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
textArea.append("Hello, world");
}
});
Just have the one actionPerformed method and then find out which button triggered it.
For example:
public void actionPerformed(ActionEvent arg0) {
if(arg0.getLabel()=="Inventory") // Do the following
if(arg0.getLabel()=="Click to add a new line") // Do the following
}
Note, getLabel() method is deprecated so you'll have to use another... can't remember off the top of my head which you should though... maybe getName(). But this is a simple way to test which button was clicked ;)
You can't do arg0.getSOurce() inside the action performed method to checkout which button has generated this event.

Categories

Resources