So I made a GUI which in this case if you want to add a Car to the database, you click "Add"
then a JFrame pops out with the following code:
public void newCar()
{
JFrame window = new JFrame("New Car");
JPanel newCarButtons = new JPanel();
newCarButtons.setLayout(new FlowLayout());
saveCar=new JButton("Save");
saveCar.addActionListener(buttonListener);
newCarButtons.add(saveCar);
cancelCar=new JButton("Cancel");
cancelCar.addActionListener(buttonListener);
newCarButtons.add(cancelCar);
JPanel newCarText = new JPanel();
GroupLayout group = new GroupLayout(newCarText);
newCarText.setLayout(group);
group.setAutoCreateGaps(true);
group.setAutoCreateContainerGaps(true);
JLabel make = new JLabel("Brand:");
JTextField maket = new JTextField(10);
newCarText.add(make);
newCarText.add(maket);
JLabel model = new JLabel("Model:");
JTextField modelt = new JTextField(10);
newCarText.add(model);
newCarText.add(modelt);
JLabel license = new JLabel("License Plate Numbers:");
JTextField licenset = new JTextField(10);
newCarText.add(license);
newCarText.add(licenset);
JLabel color = new JLabel("Color:");
JTextField colort = new JTextField(10);
newCarText.add(color);
newCarText.add(colort);
JLabel year = new JLabel("Year:");
final JTextField yeart = new JTextField(10);
yeart.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent e)
{
super.keyTyped(e);
e.getKeyCode();
if (!((int) e.getKeyChar() >= 48 && (int) e.getKeyChar() <= 57))
{
e.consume();
}
}
});
newCarText.add(year);
newCarText.add(yeart);
JLabel horse = new JLabel("Horse Power: ");
JTextField horset = new JTextField(10);
newCarText.add(horse);
newCarText.add(horset);
JLabel isAvailable = new JLabel("Car Status:");
JLabel isAvailablet = new JLabel("Available");
newCarText.add(isAvailable);
newCarText.add(isAvailablet);
JLabel time = new JLabel("Time Until Service: ");
JTextField timet = new JTextField(10);
newCarText.add(time);
newCarText.add(timet);
JLabel consumption = new JLabel("Consumption per 100km: ");
JTextField consumptiont = new JTextField(10);
newCarText.add(consumption);
newCarText.add(consumptiont);
JLabel seats = new JLabel("Number of Seats: ");
JTextField seatst = new JTextField(10);
seatst.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent e)
{
super.keyTyped(e);
e.getKeyCode();
if (!((int) e.getKeyChar() >= 48 && (int) e.getKeyChar() <= 57))
{
e.consume();
}
}
});
newCarText.add(seats);
newCarText.add(seatst);
JLabel doors = new JLabel("Number of Doors: ");
JTextField doorst = new JTextField(10);
doorst.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent e)
{
super.keyTyped(e);
e.getKeyCode();
if (!((int) e.getKeyChar() >= 48 && (int) e.getKeyChar() <= 57))
{
e.consume();
}
}
});
newCarText.add(doors);
newCarText.add(doorst);
JLabel transmission = new JLabel("Transmission ");
JComboBox transmissiont = new JComboBox<String>();
transmissiont.addItem("Auto");
transmissiont.addItem("Manual");
transmissiont.addActionListener(buttonListener);
newCarText.add(transmission);
newCarText.add(transmissiont);
JLabel climate = new JLabel("Climate Control: ");
JComboBox climatet = new JComboBox<String>();
climatet.addItem("Yes");
climatet.addItem("No");
newCarText.add(climate);
newCarText.add(climatet);
GroupLayout.SequentialGroup hGroup = group.createSequentialGroup();
hGroup.addGroup(group.createParallelGroup().addComponent(make)
.addComponent(model).addComponent(license).addComponent(color)
.addComponent(time).addComponent(consumption)
.addComponent(year).addComponent(horse).addComponent(isAvailable)
.addComponent(seats).addComponent(doors).addComponent(transmission)
.addComponent(climate));
hGroup.addGroup(group.createParallelGroup().addComponent(maket)
.addComponent(modelt).addComponent(licenset).addComponent(colort)
.addComponent(timet).addComponent(consumptiont)
.addComponent(yeart).addComponent(isAvailablet)
.addComponent(horset).addComponent(seatst).addComponent(doorst)
.addComponent(transmissiont).addComponent(climatet));
group.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = group.createSequentialGroup();
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(make).addComponent(maket));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(model).addComponent(modelt));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(license).addComponent(licenset));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(color).addComponent(colort));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(year).addComponent(yeart));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(horse).addComponent(horset));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(time).addComponent(timet));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(consumption).addComponent(consumptiont));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(isAvailable).addComponent(isAvailablet));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(seats).addComponent(seatst));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(doors).addComponent(doorst));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(transmission).addComponent(transmissiont));
vGroup.addGroup(group.createParallelGroup(Alignment.BASELINE)
.addComponent(climate).addComponent(climatet));
group.setVerticalGroup(vGroup);
JPanel newCar = new JPanel();
newCar.setLayout(new BorderLayout());
newCar.add(newCarText, BorderLayout.NORTH);
newCar.add(newCarButtons, BorderLayout.SOUTH);
newCar.setBorder(new TitledBorder(BorderFactory
.createLineBorder(Color.black), "[New Car]", 2, 0));
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(), colort.getText(), Integer.parseInt("yeart.getText()"), null, horset.getText(), timet.getText(), consumptiont.getText(), Integer.parseInt("seatst.getText()"), Integer.parseInt("doorst.getText()"), null, null, 0);
window.add(newCar);
window.setLocationRelativeTo(null);
window.setSize(400, 450);
window.setVisible(true);
}
Notice that at the bottom there is a Car object. This is where i need your help. The adapter, when adding cars, takes a Car object as an argument, so the idea is to fill out all the text fields and based on the text you input , you create a new Car object. But if I do this ,this way it will just create a empty Car object since when you open the window you don't have anything in the textfields. So how do i make that when you click "Add" it sends out a filled Car object based on the content in the text fields?
Button Listener:
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addCars)
{
newCar();
}
if (e.getSource() == saveCar)
{
adapter.addCar(car);
}
}
}
Why don't you simply pass your car object as argument to newCar method and initialize proper fields there just as you are doing when you are persisting car instance?
if (e.getSource() == addCars)
{
newCar(car);
}
remember to change newCar method signature.
public void newCar(Car newCar)
{
//DO WHATEVER YOU WANT WITH THAT DATA AND INITIALIZE PROPER FIELDS
JFrame window = new JFrame("New Car");
(.....)
This should go inside the listener
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(),
colort.getText(), Integer.parseInt("yeart.getText()"), null,
horset.getText(), timet.getText(), consumptiont.getText(),
Integer.parseInt("seatst.getText()"),
Integer.parseInt("doorst.getText()"),
null, null, 0);
You want to get the text when the button is pressed. Not in your constructor
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addCars)
{
newCar(); // I don't know what you're trying to do here
}
if (e.getSource() == saveCar)
{
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(),
colort.getText(), Integer.parseInt("yeart.getText()"), null,
horset.getText(), timet.getText(), consumptiont.getText(),
Integer.parseInt("seatst.getText()"),
Integer.parseInt("doorst.getText()"),
null, null, 0);
// add car1 to database
}
}
}
Edit: Declare all your textfields as class members, then you can use them in yout listener class
public class GUI{
JTextFeild maket = new JTextField();
JTextFeild licenset = new JTextField();
JTextFeild colort = new JTextField();
JTextFeild yeart = new JTextField();
JTextFeild horset = new JTextField();
JTextFeild timet = new JTextField();
JTextFeild consumptiont = new JTextField();
JTextFeild maket = new JTextField();
public void newCar(){
... // remove your textfields from here.
}
public static void main(String[] args){
...
}
private class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addCars)
{
newCar(); // I don't know what you're trying to do here
}
if (e.getSource() == saveCar)
{
Car car1= new Car(maket.getText(), modelt.getText(), licenset.getText(),
colort.getText(), Integer.parseInt("yeart.getText()"), null,
horset.getText(), timet.getText(), consumptiont.getText(),
Integer.parseInt("seatst.getText()"),
Integer.parseInt("doorst.getText()"),
null, null, 0);
// add car1 to database
}
}
}
}
Related
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
This question already has an answer here:
Gui JList ActionListener
(1 answer)
Closed 9 years ago.
hey all goodevening i have a problem about my second button named "Submit" because i cant transfer all information i entered to my null JList in the frame here is my code so far my problem is if i clicked submit my all information will appear in my Message area in frame it needs to be list. thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class vin extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
JList list = new JList();
JPanel panel = new JPanel();
JLabel brief;
public vin()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
list = new JList();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
vin w = new vin();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}
I modified your code so that your list is backed by a Vector which you update when you press the Submit button.
public class Frame extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
Vector vector = new Vector();
JList list = new JList(vector);
JPanel panel = new JPanel();
JLabel brief;
public Frame()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
vector.add(t1.getText() + "-" + t2.getText() + "-" + t3.getText() + "-" + t4.getText());
list.setListData(vector);
list.revalidate();
list.repaint();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
Frame w = new Frame();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}
In my form, when i press ENTER button in my keyboard, the okAction() method should be invoke (and invoke perfectly).
My problem is in focus state, When i fill the text fields and then press the ENTER button, the okAction() didn't invoked, because the focus is on the second text field (not on the panel).
How fix this problem?
public class T3 extends JFrame implements ActionListener {
JButton cancelBtn, okBtn;
JLabel fNameLbl, lNameLbl, tempBtn;
JTextField fNameTf, lNameTf;
public T3() {
add(createForm(), BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new T3();
}
});
}
public JPanel createForm() {
JPanel panel = new JPanel();
panel.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Button");
panel.getActionMap().put("Button", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
okAction();
}
});
okBtn = new JButton("Ok");
okBtn.addActionListener(this);
cancelBtn = new JButton("Cancel");
tempBtn = new JLabel();
fNameLbl = new JLabel("First Name");
lNameLbl = new JLabel("Last Name");
fNameTf = new JTextField(10);
fNameTf.setName("FnTF");
lNameTf = new JTextField(10);
lNameTf.setName("LnTF");
panel.add(fNameLbl);
panel.add(fNameTf);
panel.add(lNameLbl);
panel.add(lNameTf);
panel.add(okBtn);
panel.add(cancelBtn);
panel.add(tempBtn);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 50, 10, 80, 60);
return panel;
}
private void okAction() {
if (fNameTf.getText().trim().length() != 0 && lNameTf.getText().trim().length() != 0) {
System.out.println("Data saved");
} else System.out.println("invalid data");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okBtn) {
okAction();
}
}
}
Declare a default button for your GUI's JRootPane:
public T3() {
//!! ..... etc...
setVisible(true);
getRootPane().setDefaultButton(okBtn);
}
In fact with a default button set, I don't see that you need to use key bindings.
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("");
}
}
}
}
I am having some issues with my code, I cant see whats wrong with the logic, but here it is. I want them to have the radio button to choose either or, and when one is selected(radio button) the text area isn't available and vise versa. Here is the segment of the code. When I go back and forth on the radio buttons, both become not selectable, and I am unsure why.
private void PriceTab()
{
pricePanel = new JPanel(new FlowLayout());
final JRadioButton poolPrice= new JRadioButton("Pool");
final JRadioButton tubPrice = new JRadioButton("Hot Tub");
poolPrice.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(poolPrice);
group.add(tubPrice);
pricePanel.add(poolPrice);
pricePanel.add(tubPrice);
final JLabel poolLabel = new JLabel("Enter the pool's volume: ");
final JTextField poolField = new JTextField(10);
pricePanel.add(poolLabel);
pricePanel.add(poolField);
final JTextField tubField = new JTextField(10);
final JLabel tubLabel = new JLabel ("Enter the tub's volume: ");
pricePanel.add(tubLabel);
pricePanel.add(tubField);
JButton calculatePrice = new JButton("Calculate Price");
calculatePrice.setMnemonic('C');
pricePanel.add(calculatePrice);
pricePanel.add(createExitButton());
pricePanel.add(new JLabel("The price is: "));
final JTextField priceField = new JTextField(10);
priceField.setEditable(false);
pricePanel.add(priceField);
final JTextArea messageArea = createMessageArea(1, 25,
"*Please only select one section");
pricePanel.add(messageArea);
calculatePrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double pool = Double.parseDouble (poolField.getText());
double tub = Double.parseDouble(tubField.getText());
double price;
if (poolPrice.isSelected()) {
price = pool * 100;
} else {
price = tub * 75;
}
priceField.setText(df.format(price));
}
});
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
messageArea.setVisible(false);
}
}
};
poolPrice.addActionListener(priceListener);
tubPrice.addActionListener(priceListener);
}
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
// Re-enable the previously disabled labels
poolLabel.setEnabled(true);
poolField.setEnabled(true);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
// Re-enable disabled labels
tubLabel.setEnabled(true);
tubField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
You need to re-enable the buttons you disabled.