Use of JButton array Java - java

I am not sure what I am doing wrong. I am trying to create 4 buttons using the arrays and passing the method to the Set Panel class. When I run it I only get one button. Any help would be great. Essentially what I want is a Panel with four buttons, through the use of Methods.
public class SetButtons extends JButton implements ActionListener {
JButton [] buttonArray = new JButton[4];
JButton exitBtn, newGameBtn, checkBtn, clearBtn;
Font myFont = new Font("ink free", Font.BOLD,22);
public SetButtons(){
this.exitBtn = new JButton("Exit");
this.newGameBtn = new JButton("New Game");
this.checkBtn = new JButton("Check Answer");
this.clearBtn = new JButton("Clear");
this.buttonArray[0] = exitBtn;
this.buttonArray[1] = newGameBtn;
this.buttonArray[2] = checkBtn;
this.buttonArray[3] = clearBtn;
for (int i = 0; i < 4; i++){
this.buttonArray[i].addActionListener(this);
this.buttonArray[i].setFont(myFont);
this.buttonArray[i].setFocusable(false);
this.buttonArray[i].setLayout(new FlowLayout());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this){
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
public class SetPanel extends JPanel {
Font myFont = new Font("ink free", Font.BOLD,22);
SetLabels labels;
SetButtons exitButton;
SetPanel(){
SetButtons btn = new SetButtons();
this.add(btn);
this.setBackground(Color.darkGray);
this.setLayout(new FlowLayout());
}
}

Related

StackOverflowError when adding JTextField to the constructor

So I do know what an StackOverflowError is, the problem however is I can't find it here. I am supposed to make a simple GUI with labels, text fields and buttons. One of these buttons is supposed to "clear" the text fields, so I add that by putting text field as an argument in the constructor, but when I actually add the text fields i just get an stack overflow error. Here is the code:
Orders class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Orders extends JFrame {
public Orders() {
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4, 2, 2, 2));
JLabel name = new JLabel("Item name:");
JLabel number = new JLabel("Number of:");
JLabel cost = new JLabel("Cost:");
JLabel amount = new JLabel("Amount owed:");
JTextField nameJtf = new JTextField(10);
JTextField numberJtf = new JTextField(10);
JTextField costJtf = new JTextField(10);
JTextField amountJtf = new JTextField(10);
panel1.add(name);
panel1.add(nameJtf);
panel1.add(number);
panel1.add(numberJtf);
panel1.add(cost);
panel1.add(costJtf);
panel1.add(amount);
panel1.add(amountJtf);
JPanel panel2 = new JPanel();
JButton calculate = new JButton("Calculate");
JButton save = new JButton("Save");
JButton clear = new JButton("Clear");
JButton exit = new JButton("Exit");
panel2.add(calculate);
panel2.add(save);
panel2.add(clear);
panel2.add(exit);
OnClick action = new OnClick(exit, clear, save, calculate, nameJtf, numberJtf, costJtf, amountJtf);
exit.addActionListener(action);
this.setTitle("Otto's Items Orders Calculator");
this.add(panel1, BorderLayout.NORTH);
this.add(panel2, BorderLayout.SOUTH);
this.setSize(400, 200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Orders();
}
}
OnClick class :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OnClick extends Orders implements ActionListener {
private JButton exitModify = null;
private JButton clearModify = null;
private JButton saveModify = null;
private JButton calculateModify = null;
private JTextField nameModify = null;
private JTextField numberModify = null;
private JTextField costModify = null;
private JTextField amountModify = null;
public OnClick (JButton _exitModify, JButton _clearModify, JButton _saveModify, JButton _calculateModify, JTextField _nameModify, JTextField _numberModify, JTextField _costModify, JTextField _amountModify) {
exitModify = _exitModify;
clearModify = _clearModify;
saveModify = _saveModify;
calculateModify = _calculateModify;
nameModify = _nameModify;
numberModify = _numberModify;
costModify = _numberModify;
amountModify = _amountModify;
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == this.exitModify) {
System.exit(0);
} else if (o == this.clearModify) {
amountModify = null;
nameModify = null;
costModify = null;
numberModify = null;
}
}
}
As soon as I add nameJtf I get this error.

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

How do I compare java swing button icons to check equality?

I am making a Tic-Tac-Toe game in Java to teach myself the Swing class. I am having to problems, though.
First, how do you compare buttons using icons?
symX = new ImageIcon(this.getClass().getResource("symbolX.png"));
symO = new ImageIcon(this.getClass().getResource("symbolO.png"));
I use those 2 variables to set the button images.
if (e.getSource() instanceof JButton) {
JButton source = (JButton) e.getSource();
if (isX) {
source.setIcon(symX);
source.setEnabled(false);
source.setDisabledIcon(symX);
} else {
source.setIcon(symO);
source.setEnabled(false);
source.setDisabledIcon(symO);
}
}
The second question is where do you compare objects are an Action Event? I tried to compare inside of the if statements in the above code, but Eclipse always gives me compile time errors doing that.
If I place the code in the method with the buttons, it seems like java never gets to them.
As requested, here is the entirety of my Java file.
package ticTacToeGUI;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class tttGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9;
private ImageIcon symX, symO;
private ImageIcon symIco = new ImageIcon(this.getClass().getResource("symbolX.png"));
private boolean isX = true;
public static void main(String[] args) {
new tttGUI();
}
public tttGUI() {
//Setup the window.
super("Tic-Tac-Toe GUI 1.0");
setSize(425,425);
setIconImage(symIco.getImage());
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Create the content.
symX = new ImageIcon(this.getClass().getResource("symbolX.png"));
symO = new ImageIcon(this.getClass().getResource("symbolO.png"));
panel.setLayout(new GridLayout(3,3));
setVisible(true);
JButton btn1 = new JButton();
JButton btn2 = new JButton();
JButton btn3 = new JButton();
JButton btn4 = new JButton();
JButton btn5 = new JButton();
JButton btn6 = new JButton();
JButton btn7 = new JButton();
JButton btn8 = new JButton();
JButton btn9 = new JButton();
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
btn5.addActionListener(this);
btn6.addActionListener(this);
btn7.addActionListener(this);
btn8.addActionListener(this);
btn9.addActionListener(this);
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.add(btn6);
panel.add(btn7);
panel.add(btn8);
panel.add(btn9);
add(panel);
revalidate();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
JButton source = (JButton) e.getSource();
if (isX) {
source.setIcon(symX);
source.setEnabled(false);
source.setDisabledIcon(symX);
} else {
source.setIcon(symO);
source.setEnabled(false);
source.setDisabledIcon(symO);
}
}
isX ^= true;
}
}
I know this is two years too late, but other people in the future might find this useful...
Anyway, coincidentally I'm programming up 3D Tic Tac Toe.
To compare ImageIcons, I initialized the Icons with a String description, and then used:
((ImageIcon) JLabel().getIcon()).getDescription().compareTo("someOtherDesc")
Hope that helps you or someone else in future...
I have some ideas on how to do that, for instance:
symX = new ImageIcon(this.getClass().getResource("symbolX.png"));
symO = new ImageIcon(this.getClass().getResource("symbolO.png"));
if (btn1.getIcon().equals(symX) && btn2.getIcon().equals(symX) {
// Your logic here...
}
This can be done inside you actionPerformed() method if you promote your local variables btn1...btn9 to instance variables. It seems you mixed up concepts since you already have btn1...btn9 declared as instance variables, but also create new ones as local variables.
public class TttGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel panel = new JPanel();
private JButton btn1 = new JButton();
private JButton btn2 = new JButton();
private JButton btn3 = new JButton();
private JButton btn4 = new JButton();
private JButton btn5 = new JButton();
private JButton btn6 = new JButton();
private JButton btn7 = new JButton();
private JButton btn8 = new JButton();
private JButton btn9 = new JButton();
private ImageIcon symX, symO;
private ImageIcon symIco = new ImageIcon(this.getClass().getResource("symbolX.png"));
private boolean isX = true;
public static void main(String[] args) {
new TttGUI();
}
public TttGUI() {
//Setup the window.
super("Tic-Tac-Toe GUI 1.0");
setSize(425,425);
setIconImage(symIco.getImage());
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Create the content.
symX = new ImageIcon(this.getClass().getResource("symbolX.png"));
symO = new ImageIcon(this.getClass().getResource("symbolO.png"));
panel.setLayout(new GridLayout(3,3));
setVisible(true);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
btn5.addActionListener(this);
btn6.addActionListener(this);
btn7.addActionListener(this);
btn8.addActionListener(this);
btn9.addActionListener(this);
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.add(btn6);
panel.add(btn7);
panel.add(btn8);
panel.add(btn9);
add(panel);
revalidate();
}
}
I have changed your class name so that it is compliant to Java conventions (class names must always start with capital case).
Though it is too late but anyone who search may get help in comparing imageicons.I think it is very easy to campare
ImageIcon icon = new ImageIcon("images/myimage.jpg");
JLabel a = new JLabel(icon);
JLabel b = new JLabel(icon);
if(a.getIcon().toString().equals(b.getIcon().toString()))
{
//do whatever
}

Java grid layout GUI - how to enter new pane on event?

How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout

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("");
}
}
}
}

Categories

Resources