JLable not change after change the TextFiled and also the combox - java

Hi I'm doing a program that firstly opens setting menu like in the picture
enter image description here
first I select the choices of the game I want from the jcombox and jdialog that open window to set the names .
this is the code of it :
public class SettingMenu extends JFrame {
boolean is3players = false, is4players = false;
BufferedImage settingImage;
String[] playersChoises = { "2", "3", "4" };
String[] sizeChoises = { "30", "50", "100" };
JComboBox comboBoxPlayers;
JComboBox comboBoxSizes;
static JButton startGame, writeNames;
public SettingMenu() {
JLabel howManyPlayersText = new JLabel("How many players ?");
comboBoxPlayers = new JComboBox(playersChoises);
if (comboBoxPlayers.getSelectedItem().equals("3")) {
is3players = true;
}
if (comboBoxPlayers.getSelectedItem().equals("4")) {
is3players = true;
is4players = true;
}
JLabel writeNamesText = new JLabel("Set names of playes");
writeNames = new JButton("set names");
JLabel sizeOfBoredText = new JLabel("What the size of the bored ?");
comboBoxSizes = new JComboBox(sizeChoises);
startGame = new JButton("Click to start the game!");
howManyPlayersText.setBounds(177, 200, 270, 100);
comboBoxPlayers.setBounds(230, 270, 100, 30);
writeNamesText.setBounds(230, 210, 380, 250);
writeNames.setBounds(240, 350, 100, 36);
sizeOfBoredText.setBounds(177, 376, 300, 100);
comboBoxSizes.setBounds(230, 450, 100, 30);
startGame.setBounds(200, 500, 200, 44);
add(howManyPlayersText);
add(comboBoxPlayers);
add(writeNamesText);
add(writeNames);
add(sizeOfBoredText);
add(comboBoxSizes);
add(startGame);
setVisible(true);
}
public static void main(String[] args) {
// open this class
new SettingMenu();
// when i click on startgame bottun open the class of the game
startGame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new LeadersAndSnake_Project201();
}
});
// when i click on writeNames bottun open the class of dialog
writeNames.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new SetNames();
}
});
}
}
and this is Set Names class which open the set names window
enter image description here
class SetNames extends JDialog {
public JTextField setNamePlayer1, setNamePlayer2, setNamePlayer3, setNamePlayer4;
public SetNames() {
this.setSize(280, 151);
this.setLocationRelativeTo(null);
JLabel name1 = new JLabel("Set Player's 1 name : ");
setNamePlayer1 = new JTextField(7);
setNamePlayer1.setText("Player 1");
JLabel name2 = new JLabel("Set Player's 2 name : ");
setNamePlayer2 = new JTextField(7);
setNamePlayer2.setText("Player 2");
JPanel panelOfDialog_1 = new JPanel();
panelOfDialog_1.add(name1);
panelOfDialog_1.add(setNamePlayer1);
JPanel panelOfDialog_2 = new JPanel();
panelOfDialog_2.add(name2);
panelOfDialog_2.add(setNamePlayer2);
JPanel panelOfDialog_3 = new JPanel();
JButton okBotton = new JButton("OK");
add(okBotton);
okBotton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setNamePlayer1 = new JTextField(setNamePlayer1.getText());
setNamePlayer2 = new JTextField(setNamePlayer2.getText());
setVisible(false);
}
});
panelOfDialog_3.add(okBotton);
add(panelOfDialog_1, BorderLayout.NORTH);
add(panelOfDialog_2, BorderLayout.CENTER);
add(panelOfDialog_3, BorderLayout.AFTER_LAST_LINE);
this.setVisible(true);
}
}
and this is the large class for the game but I just put the imprtant thinga here :
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Setting Menu class for use the varible that it has
SettingMenu obj1 = new SettingMenu();
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
// -----------------left panel------------------------------
JPanel leftPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(leftPanel);
leftPanel.setLayout(groupLayout);
//---------------------------panel 1 for information player 1 -------------------------------------
JPanel panel1 = new JPanel();
ImageIcon imageMan1 = new ImageIcon("man1.png");
JLabel imageMan11 = new JLabel("", imageMan1, JLabel.CENTER);
JLabel player1text = new JLabel(obj2.setNamePlayer1.getText());
panel1.add(imageMan11);
panel1.add(player1text);
//---------------------------panel 2 for information player 2------------------------------------
JPanel panel2 = new JPanel();
ImageIcon imageMan2 = new ImageIcon("man2.png");
JLabel imageMan22 = new JLabel("", imageMan2, JLabel.CENTER);
JLabel player2text = new JLabel(obj2.setNamePlayer2.getText());
panel2.add(imageMan22);
panel2.add(player2text);
//---------------------------panel 3 for information player 3-------------------------------------
JPanel panel3 = new JPanel();
if(obj.is3 == true){
ImageIcon imageMan3 = new ImageIcon("man3.png");
JLabel imageMan33 = new JLabel("", imageMan3, JLabel.CENTER);
JLabel player3text = new JLabel("Player 3");
player2text.setFont(fontText);
panel3.add(imageMan33);
panel3.add(player3text);
}
}
}
Here on left panel are my problems
the jlable of player 1 and player 2 didn't chang even if I try to change them in the textfiled and the second problem is that the panel of player 3 didn't apper even if I select the chois "3" from the combox .
enter image description here

Try to call .pack() on the Frame after altering the elements.
EDIT
You have no code changing the labels. What you need is store the labels in a variable, like you did with other components, and in the ActionListener on on the okButton in SetNames(), instead of doing whatever you do to the TextFields there (which looks wrong), update the Label text.
So, for example
class SetNames extends JDialog {
[...]
public JButton okButton; // save okButton so others can add listeners
}
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
[...]
obj2.okButton.addActionListener(new ActionListener(){/*update labels*/});
}}

Related

Button not displaying frame connected to it

I am trying to write code for an application I'm making, I have my main frame with 6 buttons on them. When I push one of my buttons, it is meant to bring up a frame that has a tabbed layout set up.
I have the tabbed frame coded correctly and when I set each frame as visible they will appear to screen but they don't appear when the button is pushed.
I have action listeners connected to the buttons and the frames I want to connect with them as well as constructors but for some reason I can't get my code to work correctly.
I have added my driver and my first two forms I'm trying to connect to each other.
public class SimpsonsDriver {
//#param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame simpsonFrame = new JFrame("The Simpson");
JFrame homerFrame = new JFrame ("Homer Simpson");
JFrame margeFrame = new JFrame ("Marge Simpson");
JFrame bartFrame = new JFrame ("Bart Simpson");
JFrame lisaFrame = new JFrame("Lisa Simpson");
JFrame maggieFrame = new JFrame("Maggie Simpson");
SimpsonForm simpsonForm = new SimpsonForm(simpsonFrame, homerFrame, margeFrame, bartFrame,
lisaFrame, maggieFrame);
HomerForm homerForm = new HomerForm(homerFrame, simpsonFrame);
MargeForm margeForm = new MargeForm(margeFrame, simpsonFrame);
BartForm bartForm = new BartForm(bartFrame, simpsonFrame);
LisaForm lisaForm = new LisaForm(lisaFrame, simpsonFrame);
MaggieForm maggieForm = new MaggieForm(maggieFrame, simpsonFrame);
}
}
public class SimpsonForm implements ActionListener{
JFrame simpsonFrame, homerFrame, margeFrame, bartFrame, lisaFrame, maggieFrame;//instance variables
JButton homerBtn, margeBtn, bartBtn, lisaBtn, maggieBtn, closeBtn; //instance variables
public SimpsonForm(JFrame simpsonFrame, JFrame homerFrame, JFrame margeFrame, JFrame bartFrame, JFrame lisaFrame, JFrame maggieFrame) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
this.margeFrame = margeFrame;
this.bartFrame = bartFrame;
this.lisaFrame = lisaFrame;
this.maggieFrame = maggieFrame;
simpsonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanel();
}//end constructor method SimpsonForm
private void createPanel(){
homerBtn = new JButton ("Homer");
margeBtn = new JButton ("Marge");
bartBtn = new JButton ("Bart");
lisaBtn = new JButton ("Lisa");
maggieBtn = new JButton ("Maggie");
closeBtn = new JButton ("Close");
FlowLayout flow = new FlowLayout();
JPanel p1 = new JPanel();
p1.setLayout(flow);
JPanel p2 = new JPanel();
p2.setLayout(flow);
ImageIcon img = new ImageIcon(this.getClass().getResource("simpsons.png"));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(img);
imgLabel.setBounds(10, 10, img.getIconWidth(), img.getIconHeight());
p1.add(imgLabel);
p2.add(homerBtn);
homerBtn.addActionListener(this);
p2.add(margeBtn);
margeBtn.addActionListener(this);
p2.add(bartBtn);
bartBtn.addActionListener(this);
p2.add(lisaBtn);
lisaBtn.addActionListener(this);
p2.add(maggieBtn);
maggieBtn.addActionListener(this);
p2.add(closeBtn);
closeBtn.addActionListener(this);
simpsonFrame.setLayout(new BorderLayout());
simpsonFrame.setResizable(false);
simpsonFrame.add(p1, BorderLayout.BEFORE_FIRST_LINE);
simpsonFrame.add(p2, BorderLayout.CENTER);
simpsonFrame.setSize(425, 425);
simpsonFrame.setLocationRelativeTo(null);
simpsonFrame.setVisible(true);
}//end method createPanel
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == homerBtn) {
homerFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == margeBtn) {
margeFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == bartBtn) {
bartFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == lisaBtn) {
lisaFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == maggieBtn) {
maggieFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == closeBtn) {
System.exit(0);
}//end if
}//end event handler
}
public class HomerForm implements ActionListener{
JFrame simpsonFrame, homerFrame;
JButton closeBtn;
public HomerForm(JFrame simpsonFrame, JFrame homerFrame ) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
createPanel();
}
private void createPanel() {
homerFrame = new JFrame("Homer Simpson");
closeBtn = new JButton("Close");
closeBtn.setSize(200, 50);
ImageIcon ogImage = new ImageIcon(this.getClass().getResource("/homer1.png"));
JLabel ogLabel = new JLabel();
ogLabel.setIcon(ogImage);
JPanel p1 = new JPanel();
p1.add(ogLabel);
ImageIcon hwImage = new ImageIcon(this.getClass().getResource("/homer2.png"));
JLabel hwLabel = new JLabel();
hwLabel.setIcon(hwImage);
JPanel p2 = new JPanel();
p2.add(hwLabel);
ImageIcon cImage = new ImageIcon(this.getClass().getResource("/homer3.png"));
JLabel cLabel = new JLabel();
cLabel.setIcon(cImage);
JPanel p3 = new JPanel();
p3.add(cLabel);
JPanel p4 = new JPanel();
JTabbedPane tab = new JTabbedPane();
tab.setBounds(100, 100, 300, 300);
tab.add("Original", p1);
tab.add("HalfWay", p2);
tab.add("Current", p3);
tab.add("Close", p4);
p4.add(closeBtn);
closeBtn.setLayout(new BorderLayout());
closeBtn.addActionListener(this);
homerFrame.add(tab);
homerFrame.setResizable(false);
homerFrame.setSize(500, 500);
homerFrame.setLocationRelativeTo(null);
homerFrame.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == closeBtn) {
homerFrame.setVisible(false);
simpsonFrame.setVisible(true);
}//end if
else
{
System.exit(0);
}
}
}
When i run it, i get this image. simpsonsFrame
this is what happens when i click the homer button i then have to max it to see a blank screen.homerFrame.
when i set the homerFrame to visible, it displays what i what to appear if the button was pushed.it shows homerFrame then it shows the simpsonFrame.homersetVisible true

Eventhandling and how to use itemListener for multiple items

So I have 2 questions, the following classes regarding the questions I will ask are supplemented below:
1) If I have multiple JCheckBoxes, how can I use an itemListener to know when a specific JCheckBox is selected.
(In the example below, I have 3 JCheckBoxes named petrol, Electric & diesel, if petrol is chosen how can I be aware of this, I want to do something like, if petrol is selected then remove some items from the JComboBox)
2) How can I make the progress bar increase or decrease when a JButton is clicked. In the code below I have a JProgressBar, when the user clicks drive I want the JProgressBar to decrease and when they select refuel I want the JProgressBar to increase. I sort of want the JProgressBar to represent the fuel Level of the car. How would I go about doing this?
Class 1
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class CarViewer extends JFrame{
//row1
JPanel row1 = new JPanel();
JButton drv = new JButton("Drive");
JButton park = new JButton("Park");
JButton refuel = new JButton("Refuel");
//row2
JPanel row2 = new JPanel();
JLabel carTypeTag = new JLabel("Car Model:", JLabel.RIGHT);
JComboBox<String> options = new JComboBox<String>();
JCheckBox petrol = new JCheckBox("Petrol");
JCheckBox Electric = new JCheckBox("Electric");
JCheckBox diesel = new JCheckBox("Diesel");
JLabel fuelTypeTag = new JLabel("Fuel Type: ", JLabel.RIGHT);
ButtonGroup groupFuelType = new ButtonGroup();
//row3
JPanel row3 = new JPanel();
JLabel costTag = new JLabel("Cost:", JLabel.RIGHT);
JTextField costField = new JTextField(10);
JLabel engTag = new JLabel("Engine Size: ", JLabel.RIGHT);
JTextField engField = new JTextField(5);
JLabel mileageTag = new JLabel("Mileage: ", JLabel.RIGHT);
JTextField mField = new JTextField(10);
JLabel tankSizeTag = new JLabel("Tank size: ", JLabel.RIGHT);
JTextField tSField = new JTextField(5);
//row4
JPanel row4 = new JPanel();
JProgressBar petTank = new JProgressBar();
//row5
JPanel row5 = new JPanel();
JButton reset = new JButton("Reset");
public CarViewer(){
super("Analyse A Car - AAC");
setSize(400,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layoutMaster = new GridLayout(6, 1, 10, 20);
setLayout(layoutMaster);
////Initial Errands
groupFuelType.add(petrol);
groupFuelType.add(diesel);
groupFuelType.add(Electric);
Dimension buttonDimension = new Dimension(80,30);
Dimension resetButtonX = new Dimension(150,100);
drv.setPreferredSize(buttonDimension);
park.setPreferredSize(buttonDimension);
refuel.setPreferredSize(buttonDimension);
petTank.setMinimum(0);
petTank.setMaximum(100);
///Adding Car Models to Dropdown (JComboBox)
options.addItem("Mercedes C63 AMG");
options.addItem("BMW i7");
options.addItem("Jaguar XFR");
options.addItem("Nissan Skyline R35 GTR 4");
EmptyBorder empty0 = new EmptyBorder(60, 0, 440, 0); //empty Border;
EmptyBorder empty2 = new EmptyBorder(50,40,0,120); //empty Border row 3;
EmptyBorder empty4 = new EmptyBorder(80,0,0,0);
//Errands Complete
CarEvent handler = new CarEvent();
//Adding Listeners
drv.addActionListener(handler);
park.addActionListener(handler);
refuel.addActionListener(handler);
reset.addActionListener(handler);
options.addItemListener(handler);
petrol.addItemListener(handler);
Electric.addItemListener(handler);
diesel.addItemListener(handler);
//Listeners Added.
FlowLayout layout0 = new FlowLayout();
row1.setLayout(layout0);
row1.add(drv);
row1.add(park);
row1.add(refuel);
row1.setBorder(empty0);
add(row1);
GridLayout layout1 = new GridLayout(1, 3, 40, 50);
row2.setLayout(layout1);
row2.add(carTypeTag);
row2.add(options);
row2.add(fuelTypeTag);
row2.add(petrol);
row2.add(diesel);
row2.add(Electric);
add(row2);
GridLayout layout2 = new GridLayout(1, 4, 20, 0);
row3.setLayout(layout2);
costField.setEditable(false);
engField.setEditable(false);
tSField.setEditable(false);
mField.setEditable(false);
row3.add(costTag);
row3.add(costField);
row3.add(engTag);
row3.add(engField);
row3.add(tankSizeTag);
row3.add(tSField);
row3.add(mileageTag);
row3.add(mField);
row3.setBorder(empty2);
add(row3);
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER);
row4.setLayout(layout3);
row4.setBorder(empty4);
row4.add(petTank);
add(row4);
FlowLayout layout4 = new FlowLayout(FlowLayout.CENTER);
row5.setLayout(layout4);
reset.setPreferredSize(resetButtonX);
row5.add(reset);
add(row5);
setVisible(true);
}
public static void main(String[] args){
CarViewer gui = new CarViewer();
}
}
Event handling class (2):
import java.awt.event.*;
public class CarEvent implements ActionListener, ItemListener {
public void actionPerformed(ActionEvent event){
String cmd = event.getActionCommand();
if(cmd.equals("Drive"));{
}
else if(cmd.equals("Park")){
}
else if(cmd.equals("Refuel")){
}
else if(cmd.equals("Reset")){
}
}
public void itemStateChanged(ItemEvent event){
Object identifier = event.getItem();
String item = identifier.toString();
if())
}
}
For the check box question the below code may help you.
Use the CarEvent class as a inner class to CarViewer.
In the CarViewer add the event to each control
public class CarViewer extends JFrame {
petrol.addItemListener (new CarEvent());
Electric.addItemListener (new CarEvent());
diesel.addItemListener (new CarEvent());
class CarEvent implements ActionListener, ItemListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.toString());
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem().equals(petrol)) {
System.out.println("Petrol");
}
else if (e.getItem().equals(Electric)) {
System.out.println("Electric");
}
else if (e.getItem().equals(diesel)) {
System.out.println("Diesel");
}
}
} //CarEvent class
} //CarViewer class
If you want to use the CarEvent as a separate class then you need to pass the CarViewer class instance to this CarEvent class and access the check boxes (when the check boxes as public)
public class CarViewer extends JFrame {
petrol.addItemListener (new CarEvent(this));
//and so on ,,,,
}//CarViewer class
class CarEvent implements ActionListener, ItemListener {
CarViewer cv:
public CarEvent(CarViewer _object){
cv=_object;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.toString());
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem().equals(cv.petrol)) {
System.out.println("Petrol");
}
else if (e.getItem().equals(cv.Electric)) {
System.out.println("Electric");
}
else if (e.getItem().equals(cv.diesel)) {
System.out.println("Diesel");
}
}
}//CarEvent class

Action Listener does not work on swing

I have a form , That when i click to save button, "Yes" String should display on my console!
(I use "Yes" String for test!)
But does not work when clicked.
My code:
public final class NewUserFrame1 extends JFrame implements ActionListener {
UserInformation userinfo;
JLabel fnamelbl;
JLabel lnamelbl;
JTextField fntf;
JTextField lntf;
JLabel gndlnl;
JRadioButton malerb;
JRadioButton femalerb;
ButtonGroup bgroup;
JLabel registnm;
JButton savebt;
JButton cancelbt;
JLabel showreglbl;
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
fnamelbl = new JLabel("First name");
lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
fntf = new JTextField(10);
lntf = new JTextField(10);
gndlnl = new JLabel("Gender");
malerb = new JRadioButton("Male");
femalerb = new JRadioButton("Female");
bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
registnm = new JLabel("Registration ID is:");
showreglbl = new JLabel("");
JLabel regtemp = new JLabel();
savebt = new JButton("Save");
cancelbt = new JButton("Cancell");
JLabel buttontemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
JPanel radiopanel = new JPanel();
radiopanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radiopanel.add(malerb);
radiopanel.add(femalerb);
panel.add(radiopanel);
panel.add(new JLabel());
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.add(savebt);
panel.add(cancelbt);
panel.add(buttontemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 5, 3, 50, 10, 80, 60);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == savebt) {
System.out.print("Yes");
}
}
}
You need to add an ActionListener to your button like so:
savebt.addActionListener(this);
or with an anonymous class, like so:
savebt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code.
}
});
Using anonymous classes (or inner classes) is better because you can't have more than one actionPerformed() method in a given class.
You need to tell the button to invoke the ActionListener:
savebt = new JButton("Save");
savebt.addActionListener(this);
Note if you intend to use the same method for the save and cancel buttons, you'll need to differentiate, perhaps by comparing the source of the ActionEvent against the two buttons.

How Do I get the buttons to work? Java Programming

I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}

How I can get output from 1st frame textfield input text to 2nd frame textArea

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.

Categories

Resources