this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!
//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Customer extends JFrame {
Function fun = new Function();
public static void main(String[]args){
Customer.setLookAndFeel();
Customer cust = new Customer();
}
public Customer(){
super("Resident Details");
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
setLayout(two);
JPanel row1 = new JPanel();
JLabel name = new JLabel("First Name",JLabel.LEFT);
JTextField nameEntry = new JTextField("",20);
row1.add(name);
row1.add(nameEntry);
add(row1);
JPanel row2 = new JPanel();
JLabel surname = new JLabel("Surname ",JLabel.LEFT);
JTextField surnameEntry = new JTextField("",20);
row2.add(surname);
row2.add(surnameEntry);
add(row2);
JPanel row3 = new JPanel();
JLabel contact1 = new JLabel("Contact Details : Email ",JLabel.LEFT);
JTextField contact1Entry = new JTextField("",10);
FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
setLayout(newflow);
row3.add(contact1);
row3.add(contact1Entry);
add(row3);
JPanel row4 = new JPanel();
JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
JTextField contact2Entry = new JTextField("",10);
row4.add(contact2);
row4.add(contact2Entry);
add(row4);
JPanel row5 = new JPanel();
JLabel time = new JLabel("Duration Of Stay ",JLabel.LEFT);
JTextField timeEntry = new JTextField("",10);
row5.add(time);
row5.add(timeEntry);
add(row5);
JPanel row6 = new JPanel();
JComboBox<String> type = new JComboBox<String>();
type.addItem("Type Of Room");
type.addItem("Single Room");
type.addItem("Double Room");
type.addItem("VIP Room");
row6.add(type);
add(row6);
JPanel row7 = new JPanel();
FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(amt);
JLabel amount = new JLabel("Amount Per Day ");
JTextField AmountField = new JTextField("\u20ac ",10);
row7.add(amount);
row7.add(AmountField);
add(row7);
JPanel row8 = new JPanel();
FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(prc);
JLabel price = new JLabel("Total Price ");
JTextField priceField = new JTextField("\u20ac ",10);
row8.add(price);
row8.add(priceField);
add(row8);
JPanel row9 = new JPanel();
JButton clear = new JButton("Clear");
row9.add(clear);
add(row9);
JPanel row10 = new JPanel();
JButton save = new JButton("Save");
save.addActionListener(fun);
row10.add(save);
add(row10);
//Adding ActionListners
nameEntry.addActionListener(fun);
clear.addActionListener(fun);
save.addActionListener(fun);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Function implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Add Customer")) {
Login();
}
else if(command.equals("Register")){
Registration();
}
else if(command.equals("Exit")){
System.exit(0);
}
else if(command.equals("Clear")){
ClearAllFields();
}
else if(command.equals("Save")){
SaveIt();
}
}
public static void Login(){
Customer cust = new Customer();
}
public static void Registration(){
//Do Nothing
}
//This clears all the text from the JTextFields
public static void ClearAllFields(){
}
//This will save Info on to another Class
public static void SaveIt(){
}
}
Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:
JTextField nameEntry = new JTextField("",20);
Function fun = new Function(nameEntry);
Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:
JTextField nameEntry;
public Function(JTextField nameEntry) {
this.nameEntry = nameEntry;
}
Now, the following will compile:
public void ClearAllFields(){
nameEntry.setText("");
}
And, the Clear button will clear the name field.
Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GUI extends JPanel {
private JTextField textField = new JTextField(10);
private JButton clearButton = new JButton("Clear");
public GUI() {
// pass **this** into the listener class
MyListener myListener = new MyListener(this);
clearButton.addActionListener(myListener);
clearButton.setMnemonic(KeyEvent.VK_C);
add(textField);
add(clearButton);
}
// public method in GUI that will do the dirty work
public void clearAll() {
textField.setText("");
}
// other public methods here to get text from the JTextFields
// to set text, and do whatever else needs to be done
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyListener implements ActionListener {
private GUI gui;
// use constructor parameter to set a field
public MyListener(GUI gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
gui.clearAll(); // call public method in field
}
}
A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.
Related
i can't getting updated text of JTextField from other class.
change text of JTextField ( from Names ) and go to Main tabbedPane and click button. updated text not appears on JOptionPane.
this is Frame.java
import java.awt.event.ActionEvent;
public class Frame {
JFrame frame;
JPanel pnl;
JButton btn;
JTabbedPane tabbedPane;
Names n;
public static void main(String[] args) {
Frame x = new Frame();
}
public Frame() {
SwingUtilities.invokeLater(()->Window());
}
public void Window() {
n = new Names();
frame = new JFrame();
tabbedPane = new JTabbedPane();
pnl = new JPanel();
btn = new JButton("get Name");
btn.addActionListener(e->JOptionPane.showMessageDialog(null, n.getName()));
pnl.add(btn);
tabbedPane.addTab("main", pnl);
tabbedPane.addTab("name", new Names());
frame.add(tabbedPane);
frame.setBounds(360, 130, 900, 550);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
this one is Names.java
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Names extends JPanel {
JTextField tf;
public Names() {
tf = new JTextField("test");
tf.setPreferredSize(new Dimension(150,30));
this.add(tf);
}
public String getName() {
return tf.getText();
}
}
thanks for efforts.
Just take a second and have a look at the following...
n = new Names();
//...
btn.addActionListener(e->JOptionPane.showMessageDialog(null, n.getName()));
//...
tabbedPane.addTab("name", new Names());
What do you think is going to happen here?
The instance of Names which the button is interacting with is NOT the instance of Names that the user is interacting with
Change it to...
n = new Names();
//...
btn.addActionListener(e->JOptionPane.showMessageDialog(null, n.getName()));
//...
tabbedPane.addTab("name", n);
On a side note, this...
tf.setPreferredSize(new Dimension(150,30));
is a really bad idea and will come back to haunt you. Instead make use of the setColumns method (or constructor) to set the number of displayed characters the text field should attempt to display
I keep receiving this error
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import java.awt.Container.*;
public class main extends JFrame implements ActionListener
{
JButton CustomerOrder;
JButton SoftwareProducts;
JButton BooksProducts;
JButton AddBooks;
JButton StaffMember;
JButton LoginView;
static ArrayList<Software> softwareList = new ArrayList<Software>();
CardLayout c1 = new CardLayout();
JPanel mainPanel;
SoftwareProducts addsoftware;
CustomerOrder customerorder;
BooksProducts addProduct;
AddBooks addBook;
SoftwareProducts sf = new SoftwareProducts();
//Press submit;
public static void main(String[] args)
{
new main();
JFrame frame = new JFrame("Selling Product");
frame.setLocationRelativeTo(null);
//frame.getContentPane().add(main, BorderLayout.CENTER);
//new CustomerOrder();
//EmailFrame email=new EmailFrame();
//CustomerOrder co = new CustomerOrder();
//LoginView login = new LoginView();
}
public main(){
super();
// getContentPane().setBackground(Color.green);
setSize(700,800);
setLayout(new FlowLayout());
/*CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "softwareProducts");
*/
//CustomerOrder co = new CustomerOrder();
//add(co);
SoftwareProducts = new JButton("SoftwareProducts");
SoftwareProducts.setSize(150,40);
SoftwareProducts.setLocation(20,50);
CustomerOrder = new JButton("CustomerOrder");
CustomerOrder.setSize(160,40);
CustomerOrder.setLocation(150,50);
BooksProducts = new JButton("BooksProducts");
BooksProducts.setSize(200,40);
BooksProducts.setLocation(310,50);
AddBooks = new JButton("AddBook");
AddBooks.setSize(200,40);
AddBooks.setLocation(310,50);
StaffMember = new JButton("StaffMember");
StaffMember.setSize(200,40);
StaffMember.setLocation(310,50);
LoginView = new JButton("LoginView");
LoginView.setSize(150,40);
LoginView.setLocation(20,50);
SoftwareProducts.addActionListener(this);
add(SoftwareProducts);
CustomerOrder.addActionListener(this);
add(CustomerOrder);
BooksProducts.addActionListener(this);
add(BooksProducts);
AddBooks.addActionListener(this);
add(AddBooks);
StaffMember.addActionListener(this);
add(StaffMember);
mainPanel = new JPanel();
mainPanel.setBackground(Color.BLUE);
mainPanel.setPreferredSize(new Dimension(600,500));
mainPanel.setLayout(c1);
addsoftware = new SoftwareProducts();
mainPanel.add(addsoftware,"addsoftware");
customerorder = new CustomerOrder(); ////// I am getting the error
from this part of code
mainPanel.add(customerorder,"customerorder");///// I am getting the
error from this part of code
addProduct = new BooksProducts();
mainPanel.add(addProduct,"addProduct");
addBook = new AddBooks();
mainPanel.add(addBook,"addBook");
/* mainPanel.add(SoftwareProducts);
mainPanel = new JPanel(new CardLayout());
mainPanel.add(SoftwareProducts);
getContentPane().add(mainPanel);
addProduct = new BooksProducts();
mainPanel.add(addProduct,"addProduct");
*/
add(mainPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == SoftwareProducts)
{
c1.show(mainPanel,"addsoftware");
this.setTitle("SoftwareProducts");
//System.out.println("Softwares");
}
if(e.getSource() == CustomerOrder)
{
c1.show(mainPanel,"customerorder");
this.setTitle("CustomerOrder");
//System.out.println("Custmers");
}
if(e.getSource() == BooksProducts)
{
c1.show(mainPanel,"addProduct");
this.setTitle("BooksProducts");
}
if(e.getSource() == AddBooks)
{
c1.show(mainPanel,"addBook");
this.setTitle("AddBooks");
}
if(e.getSource() == LoginView)
{
c1.show(mainPanel,"LogIN");
this.setTitle("LOGIN");
}
}
/* public void actionPerformed(ActionEvent e)
{
if(e.getSource() == press)
{
System.out.println("addProducts");
}
}*/
}
and my customerOrder class
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
import java.io.*;
public class CustomerOrder extends JFrame
implements ActionListener
{
//JButton asd = new JButton("BUTTON");
//JTextField productID;
//JTextField productName;
//JTextField productCost;
//JTextField productPYear;
//JTextField productPHouse;
JButton showOrder;
DefaultListModel<String> model = new DefaultListModel<>();
JList <String>orderList = new JList(model);
JTable softwareTabel = new JTable();
//DefaultTableModel tableModel = new DefaultTableModel(0, 1);
public CustomerOrder()
{
//super();
// JLabel toLabel=new JLabel("Product ID: ");
//JTextField to=new JTextField();
setLayout(new FlowLayout());
/*
productName = new JTextField(12);
add(productName);
productCost = new JTextField(12);
add(productCost);
productPYear = new JTextField(12);
add(productPYear);
productPHouse = new JTextField(12);
add(productPHouse);
*/
showOrder = new JButton("SHOW ORDER");
showOrder.setSize(25,40);
showOrder.addActionListener(this);
add(showOrder);
}
public void actionPerformed(ActionEvent e)
{
//Object[] colNames={"Product ID","Processor","RAm"};
if(e.getSource() == showOrder)
{
model.removeAllElements();
/* GridLayout exLayout = new GridLayout(3, 3);
JLabel ram,processor;
ram = new JLabel("RAM");
processor = new JLabel("Processor");
String softwaredata[] = {"ID","RAM","Processor","Product ID","Product Name","Product Year","Product Year","Product PublishHouse"};
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 3));
add(ram);
add(processor);
JTable table = new JTable();*/
//DeafultTableModel dm = new DeafultTableModel(0,0);
//String header[] = new String[] {"RAM", "Processor","ProductID","Product Name","Product Year","Product Publish House"};
//dm.setColumnIdentifiers(header);
//Object[][] software = new Object[8][3];
//model.addRow(orderList.toArray());
int x = 0;
while (x < main.softwareList.size())
{
//./model.addElement(main.softwareList.get(x).getproductYear());
model.addElement(""+main.softwareList.get(x).getproductID());
model.addElement(""+main.softwareList.get(x).getRam());
model.addElement(""+ main.softwareList.get(x).getProcessor());
model.addElement(""+ main.softwareList.get(x).getproductID());
model.addElement(main.softwareList.get(x).getproductName());
model.addElement(""+ main.softwareList.get(x).getproductYear());
model.addElement(main.softwareList.get(x).getproductPublishHouse());
//model.addElement(main.softwareList.get(x).getproductID());*/
x++;
//System.out.println("as");
}
/* ArrayList<String> table1 = new ArrayList();
ArrayList<ArrayList<String>> table2 = new ArrayList();
table1.add("Product ID");
table1.add("RAM");
table1.add("Processor");
table1.add("Product Name");
table1.add("Product Year");
table1.add("Product PHouse");
Object[] software = table1.toArray();
String[] [] softwarest = new String[table1.size()][];
int i = 0;
for (List<String> next : table2){
softwarest[i++] = next.toArray(new String[next.size()]);
}
JTable newTable = new JTable(softwarest,software);
JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(newTable));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
*/
//table.add(model);
// add(orderList);
//Object[] column = {"RAM:", "Processor:"};
//Object[][] data = {{"RAM:", "Processor:"}};
//JTable table = new JTable();
//table.setShowGrid(false);
//table.setTableHeader(null);
}
}
}
When i run this code i get the following exception from the main class in customerorder = new CustomerOrder;
mainPanel.add(customerorder,"customerorder")
customorder is an instance of CustomerOrder, which extends from JFrame; public class CustomerOrder extends JFrame
As the error states illegalargumentexception adding a window to a container; it is illegal to add a window to another window, it simply doesn't make sense.
This is one of the reasons we discourage extending from top level containers like JFrame directly.
Either make the CustomerOrder visible like any normal frame (although that might lead you into other issues) or better yet, base your CustomerOrder component of a JPanel
public class CustomerOrder extends JPanel {
//...
}
This way you can add it to what ever container you need to.
Idk if this logic is correct, but in just playing around to try and figure out the reason it doesn't make sense for myself I concluded that:
extending JFrame causes only one object to be created and why it tries to add the JFrame frame; object to itself which causes the exception...
extending JPanel allows the JFrame frame; <-- object to divide into a Container & a Component which allows you to
frame.add(this) ..
frame.add(this) is the component invoked by JPanel method .add()
if this is wrong plz correct..
I'm new to programming with Java.
I have these two small projects.
import javax.swing.*;
public class tutorial {
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("hello");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(label);
JButton button = new JButton("Hello again");
panel.add(button);
}
}
and this one:
import java.util.*;
public class Test {
public static void main(String[] args){
int age;
Scanner keyboard = new Scanner(System.in);
System.out.println("How old are you?");
age = keyboard.nextInt();
if (age<18)
{
System.out.println("Hi youngster!");
}
else
{
System.out.println("Hello mature!");
}
}
}
How can I add the second code to the first one, so that the user will see a window that says 'How old are you' and they can type their age.
Thanks in advance!
I'm not sure of all the things you wanted because it was undefined, but as I far as I understand, you wanted a JFrame containing an input field, in which you will be able to input values and display the appropriate answer.
I also suggest you read tutorial , but don't hesitate if you have question.
I hope it's a bit close to what you wanted.
package example.tutorial;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Tutorial extends JPanel {
private static final String YOUNG_RESPONSE = "Hi youngster!";
private static final String ADULT_RESPONSE = "Hello mature!";
private static final String INVALID_AGE = "Invalid age!";
private static final int MIN_AGE = 0;
private static final int MAX_AGE = 100;
private static JTextField ageField;
private static JLabel res;
private Tutorial() {
setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
JLabel label = new JLabel("How old are you ? ");
northPanel.add(label);
ageField = new JTextField(15);
northPanel.add(ageField);
add(northPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
JButton btn = new JButton("Hello again");
btn.addActionListener(new BtnListener());
centerPanel.add(btn);
res = new JLabel();
res.setVisible(false);
centerPanel.add(res);
add(centerPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.add(new Tutorial());
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String content = ageField.getText();
int age = -1;
try{
age = Integer.parseInt(content);
if(isValid(age)) {
res.setText(age < 18 ? YOUNG_RESPONSE : ADULT_RESPONSE);
} else {
res.setText(INVALID_AGE);
}
if(!res.isVisible())
res.setVisible(true);
} catch(NumberFormatException ex) {
res.setText("Wrong input");
}
}
private boolean isValid(int age) {
return age > MIN_AGE && age < MAX_AGE;
}
}
}
so that the user will see a window that says 'How old are you' and they can type their age.
The easiest way to start would be to use a JOptionPane. Check out the section from the Swing tutorial on How to Use Dialogs for examples and explanation.
Don't forget to look at the table of contents for other Swing related topics for basic information about Swing.
You will need an input field to get the text and then add an ActionListener to the button which contains the logic that is performed when the button is pressed.
I modified your code to implement what you described:
import javax.swing.*;
import java.awt.event.*;
public class tutorial {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("hello");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(label);
final JTextField input = new JTextField(5); // The input field with a width of 5 columns
panel.add(input);
JButton button = new JButton("Hello again");
panel.add(button);
final JLabel output = new JLabel(); // A label for your output
panel.add(output);
button.addActionListener(new ActionListener() { // The action listener which notices when the button is pressed
public void actionPerformed(ActionEvent e) {
String inputText = input.getText();
int age = Integer.parseInt(inputText);
if (age < 18) {
output.setText("Hi youngster!");
} else {
output.setText("Hello mature!");
}
}
});
}
}
In that example we don't validate the input. So if the input is not an Integer Integer.parseInt will throw an exception. Also the components are not arranged nicely. But to keep it simple for the start that should do it. :)
it's not an easy question since you are working on command line in one example, and in a Swing GUI in the other.
Here's a working example, i've commented here and there.
This is no where near java best practises and it misses a lot of validation (just see what happens when you enter a few letters or nothing in the textfield.
Also please ignore the setLayout(null) and setBounds() statements, it's just a simple example not using any layout managers.
I hope my comments will help you discovering java!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//You'll need to implement the ActionListener to listen to buttonclicks
public class Age implements ActionListener{
//Declare class variables so you can use them in different functions
JLabel label;
JTextField textfield;
//Don't do al your code in the static main function, instead create an instance
public static void main(String[] args){
new Age();
}
// this constructor is called when you create a new Age(); like in the main function above.
public Age()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0,0,300,300);
panel.setLayout(null);
label = new JLabel("hello");
label.setBounds(5,5,100,20);
// a JTextfield allows the user to edit the text in the field.
textfield = new JTextField();
textfield.setBounds(5,30,100,20);
JButton button = new JButton("Hello again");
button.setBounds(130,30,100,20);
// Add this instance as the actionlistener, when the button is clicked, function actionPerformed will be called.
button.addActionListener(this);
panel.add(label);
panel.add(textfield);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
//Required function actionPerformed for ActionListener. When the button is clicked, this function is called.
#Override
public void actionPerformed(ActionEvent e)
{
// get the text from the input.
String text = textfield.getText();
// parse the integer value from the string (! needs validation for wrong inputs !)
int age = Integer.parseInt(text);
if (age<18)
{
//instead of writing out, update the text of the label.
label.setText("Hi youngster!");
}
else
{
label.setText("Hello mature!");
}
}
}
I am working on my HOMEWORK (please don't do my work for me). I have 95% of it completed already. I am having trouble with this last bit though. I need to display the selected gender in the JTextArea. I must use the JRadioButton for gender selection.
I understand that JRadioButtons work different. I set up the action listener and the Mnemonic. I think I am messing up here. It would seem that I might need to use the entire group to set and action lister maybe.
Any help is greatly appreciated.
Here is what I have for my code (minus parts that I don't think are needed so others can't copy paste schoolwork):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
public class LuisRamosHW3 extends JFrame {
private JLabel WelcomeMessage;
private JRadioButton jrbMale = new JRadioButton("Male");
private JRadioButton jrbFemale = new JRadioButton("Female");
public LuisRamosHW3(){
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbMale);
jpRadioButtons.add(jrbFemale);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);
ButtonGroup gender = new ButtonGroup();
gender.add(jrbMale);
jrbMale.setMnemonic(KeyEvent.VK_B);
jrbMale.setActionCommand("Male");
gender.add(jrbFemale);
jrbFemale.setMnemonic(KeyEvent.VK_B);
jrbFemale.setActionCommand("Female");
//Set defaulted selection to "male"
jrbMale.setSelected(true);
//Create Welcome button
JButton Welcome = new JButton("Submit");
add(Welcome);
Welcome.addActionListener(new SubmitListener());
WelcomeMessage = (new JLabel(" "));
add(WelcomeMessage);
}
class SubmitListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
String FirstName = jtfFirstName.getText();
String FamName = jtfLastName.getText();
Object StateBirth = jcbStates.getSelectedItem();
String Gender = gender.getActionCommand(); /*I have tried different
variations the best I do is get one selection to print to the text area*/
WelcomeMessage.setText("Welcome, " + FirstName + " " + FamName + " a "
+ gender.getActionCommmand + " born in " + StateBirth);
}
}
} /*Same thing with the printing, I have tried different combinations and just can't seem to figure it out*/
I have done a similar kind of a problem on JTable where we get the selection from the radio group and then act accordingly. Thought of sharing the solution.
Here, I have grouped the radio buttons using the action listener and each radio button will have an action command associated with it. When the user clicks on a radio button then an action will be fired subsequently an event is generated where we deselect other radio button selection and refresh the text area with the new selection.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class RadioBtnToTextArea {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new RadioBtnToTextArea().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JPanel radioPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel textPnl = new JPanel();
JRadioButton radioMale = new JRadioButton();
JRadioButton radioFemale = new JRadioButton();
JTextArea textArea = new JTextArea(10, 30);
ActionListener listener = new RadioBtnAction(radioMale, radioFemale, textArea);
radioPnl.add(new JLabel("Male"));
radioPnl.add(radioMale);
radioMale.addActionListener(listener);
radioMale.setActionCommand("1");
radioPnl.add(new JLabel("Female"));
radioPnl.add(radioFemale);
radioFemale.addActionListener(listener);
radioFemale.setActionCommand("2");
textPnl.add(textArea);
panel.add(radioPnl, BorderLayout.NORTH);
panel.add(textPnl, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class RadioBtnAction implements ActionListener {
JRadioButton maleBtn;
JRadioButton femaleBtn;
JTextArea textArea;
public RadioBtnAction(JRadioButton maleBtn,
JRadioButton femaleBtn,
JTextArea textArea) {
this.maleBtn = maleBtn;
this.femaleBtn = femaleBtn;
this.textArea = textArea;
}
#Override
public void actionPerformed(ActionEvent e) {
int actionCode = Integer.parseInt(e.getActionCommand());
switch (actionCode) {
case 1:
maleBtn.setSelected(true);
femaleBtn.setSelected(false);
textArea.setText("Male");
break;
case 2:
maleBtn.setSelected(false);
femaleBtn.setSelected(true);
textArea.setText("Female");
break;
default:
break;
}
}
}
Suggestions:
Make your ButtonGroup variable, gender, a field (declared in the class) and don't declare it in the constructor which will limit its scope to the constructor only. It must be visible throughout the class.
Make sure that you give your JRadioButton's actionCommands. JRadioButtons are not like JButtons in that if you pass a String into their constructor, this does not automatically set the JRadioButton's text, so you will have to do this yourself in your code.
You must first get the selected ButtonModel from the ButtonGroup object via getSelection()
Then check that the selected model is not null before getting its actionCommand text.
For example
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class RadioButtonEg extends JPanel {
public static final String[] RADIO_TEXTS = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
// *** again declare this in the class.
private ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textfield = new JTextField(20);
public RadioButtonEg() {
textfield.setFocusable(false);
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
for (String radioText : RADIO_TEXTS) {
JRadioButton radioButton = new JRadioButton(radioText);
radioButton.setActionCommand(radioText); // **** don't forget this
buttonGroup.add(radioButton);
radioButtonPanel.add(radioButton);
}
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ButtonAction("Press Me", KeyEvent.VK_P)));
setLayout(new BorderLayout());
add(radioButtonPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
add(textfield, BorderLayout.PAGE_START);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
textfield.setText("No radio button has been selected");
} else {
textfield.setText("Selection: " + model.getActionCommand());
}
}
}
private static void createAndShowGui() {
RadioButtonEg mainPanel = new RadioButtonEg();
JFrame frame = new JFrame("RadioButtonEg");
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();
}
});
}
}
Here is my 1st frame - I want went I input text in textfield example name then click button report will display output to 2nd frame using textArea... please help me
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Order extends JFrame implements ActionListener
{
private JPanel pInfo,pN, pIC, pDate,Blank,pBlank, button, pTotal;
private JLabel nameL,icL,DateL;
private JTextField nameTF, icTF;
private JFormattedTextField DateTF;
private JButton calB,clearB,exitB,reportB;
public Order()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.setBackground(Color.gray);
pInfo = new JPanel();
pN = new JPanel();
pIC = new JPanel();
pDate = new JPanel();
nameTF = new JTextField(30);
icTF = new JTextField(30);
DateTF = new JFormattedTextField(
java.util.Calendar.getInstance().getTime());
DateTF.setEditable (false);
DateTF.addActionListener(this);
nameL = new JLabel(" NAME : ",SwingConstants.RIGHT);
icL = new JLabel(" IC : ",SwingConstants.RIGHT);
DateL = new JLabel(" DATE :",SwingConstants.RIGHT);
pInfo.setLayout(new GridLayout(10,2,5,5));
pInfo.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),"ORDER"));
pN.add(nameL);
pN.add(nameTF);
pIC.add(icL);
pIC.add(icTF);
pDate.add(DateL);
pDate.add(DateTF);
pInfo.add(pN);
pInfo.add(pIC);
pInfo.add(pDate);
pInfo.setBackground(Color.GRAY);
pN.setBackground(Color.gray);
pIC.setBackground(Color.gray);
pDate.setBackground(Color.gray);
nameL.setForeground(Color.black);
icL.setForeground(Color.black);
DateL.setForeground(Color.black);
nameTF.setBackground(Color.pink);
icTF.setBackground(Color.pink);
DateTF.setBackground(Color.pink);
contentPane.add(pInfo,BorderLayout.CENTER);
Blank = new JPanel();
pBlank = new JPanel();
button = new JPanel();
calB = new JButton("CALCULATE");
calB.setToolTipText("Click to calculate");
clearB = new JButton("RESET");
clearB.setToolTipText("Click to clear");
reportB = new JButton ("REPORT");
reportB.setToolTipText ("Click to print");
exitB = new JButton("EXIT");
exitB.setToolTipText("Click to exit");
Blank.setLayout(new GridLayout(2,2));
Blank.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),""));
button.setLayout(new GridLayout(1,4));
button.add(calB,BorderLayout.WEST);
button.add(clearB,BorderLayout.CENTER);
button.add(reportB,BorderLayout.CENTER);
button.add(exitB,BorderLayout.EAST);
Blank.add(pBlank);
Blank.add(button);
contentPane.add(Blank,BorderLayout.SOUTH);
Blank.setBackground(Color.gray);
pBlank.setBackground(Color.gray);
calB.setForeground(Color.black);
clearB.setForeground(Color.black);
reportB.setForeground(Color.black);
exitB.setForeground(Color.black);
calB.setBackground(Color.pink);
clearB.setBackground(Color.pink);
reportB.setBackground(Color.pink);
exitB.setBackground(Color.pink);
calB.addActionListener(this);
clearB.addActionListener(this);
reportB.addActionListener(this);
exitB.addActionListener(this);
}
public void actionPerformed(ActionEvent p)
{
if (p.getSource() == calB)
{
}
else if (p.getSource() == clearB)
{
}
else if (p.getSource () == reportB)
{
}
else if (p.getSource() == exitB)
{
}
}
public static void main (String [] args)
{
Order frame = new Order();
frame.setTitle("Order");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);//center the frame
}
}
If you only have one String to pass, add it to the constructor of your second JFrame:
public class SecondFrame extends JFrame {
public SecondFrame(String someValueFromFirstFrame) {
someTextField.setText(someValueFromFirstFrame);
}
}
and pass it when creating the second JFrame:
SecondFrame secondFrame = new SecondFrame(firstTextField.getText());
If there is more than one attribute to pass, consider putting them together in another class and pass the instance of this class. This saves you from changing the constructor every time you need to pass an additional variable.
Simply add some reference to the first frame in the second or pass the value you're interested in to the second frame before you display it.
As for the code example you requested:
public class SecondFrame extends JFrame {
private JFrame firstFrame;
public SecondFrame(JFrame firstFrame) {
this.firstFrame = firstFrame;
}
}
Now you can obtain everything there is to obtained from the firstFrame through the internal reference to it.