Separating logic from GUI in java - java

I'm having really hard time splitting up my class into two classes, right now I have the GUI and the logic all together in one class and I want it to be separate, I had a read on objects and classes but I still don't understand how I would split it up for my example, my only "logic" in this program is 3 inner classes which determine what the buttons do (Delete record, save record etc...)
Heres my code, can anyone point me in the right direction?
private String name;
private String surname;
private String phone;
private String address;
private String postcode;
private String email;
static String summary;
private JPanel panel;
private JPanel buttonspanel;
private JPanel labelspanel;
private JPanel tablepanel;
private JFrame frame;
private JLabel lblName;
private JLabel lblEmail;
private JLabel lblPostcode;
private JLabel lblAddress;
private JLabel lblSurname;
private JLabel lblPhone;
private JTextField txtName;
private JTextField txtSurname;
private JTextField txtPostcode;
private JTextField txtEmail;
private JTextField txtPhone;
private JTextField txtAddress;
private JButton btnSave;
private JButton btnUpload;
private JButton btnDelete;
String columns[] = {"Name","Surname","Phone","Address","Postcode","Email"};
private DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
public AddressBook() {
createForm();
createLabels();
createTextField();
createButton();
createTable();
frame.add(panel);
frame.setVisible(true);
}
public void createLabels(){
lblName = new JLabel ("Name");
lblName.setBounds(10, 30, 100, 20);
labelspanel.add (lblName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(10, 50, 100, 20);
labelspanel.add (lblSurname);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
labelspanel.add (lblAddress);
lblPhone = new JLabel ("Phone");
lblPhone.setBounds(10, 90, 100, 20);
labelspanel.add (lblPhone);
lblPostcode = new JLabel ("Postcode");
lblPostcode.setBounds(10, 110, 100, 20);
labelspanel.add (lblPostcode);
lblEmail = new JLabel ("Email");
lblEmail.setBounds(10, 130, 100, 20);
labelspanel.add (lblEmail);
}
public void createTextField(){
txtName = new JTextField (null);
txtName.setBounds(110, 30, 150, 20);
labelspanel.add (txtName);
txtSurname = new JTextField (null);
txtSurname.setBounds(110, 50, 150, 20);
labelspanel.add (txtSurname);
txtAddress = new JTextField (null);
txtAddress.setBounds(110, 70, 150, 20);
labelspanel.add (txtAddress);
txtPhone = new JTextField (null);
txtPhone.setBounds(110, 90, 150, 20);
labelspanel.add (txtPhone);
txtPostcode = new JTextField (null);
txtPostcode.setBounds(110, 110, 150, 20);
labelspanel.add (txtPostcode);
txtEmail = new JTextField (null);
txtEmail.setBounds(110, 130, 150, 20);
labelspanel.add (txtEmail);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Address Book");
frame.setSize(800,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
buttonspanel = new JPanel();
buttonspanel.setLayout(new FlowLayout());
buttonspanel.setBorder (BorderFactory.createEtchedBorder ());
labelspanel = new JPanel();
labelspanel.setBorder (BorderFactory.createEtchedBorder ());
labelspanel.setLayout(null);
labelspanel.setPreferredSize(new Dimension (400,200));
tablepanel = new JPanel();
tablepanel.setLayout(new BorderLayout());
panel.add(buttonspanel);
panel.add(labelspanel);
panel.add(tablepanel);
}
public void createButton(){
btnSave = new JButton ("Save to a file");
btnSave.addActionListener(new SaveHandler());
buttonspanel.add (btnSave);
btnDelete = new JButton ("Delete from the table");
btnDelete.addActionListener(new DeleteHandler());
buttonspanel.add (btnDelete);
btnUpload = new JButton ("Add details to table");
btnUpload.addActionListener(new AddHandler());
buttonspanel.add (btnUpload);
}
public void createTable(){
model.setColumnIdentifiers(columns);
JScrollPane scrollPane = new JScrollPane(table);
tablepanel.add(scrollPane, BorderLayout.SOUTH);
}
class SaveHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave)
{
name = ("");
surname = ("");
phone = ("");
address = ("");
postcode = ("");
email = ("");
name = txtName.getText();
surname = txtSurname.getText();
phone = txtPhone.getText();
address = txtAddress.getText();
postcode = txtPostcode.getText();
email = txtEmail.getText();
summary = ("Name:" +name)+("Surname:" +surname)+("Phone:" + phone)+("Address:" + address)+("Postcode:" + postcode)+("Email:" + email);
String saveFile = summary;
try {
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("userinfo.txt"), true));
reader.write(saveFile);
reader.newLine();
reader.close();
JOptionPane.showMessageDialog(frame, "The details were sucessfuly saved");
} catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Something went wrong, please try again");
}
}
}
}
class AddHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnUpload)
{
String nameRow = txtName.getText();
String surnameRow = txtSurname.getText();
String phoneRow = txtPhone.getText();
String addressRow = txtAddress.getText();
String postcodeRow = txtPostcode.getText();
String emailRow = txtEmail.getText();
Object[] row = {nameRow,surnameRow,phoneRow,addressRow,postcodeRow,emailRow};
model.addRow(row);
}
}
}
class DeleteHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnDelete)
{
int i = table.getSelectedRow();
if(i >= 0){
model.removeRow(i);
}
}
}
}
public static void main(String[] args) {
new AddressBook();
}

class GUI{
Jbutton btnsave;
Jbutton Delete;
jbutton update
HandleAll btnHandler = new HandleAll();
btnSave.addActionListener(btnHandler);
Deletea.ddActionListener(btnHandler);
update.addActionListener(btnHandler);
class HandleAll implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave){
//on click save button
}else if(e.getSource()==Delete){
//on click delete button
}else if(e.getSource()==update){
//on click update button
}
}
}
}
you can follow above approach to seperate logic from Gui . by the way i have made the HandleAll class a inner class. HandleAll implements actionListner interface . on every button press actionperformed on this class will get call but by selecting e.getsource you can check which button was pressed exactly.try this approach

Related

Why is my JTable not showing?

I'm trying to create a address book and all I currently need is a table to store the data, however I cannot get it to display on the panel, any ideas why? I've got a method which should be creating the table on execution but its not.
private String name;
private String surname;
private String phone;
private String address;
static String summary;
private JPanel panel;
private JFrame frame;
private JLabel lblName;
private JLabel lblAddress;
private JLabel lblSurname;
private JLabel lblPhone;
private JTextField txtName;
private JTextField txtSurname;
private JTextField txtPhone;
private JTextField txtAddress;
private JButton btnSave;
private JButton btnUpload;
private JButton btnDelete;
String columns[] = {"Name","Surname","Phone","Address"};
String[][] data =
{{"human", "bean","07443244","somewhere"},
{"Max", "Kenny","044353534","Somewhere"}};
public AddressBook() {
createForm();
createLabels();
createTextField();
createButton();
createTable();
frame.add(panel);
frame.setVisible(true);
}
public void createLabels(){
lblName = new JLabel ("Name");
lblName.setBounds(10, 30, 100, 20);
panel.add (lblName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(10, 50, 100, 20);
panel.add (lblSurname);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
lblPhone = new JLabel ("Phone");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
}
public void createTextField(){
txtName = new JTextField (null);
txtName.setBounds(110, 30, 150, 20);
panel.add (txtName);
txtSurname = new JTextField (null);
txtSurname.setBounds(110, 50, 150, 20);
panel.add (txtSurname);
txtAddress = new JTextField (null);
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
txtPhone = new JTextField (null);
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
}
public void createForm(){
panel = new JPanel();
panel.setBorder (BorderFactory.createLineBorder (Color.RED, 3));
panel.setLayout(null);
frame = new JFrame();
frame.setTitle("Address Book");
frame.setSize(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createButton(){
btnSave = new JButton ("Save to a file");
btnSave.setBounds(50, 200, 200, 20);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnDelete = new JButton ("Delete from the table");
btnDelete.setBounds(50, 300, 200, 20);
panel.add (btnDelete);
btnUpload = new JButton ("Upload file to table");
btnUpload.setBounds(50, 400, 200, 20);
panel.add (btnUpload);
}
public void createTable(){
JTable table = new JTable(data, columns);
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
panel.add(table);
}
class SaveHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave)
{
name = ("");
surname = ("");
phone = ("");
address = ("");
name = txtName.getText();
surname = txtSurname.getText();
phone = txtPhone.getText();
address = txtAddress.getText();
summary = ("Name:" +name)+(surname)+("Phone:" + phone)+("Address:" + address);
String saveFile = summary;
try {
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("userinfo.txt"), true));
reader.write(saveFile);
reader.newLine();
reader.close();
JOptionPane.showMessageDialog(frame, "The details were sucessfuly saved");
} catch (IOException e1) {
e1.printStackTrace();
}
}
} }
public static void main(String[] args) {
new AddressBook();
}
}
panel.setLayout(null);
You chose to use no layout manager and handle all of the layout yourself.
JTable table = new JTable(data, columns);
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
However, you did not specify a size and position for the JTable.
I recommend learning to use the layout managers instead. It will work better, it will handle the user resizing the window, and will make the code more maintainable.

Inserting image through event handling?

I am encountering problems with event handling in java.
I want to add the image1 if button 1 is pressed, image2 if button 2 is pressed, et cetera.
This is my code till now; Can anyone help? This code doesn't compile.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ImageIcon;
public class MyPanel extends JPanel {
private JLabel jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JButton jcomp4;
private JButton jcomp5;
private JButton jcomp6;
private JButton jcomp7;
private JButton jcomp8;
private JButton jcomp9;
private ImageIcon image1;
private ImageIcon image2;
private ImageIcon image3;
private ImageIcon image4;
private ImageIcon image5;
private ImageIcon image6;
private ImageIcon image7;
private ImageIcon image8;
public MyPanel() {
//construct components
image1 = new ImageIcon(getClass().getResource("hang1.jpg"));
image2 = new ImageIcon(getClass().getResource("hang2.jpg"));
image3 = new ImageIcon(getClass().getResource("hang3.jpg"));
image4 = new ImageIcon(getClass().getResource("hang4.jpg"));
image5 = new ImageIcon(getClass().getResource("hang5.jpg"));
image6 = new ImageIcon(getClass().getResource("hang6.jpg"));
image7 = new ImageIcon(getClass().getResource("hang7.jpg"));
image8 = new ImageIcon(getClass().getResource("hang8.jpg"));
jcomp1 = new JLabel (image1);
jcomp2 = new JButton ("1");
jcomp3 = new JButton ("2");
jcomp4 = new JButton ("3");
jcomp5 = new JButton ("4");
jcomp6 = new JButton ("5");
jcomp7 = new JButton ("6");
jcomp8 = new JButton ("7");
jcomp9 = new JButton ("8");
//events
jcomp2.setActionCommand("1");
jcomp3.setActionCommand("2");
jcomp4.setActionCommand("3");
jcomp5.setActionCommand("4");
jcomp6.setActionCommand("5");
jcomp7.setActionCommand("6");
jcomp8.setActionCommand("7");
jcomp9.setActionCommand("8");
jcomp2.addActionListener(new ButtonClickListener());
jcomp3.addActionListener(new ButtonClickListener());
jcomp4.addActionListener(new ButtonClickListener());
jcomp5.addActionListener(new ButtonClickListener());
jcomp6.addActionListener(new ButtonClickListener());
jcomp7.addActionListener(new ButtonClickListener());
jcomp8.addActionListener(new ButtonClickListener());
jcomp9.addActionListener(new ButtonClickListener());
//adjust size and set layout
setPreferredSize(new Dimension(624, 537));
setLayout(null);
//add components
add(jcomp2);
add(jcomp3);
add(jcomp4);
add(jcomp5);
add(jcomp6);
add(jcomp7);
add(jcomp8);
add(jcomp9);
// set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds(15, 10, 595, 350);
jcomp2.setBounds(35, 375, 100, 25);
jcomp3.setBounds(190, 375, 100, 25);
jcomp4.setBounds(320, 375, 100, 25);
jcomp5.setBounds(465, 375, 100, 25);
jcomp6.setBounds(35, 450, 100, 25);
jcomp7.setBounds(190, 450, 100, 25);
jcomp8.setBounds(320, 450, 100, 25);
jcomp9.setBounds(465, 450, 100, 25);
}
class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
jcomp1.set(image1);
}
}
}
public static void main (String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
I believe you are trying to get something like this:
public class MyPanel extends JPanel {
private JLabel label;
private JButton[] buttons = new JButton[8];
private ImageIcon[] images = new ImageIcon[8];
public MyPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(2, 4, 15, 10));
for (int i = 0; i < images.length; i++) {
images[i] = new ImageIcon(getClass().getResource(i+1 + ".png"));
buttons[i] = new JButton(String.valueOf(i+1));
buttons[i].setActionCommand(String.valueOf(i+1));
buttons[i].addActionListener(new ButtonClickListener());
buttonPanel.add(buttons[i]);
}
label = new JLabel(images[0]);
setLayout(new BorderLayout());
add(label);
add(buttonPanel, BorderLayout.PAGE_END);
}
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setIcon(images[Integer.parseInt(e.getActionCommand()) - 1]);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible(true);
}
}
Notes:
Don't forget to change the image file name.
You can play with the layout manager to get what you want.
I removed setPreferredSize(new Dimension(624, 537)); because you didn't specify a resize behavior which would make this line meaningless. pack() would take care of the sizes for you.
Set the icon of the button or label. To do this, you need to create an ImageIcon, which has multiple constructors to create from a filename or a loaded image.
jcomp1.setIcon(new ImageIcon(...));

The java applet appears blank

I've been working at this problem for hours now, with no results. I cannot seem to get the applet to display properly when viewing the HTML page OR when running the applet through Eclipse. It is always blank. I've been searching for a long time now and decided just to ask.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet{
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public JPanel createContentPane(){
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
//posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
topicGUI.add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150,25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
postPanel.add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70,15);
username.setHorizontalAlignment(0);
postPanel.add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40,15);
topic.setHorizontalAlignment(0);
postPanel.add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70,15);
paragraph.setHorizontalAlignment(0);
postPanel.add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
postPanel.add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
postPanel.add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane (paragraphArea);
scrollParagraph.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
postPanel.add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal + "/n" + paragraphArea + "/n";
}
});
postPanel.add(submitButton);
setVisible(true);
return topicGUI;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("");
Topics display = new Topics();
frame.setContentPane(display.createContentPane());
frame.setSize(500, 270);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
In order to run as an applet, you need to override the init method. You don't need a main method. Just add all you components inside the init method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet {
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public void init() {
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
// posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150, 25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70, 15);
username.setHorizontalAlignment(0);
add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40, 15);
topic.setHorizontalAlignment(0);
add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70, 15);
paragraph.setHorizontalAlignment(0);
add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane(paragraphArea);
scrollParagraph
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal
+ "/n" + paragraphArea + "/n";
}
});
add(submitButton);
}
}

Trouble Updating AbstractTableModel from another Class

I'm trying to update a JTable that pulls in data from an ArrayList. I have two frames in my program. The first frame is a JTable (AbstractTableModel) that displays the contents of the ArrayList. I click the "New" button on that frame to bring up the second window, which lets me add to the aforementioned ArrayList. When I click my "Save" button, the second window closes and the first is supposed to refresh with the new row. I don't have any syntactical errors in my code, and it looks conceptually right. I think the first place to start troubleshooting would be in the NoteCntl class. I'm under the impression that getNoteTableUI() should update the view with the new data when it's called, but I'm stumped as to what's going on. I'm new to the concept of Model View Controller, but I'd like to follow that as closely as possible.
Here is the Controller class:
public class NoteCntl {
private NoteTableModel theNoteTableModel = new NoteTableModel();;
private NoteTableUI theNoteTableUI;
private NoteDetailUI theNoteDetailUI;
public NoteCntl(){
theNoteTableUI = new NoteTableUI(this);
}
public NoteTableModel getNoteTableModel(){
return theNoteTableModel;
}
public void getNoteDetailUI(Note theNote){
if (theNoteDetailUI == null || theNote == null){
theNoteDetailUI = new NoteDetailUI(this,theNote);
}
else{
theNoteDetailUI.setVisible(true);
}
}
public NoteTableUI getNoteTableUI(){
theNoteTableModel.fireTableDataChanged(); //why doesn't this do anything?
theNoteTableUI.setVisible(true);
return theNoteTableUI;
}
public void deleteNote(int noteToDelete){
theNoteTableModel.removeRow(noteToDelete);
}
}
The First UI (Table):
public class NoteTableUI extends JFrame{
NoteTableModel noteModel;
NoteCntl theNoteCntl;
JPanel buttonPanel;
JPanel tablePanel;
JTable theNoteTable;
JScrollPane theScrollPane;
JButton backButton;
JButton deleteButton;
JButton editButton;
JButton newButton;
public NoteTableUI(NoteCntl theParentNoteCntl){
theNoteCntl = theParentNoteCntl;
this.initComponents();
this.setSize(400, 500);
this.setLocationRelativeTo(null);
this.setTitle("NoteTableUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
buttonPanel = new JPanel();
tablePanel = new JPanel();
backButton = new JButton("Back");
newButton = new JButton("New");
newButton.addActionListener(new newButtonListener());
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new deleteButtonListener());
noteModel = theNoteCntl.getNoteTableModel();
theNoteTable = new JTable(theNoteCntl.getNoteTableModel());
theScrollPane = new JScrollPane(theNoteTable);
theNoteTable.setFillsViewportHeight(true);
tablePanel.add(theScrollPane);
buttonPanel.add(backButton);
buttonPanel.add(deleteButton);
buttonPanel.add(editButton);
buttonPanel.add(newButton);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(tablePanel, BorderLayout.CENTER);
}
public class deleteButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int selectedRow = theNoteTable.getSelectedRow();
if (selectedRow == -1){
System.out.println("No row selected");
}
else{
noteModel.removeRow(selectedRow);
}
revalidate();
repaint();
}
}
public class newButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
NoteTableUI.this.setVisible(false);
NoteTableUI.this.theNoteCntl.getNoteDetailUI(null);
/*
NoteDetailCntl theNoteDetailCntl = new NoteDetailCntl();
lastRow++;
long newRow = lastRow;
noteModel.addRow(newRow, 0, "", "");
revalidate();
repaint();
*/
}
}
The 2nd UI (Detail editor)
public class NoteDetailUI extends JFrame{
private final int FRAME_WIDTH = 700;
private final int FRAME_HEIGHT = 500;
private final int FIELD_WIDTH = 10;
JButton saveButton;
JButton backButton;
JTextField idField;
JTextField dateField;
JTextField nameField;
JTextField descriptionField;
JTextArea noteDetail;
JLabel idLabel;
JLabel dateLabel;
JLabel nameLabel;
JLabel descriptionLabel;
JPanel buttonPanel;
JPanel textFieldPanel;
JPanel textAreaPanel;
JPanel mainPanel;
NoteTableModel theNoteTableModel;
NoteDetailCntl theNoteDetailCntl;
NoteCntl theNoteCntl;
Note theCurrentNote;
public NoteDetailUI(){
this.initComponents();
this.setSize(FRAME_WIDTH,FRAME_HEIGHT);
this.setLocationRelativeTo(null);
this.setTitle("NoteDetailUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public NoteDetailUI(NoteCntl parentNoteCntl, Note theSelectedNote){
theNoteCntl = parentNoteCntl;
theCurrentNote = theSelectedNote;
this.initComponents();
this.setSize(400,500);
this.setLocationRelativeTo(null);
this.setTitle("Note");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
saveButton = new JButton("Save");
saveButton.addActionListener(new saveButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new backButtonListener());
idField = new JTextField(FIELD_WIDTH);
theNoteTableModel = new NoteTableModel();
idField.setText("10");
idField.setEditable(false);
dateField = new JTextField(FIELD_WIDTH);
dateField.setText("20131108");
nameField = new JTextField(FIELD_WIDTH);
nameField.setText("Untitled");
descriptionField = new JTextField(FIELD_WIDTH);
descriptionField.setText("not described");
idLabel = new JLabel("ID");
dateLabel = new JLabel("Date");
nameLabel = new JLabel("Name");
descriptionLabel = new JLabel("Description");
noteDetail = new JTextArea(25,60);
buttonPanel = new JPanel();
textFieldPanel = new JPanel();
textAreaPanel = new JPanel();
mainPanel = new JPanel(new BorderLayout());
buttonPanel.add(backButton);
buttonPanel.add(saveButton);
textFieldPanel.add(idLabel);
textFieldPanel.add(idField);
textFieldPanel.add(dateLabel);
textFieldPanel.add(dateField);
textFieldPanel.add(nameLabel);
textFieldPanel.add(nameField);
textFieldPanel.add(descriptionLabel);
textFieldPanel.add(descriptionField);
textAreaPanel.add(noteDetail);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.add(textAreaPanel, BorderLayout.CENTER);
add(mainPanel);
}
public ArrayList<String> getNoteDetails(){
ArrayList<String> newData = new ArrayList<String>();
newData.add(idField.getText());
newData.add(dateField.getText());
newData.add(nameField.getText());
newData.add(descriptionField.getText());
return newData;
}
public class saveButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
/*
* Access the noteTableData array in NoteTableModel
* Add the newData fields in order
*/
if(theCurrentNote == null){
int newNoteNumber = Integer.parseInt(NoteDetailUI.this.idField.getText());
int newNoteDate = Integer.parseInt(NoteDetailUI.this.dateField.getText());
String newNoteName = NoteDetailUI.this.nameField.getText();
String newNoteDescription = NoteDetailUI.this.descriptionField.getText();
NoteDetailUI.this.theCurrentNote = new EssayNote(newNoteNumber,newNoteDate,newNoteName,newNoteDescription);
NoteDetailUI.this.setVisible(false);
NoteDetailUI.this.dispose();
NoteDetailUI.this.theNoteCntl.getNoteTableUI();
}
else{
//if it's a current Note
}
//Refresh the JTable
}
}
public class backButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
Thanks for all the help. I can provide the other classes if you want to just run the program and see what's happening, but I suspect it's either a problem with the fireTableDataChanged() call in the controller class or a problem with updating the contents of the ArrayList in the SaveButtonListener.

Working with ActionListeners and cannot set text field to not visible

I'm just trying to make a text field not visible until I click one of the numbered buttons. Ignore my poor spacing and lack of commenting as this is an early, rough draft. The text field is called inputField1 and I want it to be set Visible when I click the button labeled 1. Thanks
import java.lang.String.*;
import java.lang.Exception.*;
import java.util.EventObject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Airplanes extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 330;
private static final int FRAME_HEIGHT = 300;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 300;
private static final int BUTTON_WIDTH = 50;
private static final int BUTTON_HEIGHT = 30;
private JTextField inputLine1;
private JButton oneButton;
private JButton twoButton;
private JButton threeButton;
private JButton fourButton;
private JButton fiveButton;
private JButton sixButton;
private JButton sevenButton;
private JButton eightButton;
private JButton nineButton;
private JButton tenButton;
private JButton elevenButton;
private JButton twelveButton;
public static void main(String[] args) {
Airplanes airplanes = new Airplanes();
airplanes.setVisible(true);
}
#SuppressWarnings("null")
public Airplanes() {
Container contentPane;
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("Island Airways");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.white);
oneButton = new JButton("1");
oneButton.setBounds(10, 100, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(oneButton);
twoButton = new JButton("2");
twoButton.setBounds(10, 140, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(twoButton);
threeButton = new JButton("3");
threeButton.setBounds(60, 100, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(threeButton);
fourButton = new JButton("4");
fourButton.setBounds(60, 140, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(fourButton);
fiveButton = new JButton("5");
fiveButton.setBounds(110, 100, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(fiveButton);
sixButton = new JButton("6");
sixButton.setBounds(110, 140, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(sixButton);
sevenButton = new JButton("7");
sevenButton.setBounds(160, 100, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(sevenButton);
eightButton = new JButton("8");
eightButton.setBounds(160, 140, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(eightButton);
nineButton = new JButton("9");
nineButton.setBounds(210, 100, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(nineButton);
tenButton = new JButton("10");
tenButton.setBounds(210, 140, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(tenButton);
elevenButton = new JButton("11");
elevenButton.setBounds(260, 100, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(elevenButton);
JButton twelveButton = new JButton("12");
twelveButton.setBounds(260, 140, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(twelveButton);
JButton firstClass = new JButton("First Class");
firstClass.setBounds(50, 30, 100, 30);
contentPane.add(firstClass);
JButton coach = new JButton("Coach");
coach.setBounds(175, 30, 100, 30);
contentPane.add(coach);
inputLine1 = new JTextField();
inputLine1.setBounds(70, 200, 135, 30);
contentPane.add(inputLine1);
inputLine1.setVisible(false);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("First Class")) {
inputLine1.setVisible(true);
if (buttonText.equals("1")) {
}
}
}
}
}
You have implemented ActionListener but your buttons are not attached to any Listener, hence its not invoking your actionPerformed method.
You need to do add listners to your buttons like this:
oneButton.addActionListener(this);
Then change your actionPerfomed like:
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("First Class")) {
//do something
} else if (buttonText.equals("1")) {
inputLine1.setVisible(true);
}
}
}
Read this tutorial
When you are implementing ActionListener
you have to implement it's methods
you have to add that listener to a particular component you want.
You forgot to do second one.
oneButton.addActionListener(this);
you add the following code to your actionPerformed method.
if (buttonText.equals("1")) {
inputLine1.setVisible(true);
}

Categories