add item to JComboBox from another JDialog - java

Hi I need help with filling ComboBox (ClassA) from ClassAddItem. After selecting "Add New Item" from the ComboBox, call the new window. When you click "Add new item" (ClassAddItem) I want to join a new item into the ComboBox - class ClassA.
In a ClassA is also button "Add New Item" it works, but how do I add a new item to the CB from another class???
Item "Add new item" in a ComboBox is deliberately not in the array String[] cbItem, because in my application possibilities Loading from a file and I do not want this item is visible in the file. Also, it would be advantageous if the item "Add new item" still at the end of the ComboBox.
Thank you for your response
sorry for my English :)
public class ClassA extends JFrame {
private JPanel contentPane;
public JComboBox comboBox;
private String[] cbItem = {"A", "B", "C"};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClassA frame = new ClassA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ClassA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 291, 152);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
comboBox = new JComboBox(cbItem);
comboBox.addItem("add new Item");
comboBox.setBounds(10, 11, 116, 23);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("add new Item")) {
ClassAddItem cAI = new ClassAddItem();
cAI.setVisible(true);
}
}
});
contentPane.add(comboBox);
JButton btnAddNewItem = new JButton("add new item");
btnAddNewItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.addItem("this works");
}
});
btnAddNewItem.setBounds(136, 11, 116, 23);
contentPane.add(btnAddNewItem);
}
}
ClassAddItem:
public class ClassAddItem extends JDialog {
public ClassAddItem() {
setBounds(100, 100, 266, 155);
getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Add new item");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClassA cA = new ClassA();
cA.comboBox.addItem("this does not work");
}
});
btnNewButton.setBounds(62, 11, 120, 23);
getContentPane().add(btnNewButton);
}
}

you can make a constructor using the combobox...
private JComboBox comboBox;
//constructor
public ClassAddItem(JComboBox box) {
this.comboBox = box;
....
}
and use this comboBox within your actionListener
public void actionPerformed(ActionEvent e) {
this.comboBox.addItem("this does work");
}

Related

Dispose() only working once

My problem is that I have a class that when the user types out the text displayed dispose() is called, which works the first time but if you don't close the program and open it again, dispose() is called, but doesn't do anything which breaks the program.
public class TypeMenu extends JDialog {
protected final JPanel contentPanel = new JPanel();
protected static JTextField inputTxtField;
protected static JTextField textField;
protected static JTextField introTxtField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
* #param introTxtField2
* #param textField2
* #param inputTxtField2
*/
public TypeMenu(JTextField inputTxtField2, JTextField introTxtField2, JTextField textField2) {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getTextField());
contentPanel.add(getIntroTxtField());
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
}
}
protected JTextField getInputTxtField() {
if (inputTxtField == null) {
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
protected JTextField getIntroTxtField() {
if (introTxtField == null) {
introTxtField = new JTextField();
introTxtField.setHorizontalAlignment(SwingConstants.CENTER);
introTxtField.setFont(new Font("Tahoma", Font.BOLD, 15));
introTxtField.setText("Easy Mode");
introTxtField.setEditable(false);
introTxtField.setBounds(56, 11, 314, 29);
introTxtField.setColumns(10);
}
return introTxtField;
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setFont(new Font("Monospaced", Font.BOLD, 20));
textField.setBounds(10, 51, 414, 40);
}
return textField;
}
}
This is one of the child classes
public class Easy extends TypeMenu {
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Easy() {
super(inputTxtField, introTxtField, textField);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getIntroTxtField());
getString();
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
textField.selectAll();
}
}
private void getString() {
String str = textField.getText();
if (str.equals("")) {
String generator = StringGenerator.medium();
String nStr = "" + generator;
textField.setText(nStr);
}
}
}
The code that calls this class
public class StartMenu extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField introTxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
StartMenu dialog = new StartMenu();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates the dialog and creates the buttons that take the user to each variation of the game when pressed.
*/
public StartMenu() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
introTxt = new JTextField();
introTxt.setFont(new Font("Tahoma", Font.BOLD, 12));
introTxt.setHorizontalAlignment(SwingConstants.CENTER);
introTxt.setText("Start Menu\r\n");
introTxt.setEditable(false);
introTxt.setBounds(75, 11, 276, 20);
contentPanel.add(introTxt);
introTxt.setColumns(10);
}
{
JButton btnEasyButton = new JButton("Easy Mode");
btnEasyButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
new Easy().setVisible(true);
}
});
btnEasyButton.setBounds(141, 42, 140, 23);
contentPanel.add(btnEasyButton);
}
{
JButton btnMediumButton = new JButton("Medium Mode");
btnMediumButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Medium().setVisible(true);
}
});
btnMediumButton.setBounds(141, 81, 140, 23);
contentPanel.add(btnMediumButton);
}
{
JButton btnHardButton = new JButton("Hard Mode");
btnHardButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Hard().setVisible(true);
}
});
btnHardButton.setBounds(141, 120, 140, 23);
contentPanel.add(btnHardButton);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
}
your text field is static so he will have only one instance across the application.
so in the method getIntroTxtField() you have if statement that says :
if (introTxtField == null)
in the first time this condition is true but when you create the new instance this condition is false because the instance of the static field is all ready created in the first and you are adding the key listener inside the condition
so the action listener will be added only in the first creation.
if you need to keep the static because you need in other class you need to remove the == null
protected JTextField getInputTxtField() {
inputTxtField = null;
{
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
or remove the static from you field declaration static is used in
shared instace only when you are using only one instace across the
application like sessionFactory or any thing that need to be created
only one time.
you code is a lot to read but i think your problem is that you are calling the dispose() of the wrong object. may you are calling it always for the first object and you are creating a new one, and the dispose of this new dialog will never be call,Check you code may be you are creating many object and the dispose() is not called at all. make sure that you have full control of your objects instance to know if you are diposing the wanted dialog.

refresh button doesn't refresh jtable

public class WeatherFrame extends JFrame {
private JPanel contentPane;
private JTable table;
HealthData health = new HealthData();
private DefaultTableModel model;
String[] columnNames = {"zipcode", "county", "city", "state", "year", "month","ageGroup",
"numOfVisits", "MonthlyMax", "MonthlyMin", "MonthlyNor"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WeatherFrame frame = new WeatherFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WeatherFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 300);
contentPane = new JPanel();
contentPane.setBounds(100, 100,750, 200);
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 25, 788, 180);
contentPane.add(scrollPane);
populateTable();
table = new JTable(model);
scrollPane.setViewportView(table);
JButton btnInsert = new JButton("insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
InsertFrame frame = new InsertFrame();
frame.setVisible(true);
}
});
btnInsert.setBounds(279, 217, 117, 29);
contentPane.add(btnInsert);
JButton btnDelete = new JButton("delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DeleteFrame delete = new DeleteFrame();
delete.setVisible(true);
}
});
btnDelete.setBounds(412, 217, 117, 29);
contentPane.add(btnDelete);
JButton btnSearch = new JButton("search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SelectFrame search = new SelectFrame();
search.setVisible(true);
}
});
btnSearch.setBounds(530, 217, 117, 29);
contentPane.add(btnSearch);
JLabel lblWeatherTable = new JLabel("Weather Table");
lblWeatherTable.setBounds(149, 6, 107, 16);
contentPane.add(lblWeatherTable);
JButton btnNext = new JButton("update");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpdateFrame update = new UpdateFrame();
update.setVisible(true);
}
});
btnNext.setBounds(150, 217, 117, 29);
contentPane.add(btnNext);
JButton btnRefresh = new JButton("refresh");
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
populateTable();
}
});
btnRefresh.setBounds(29, 217, 117, 29);
contentPane.add(btnRefresh);
JButton btnAnalyze = new JButton("Analyze");
btnAnalyze.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ShowAnalyze analyze = new ShowAnalyze(health.analyze());
analyze.setVisible(true);
}
});
btnAnalyze.setBounds(662, 217, 117, 29);
contentPane.add(btnAnalyze);
}
#SuppressWarnings("serial")
public void populateTable() {
model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> temp = new ArrayList<Health>();
temp = health.showAllData();
for(int i = 0; i< temp.size(); i++) {
Object[] data = {temp.get(i).getZipCode(), temp.get(i).getCounty(), temp.get(i).getCounty(), temp.get(i).getState(),temp.get(i).getYear(),
temp.get(i).getMonth(), temp.get(i).getAgeGroup(), temp.get(i).getNumOfVisits(), temp.get(i).getMMax(), temp.get(i).getMMin(), temp.get(i).getMNor()};
model.addRow(data);
}
table.setModel(model);
}
}
I'm trying to refresh the jtable using a refresh button, when I click the button it seems like it is loading, but after that nothing changes on the table. How can I fix this problem? In the action performed method of the refresh button, I called populateTable which is a function to load data into table.
In the populateTable method, you change the table model but you do not pass that new model to the JTable.
Option 1: replace the table model
In the constructor, you call:
table = new JTable(model);
populateTable();
In the populateTable, I would expect something like:
table.setModel(model);
Option 2: update the table model
As mKorbel already suggested, you can also update your table model instead of throwing the existing model away and creating a new one. Your populateTable method could look like this (using Java 8 and with a new initializeModel method to create the table model initially):
public void populateTable() {
boolean firstTime = (model == null);
if (firstTime) {
initializeModel();
} else {
model.getDataVector().clear();
}
for (Health item : health.showAllData()) {
model.addRow(new Vector<>(Arrays.asList(
item.getZipCode(), item.getCounty(), item.getState(), item.getYear(),
item.getMonth(), item.getAgeGroup(), item.getNumOfVisits(),
item.getMMax(), item.getMMin(), item.getMNor()
)));
}
if (firstTime && table != null) {
table.setModel(model);
}
}
private void initializeModel() {
model = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for (String name : columnNames)
model.addColumn(name);
}
JTable and its DefaultTableModel (desclared as private JTable table; and private DefaultTableModel model;) doesn't know something that a new model = new DefaultTableModel(){ is (re)created in public void populateTable() {,
you have to
add a new DefaultTableModel to JTables instance that is already visible in your Swing GUI
(better option is) add a new data directly to private DefaultTableModel model;, this model is designated for
rest is very well described in comment by # Andrew Thompson

I'm creating a contact application. Is there any other thing that I should create?

I'm creating the app using Eclipse Kepler...I've created 3 database in Eclipse- database, entity and UI. In database, it contains ContactDAO,UserDAO and DBManager(for database connection) . In Entity, it contains Contact and User. In UI, it contains ContactAdd, COntactDetails , ContactList, LoginFrame and MenuFrame JFrames. Now, I'm stuck at ContactList frame... it contains ComboBox and I've tried to run it but I can't get the names... this is the code:
public class ContactList extends JFrame {
private JPanel contentPane;
private JTextField txtSearch;
private JComboBox cbContactNames;
private MenuFrame parentFrame;
private Contact selContact;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ContactList frame = new ContactList(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ContactList(MenuFrame f) {
this.parentFrame = f;
setTitle("Personal Assistant");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtSearch = new JTextField();
txtSearch.setBounds(22, 11, 294, 20);
contentPane.add(txtSearch);
txtSearch.setColumns(10);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
searchContact();
}
});
btnSearch.setBounds(326, 10, 89, 23);
contentPane.add(btnSearch);
JLabel lblName = new JLabel("Name");
lblName.setBounds(42, 88, 46, 14);
contentPane.add(lblName);
cbContactNames = new JComboBox();
cbContactNames.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED)
{
if (cbContactNames.getSelectedIndex()>0){
String name=(String)cbContactNames.getSelectedItem();
selContact=ContactDAO.findContactByName(name); //adjusted
showContact();
}
}
}
});
ArrayList<Contact> ContactList=ContactDAO.getAllContacts();
cbContactNames.addItem("--Select Name--");
for (int i=0; i<ContactList.size(); i++)
{
Contact contact = ContactList.get(i);
cbContactNames.addItem(contact.getName());
}
cbContactNames.setBounds(87, 85, 229, 20);
contentPane.add(cbContactNames);
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
goBack();
}
});
btnClose.setBounds(158, 203, 89, 23);
contentPane.add(btnClose);
}
private void goBack() {
// TODO Auto-generated method stub
parentFrame.setVisible(true);
this.dispose();
}
private void showContact() {
// TODO Auto-generated method stub
ContactDetails contactdetails=new ContactDetails(this,selContact);
contactdetails.setVisible(true);
this.setVisible(false);
}
private void searchContact() {
String name=txtSearch.getText();
if (name!=null){
selContact=ContactDAO.findContactByName(txtSearch.getText());
}
showContact();
}
}
Then, I have also created the ContactDetails frame that contains the contact details, edit save and close buttons, and Delete label set as Image. The project says when the edit button is clicked, the save button will be visible... I don't know how to do that...Here's my code :
public class ContactDetails extends JFrame {
private JPanel contentPane;
private JTextField txtName;
private JTextField txtMobile;
private JTextField txtHome;
private JTextField txtEmail;
private JButton btnEdit;
private JButton btnSave;
private ContactList parentFrame;
private Contact contact;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ContactDetails frame = new ContactDetails(null,null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ContactDetails(ContactList f,Contact c) {
this.parentFrame = f;
this.contact=c;
setTitle("Contact Details");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblImage = new JLabel("");
lblImage.setIcon(new ImageIcon(ContactDetails.class.getResource("/images/kitty.png")));
lblImage.setBounds(34, 28, 79, 70);
contentPane.add(lblImage);
JLabel lblName = new JLabel("Name:");
lblName.setBounds(119, 48, 46, 14);
contentPane.add(lblName);
txtName = new JTextField(contact.getName());
txtName.setBounds(162, 45, 169, 20);
contentPane.add(txtName);
txtName.setColumns(10);
JLabel lblMobile = new JLabel("Mobile:");
lblMobile.setBounds(119, 93, 46, 14);
contentPane.add(lblMobile);
txtMobile = new JTextField();
txtMobile.setBounds(162, 90, 169, 20);
contentPane.add(txtMobile);
txtMobile.setColumns(10);
JLabel lblHome = new JLabel("Home:");
lblHome.setBounds(119, 141, 46, 14);
contentPane.add(lblHome);
txtHome = new JTextField();
txtHome.setBounds(162, 138, 169, 20);
contentPane.add(txtHome);
txtHome.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(119, 186, 46, 14);
contentPane.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(162, 183, 169, 20);
contentPane.add(txtEmail);
txtEmail.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
contactAdded();
}
});
btnSave.setBounds(184, 227, 74, 23);
contentPane.add(btnSave);
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
editContact();
}
});
btnEdit.setBounds(110, 227, 74, 23);
contentPane.add(btnEdit);
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
goBack();
}
});
btnClose.setBounds(257, 227, 74, 23);
contentPane.add(btnClose);
JLabel lblDelete = new JLabel("");
lblDelete.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
removeContact();
}
});
lblDelete.setIcon(new ImageIcon(ContactDetails.class.getResource("/images/trush.png")));
lblDelete.setBounds(365, 28, 46, 54);
contentPane.add(lblDelete);
}
private void contactAdded() {
// TODO Auto-generated method stub
String name=txtName.getText();
String mobile=txtMobile.getText();
String home=txtHome.getText();
String email=txtEmail.getText();
Contact contact = new Contact(name, mobile, home, email);
if(ContactDAO.create(contact)){
JOptionPane.showMessageDialog(contentPane, "Contact successfull saved!");
}
else {
JOptionPane.showMessageDialog(contentPane, "Contact not save!");
}
}
private void goBack() {
// TODO Auto-generated method stub
parentFrame.setVisible(true);
this.dispose();
}
private void removeContact() {
// TODO Auto-generated method stub
String name=txtName.getText();
String mobile=txtMobile.getText();
String home=txtHome.getText();
String email=txtEmail.getText();
Contact contact = new Contact(name, mobile, home, email);
if(ContactDAO.delete(contact)){
JOptionPane.showMessageDialog(contentPane, "Contact deleted");
}
else {
JOptionPane.showMessageDialog(contentPane, "Contact delete unsuccessful");
}
}
private void editContact() {
// TODO Auto-generated method stub
String name=txtName.getText();
String mobile=txtMobile.getText();
String home=txtHome.getText();
String email=txtEmail.getText();
Contact contact = new Contact(name, mobile, home, email);
if (ContactDAO.update(contact)){
JOptionPane.showMessageDialog(contentPane, "Contact successfully updated");
}
else {
JOptionPane.showMessageDialog(contentPane, "Contact update unsuccessful");
}
}
}
Also, the Save button is tricky for me... It seems that after clicking the Save button, a message should pop up for confirmation that should include (OK) button. When the (ok)button is clicked, Save button will be disabled and Edit button will be enabled again. All Text fields will be disabled. The (Delete Icon button) also needs a prompt box that includes (Yes, no and cancel) buttons. If confirm, contact will be deleted and user will be brought back to the contacts list frame... How should I do it?
Tell me if I have to create another JFrame or DAO...
You need somthing like this for your save button and same for remove button:
int showConfirmDialog = JOptionPane.showConfirmDialog(new JFrame(), "Approve?","Title",JOptionPane.YES_NO_OPTION);
if(showConfirmDialog == JOptionPane.YES_OPTION){
btnSave.setEnabled(false);
btnEdit.setEnabled(true);
txtName.setEnabled(false);
//other fields
} else {
//If no or cancel actions
}
Read tutorial for dialogs.
Watch showConfirmDialog(...)

Focus navigation in keyBinding

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.

How to give JButtons different functionality?

How would give different JButtons using the same ActionPerformed function different functionality?
public class ToolBarExample extends JPanel implements ActionListener {
public JTextPane pane;
public JMenuBar menuBar;
public JToolBar toolBar;
public JButton Aster;
public JButton Azaleas;
public JButton ChristFern;
public JButton JapBarberry;
public ToolBarExample() {
toolBar = new JToolBar("Formatting", JToolBar.VERTICAL);
this.Aster = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_Aster.png"));
this.toolBar.add(Aster);
this.Aster.addActionListener(this);
this.Azaleas = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_Azaleas.png"));
this.toolBar.add(Azaleas);
this.Azaleas.addActionListener(this);
this.ChristFern = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_ChristmasFern.png"));
this.toolBar.add(ChristFern);
this.ChristFern.addActionListener(this);
this.JapBarberry = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_JapaneseBarberry.png"));
this.toolBar.add(JapBarberry);
this.JapBarberry.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
try {
if(e.getSource() == Aster) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_Aster.png", 200, 600);
Game.setNatives(plant1);
}
if(e.getSource() == Azaleas) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_Azaleas.png", 100, 600);
Game.setNatives(plant1);
}
if(e.getSource() == ChristFern) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_ChristmasFern.png", 300, 600);
Game.setNatives(plant1);
}
if(e.getSource() == JapBarberry) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_JapaneseBarberry.png", 400, 600);
Game.setNatives(plant1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Right now I am trying to use the e.getSource to find out what button is being pushed,
and then execute something different for each button.
However, right now the only button that is working is the first one (Aster).
Does anyone know what I am doing wrong, or what I should be doing?
You can use the setActionCommand() of each button and call the respective getActionCommand from the actionPerformed. Using constants to define the actions would be a good approach in my opinion. A small sample as follows;
public class SwingTest extends JFrame implements ActionListener{
public SwingTest()
{
JButton btnOne = new JButton("test one");
btnOne.addActionListener(this);
btnOne.setActionCommand("TestOne");
JButton btnTwo = new JButton("test two");
btnTwo.addActionListener(this);
btnTwo.setActionCommand("TestTwo");
this.setLayout(new FlowLayout());
this.getContentPane().add(btnOne);
this.getContentPane().add(btnTwo);
}
public static void main(String[] args) {
SwingTest t = new SwingTest();
t.pack();
t.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
instead of having it be
e.getSource() == Aster
change it to:
e.getSource().equals(Aster)
it looks like the same thing, but it will give you the results your looking for...
because .equals() is checking for the state of an object, where as '==' is checking the actually instances.
http://www.javabeat.net/qna/13-what-is-difference-between-equals-and-/

Categories

Resources