How to add component to JTabbedPane - java

So i have two classes, one called ApplicationViewer and one called PetshopOverview. I want the applicationviewer to display some information in two tabs using JTabbedPane. I need to get some information from another class which extends JScrollPane, however, the tab does not display the information. I have look at various answers but it seems that mine does not work. See code below:
public class ApplicationViewer extends JFrame{
public void viewer(final ArrayList<PetShop> petshops){
lookAndFeel(); //this calls the look and feel method which changes the looks of the frame.
PetshopOverview ov = new PetshopOverview(petshops);
Object[] columnNames = {"Name", "Address", "Phone Number", "Website", "Opening Time"}; //declaring columns names
Object[][] rowData = new Object[petshops.size()][columnNames.length]; //initializing rows.
DefaultTableModel listTableModel;
for (int i = 0; i < petshops.size(); i++) { //this for loop adds data from the arraylist to each coloumn.
rowData[i][0] = petshops.get(i).getName();
rowData[i][1] = petshops.get(i).getAddress();
rowData[i][2] = petshops.get(i).getPhoneNumber();
rowData[i][3] = petshops.get(i).getWebsite();
rowData[i][4] = petshops.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
JPanel panelLB = new JPanel();
JPanel panel = new JPanel();
JPanel panelBT = new JPanel();
JButton btnViewSum = new JButton("View Summary");
JButton btnExp = new JButton("Export table data");
//---------------------JTABLE AND JFRAME (adding adding table, panels and buttons to the jframe)--------------------------------------------------------
JTable listTable;
listTable = new JTable(listTableModel);
listTable.setRowSelectionAllowed(true);
JScrollPane scroll = new JScrollPane(listTable);
scroll.setViewportView(listTable);
JFrame frame = new JFrame("PetShops");
JTabbedPane tab = new JTabbedPane();
tab.addTab("Tab1", scroll);
tab.addTab("Tab2", new PetshopOverview(petshops));
JLabel lb = new JLabel("Welcome to Pet shop app");
panelBT.add(lb);
panelBT.add(btnExp);
panelBT.add(btnViewSum);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.add(panelBT);
frame.add(tab);
frame.getContentPane().add(panelBT, java.awt.BorderLayout.NORTH);
frame.getContentPane().add(tab, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
}
This is the other class PetshopOverview:
public class PetshopOverview extends JScrollPane{
public PetshopOverview(ArrayList<PetShop> petshopsSum){
Object[] columnNames = {"Name", "Opening Time"};
Object[][] rowData = new Object[petshopsSum.size()][columnNames.length];
DefaultTableModel listTableModel;
int size= petshopsSum.size();
for (int i = 0; i < size; i++) {
rowData[i][0] = petshopsSum.get(i).getName();
rowData[i][1] = petshopsSum.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
//-------------------------JTABLE AND JFRAME--------------------------
JTable listTable;
listTable = new JTable(listTableModel);
Petshop:
public class PetShop {
private String name, address, phoneNumber, website, openingTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public PetShop(String sName, String sAddress, String sPhoneNumber, String sWebsite, String sOpeningTime){
this.name = sName;
this.address = sAddress;
this.phoneNumber = sPhoneNumber;
this.website = sWebsite;
this.openingTime = sOpeningTime;
}
#Override
public String toString(){
return getName()+"\n"
+getAddress().replaceAll(":", "").replaceFirst("", " ")+"\n"
+getPhoneNumber()+"\n"
+getWebsite().replaceFirst("", " ")+"\n"
+getOpeningTime().replaceFirst(",", "").replaceFirst("", " ")+"\n\n";
}
public PetShop(String sName, String sOpeningTime){
this.name = sName;
this.openingTime = sOpeningTime;
}
public String toString2 (){
return getName()+": "
+getOpeningTime().replaceFirst(",", "").replaceFirst("", " ");
}
}

You're almost there i think you just need to adjust the frame and add your components to it. So in ApplicationViewer instead of creating a new JFrame add your components to ApplicationViewer which is already a JFrame. And on PetShopOverview you need to set the ViewportView of the PetShopOverview to the listTable.
Here's an example :
PetShop
public class PetShop {
String name;
String openingTime;
String address;
String phoneNumber;
String website;
public PetShop(String name, String openingTime, String address, String phoneNumber, String website) {
this.name = name;
this.openingTime = openingTime;
this.address = address;
this.phoneNumber = phoneNumber;
this.website = website;
}
public String getName() {
return name;
}
public String getOpeningTime() {
return openingTime;
}
public String getAddress() {
return address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getWebsite() {
return website;
}}
PetShopOverview:
public class PetShopOverview extends JScrollPane {
public PetShopOverview(ArrayList<PetShop> petshopsSum) {
Object[] columnNames = { "Name", "Opening Time" };
Object[][] rowData = new Object[petshopsSum.size()][columnNames.length];
DefaultTableModel listTableModel;
int size = petshopsSum.size();
for (int i = 0; i < size; i++) {
rowData[i][0] = petshopsSum.get(i).getName();
rowData[i][1] = petshopsSum.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
// -------------------------JTABLE AND JFRAME--------------------------
JTable listTable;
listTable = new JTable(listTableModel);
this.setViewportView(listTable);
}}
ApplicationViewer:
public class ApplicationViewer extends JFrame {
public ApplicationViewer(ArrayList<PetShop> petshops) {
viewer(petshops);
}
public void viewer(final ArrayList<PetShop> petshops) {
PetShopOverview ov = new PetShopOverview(petshops);
Object[] columnNames = { "Name", "Address", "Phone Number", "Website", "Opening Time" }; // declaring columns
// names
Object[][] rowData = new Object[petshops.size()][columnNames.length]; // initializing rows.
DefaultTableModel listTableModel;
for (int i = 0; i < petshops.size(); i++) { // this for loop adds data from the arraylist to each coloumn.
rowData[i][0] = petshops.get(i).getName();
rowData[i][1] = petshops.get(i).getAddress();
rowData[i][2] = petshops.get(i).getPhoneNumber();
rowData[i][3] = petshops.get(i).getWebsite();
rowData[i][4] = petshops.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
JPanel panelLB = new JPanel();
JPanel panel = new JPanel();
JPanel panelBT = new JPanel();
JButton btnViewSum = new JButton("View Summary");
JButton btnExp = new JButton("Export table data");
// ---------------------JTABLE AND JFRAME (adding adding table, panels and buttons to the
// jframe)--------------------------------------------------------
JTable listTable;
listTable = new JTable(listTableModel);
listTable.setRowSelectionAllowed(true);
JScrollPane scroll = new JScrollPane(listTable);
scroll.setViewportView(listTable);
JTabbedPane tab = new JTabbedPane();
tab.addTab("Tab1", scroll);
tab.addTab("Tab2", new PetShopOverview(petshops));
JLabel lb = new JLabel("Welcome to Pet shop app");
panelBT.add(lb);
panelBT.add(btnExp);
panelBT.add(btnViewSum);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.add(panelBT);
this.add(tab);
this.getContentPane().add(panelBT, java.awt.BorderLayout.NORTH);
this.getContentPane().add(tab, java.awt.BorderLayout.CENTER);
this.setVisible(true);
}}
Main method :
public static void main(String[] args) {
ArrayList<PetShop> p = new ArrayList<PetShop>();
p.add(new PetShop("a", "9", "street 1", "123", "www.a.com"));
p.add(new PetShop("b", "10", "street 2", "456", "www.b.com"));
p.add(new PetShop("c", "11", "street 3", "789", "www.c.com"));
p.add(new PetShop("d", "12", "street 4", "000", "www.d.com"));
ApplicationViewer v = new ApplicationViewer(p);
v.setVisible(true);
}
p.s. i just created an arbitrary PetShop class

Related

JTable in a JDialog doesn't appear

I wanted to set a JTable of ArrayList content in a new JDialog. I debugged the code and the table model has its columns and rows set up, but JDialog doesn't show anything. I checked the similar questions and they all point that setVisible(true) should be being at the end. In my case, it already is. How can I show the JTable in that JDialog (including the data which comes from the ArrayList - that part should already be working), basically it's currently empty, there is no table at all.
public class Main {
public static void main(String[] args) {
MainWindow wnd = new MainWindow();
}
}
public class MainWindow extends JFrame implements ActionListener {
private List<Movie> movies = new ArrayList<Movie>();
// Създаване на променливи за отделните контроли
private JLabel label1;
private JTextField tf1;
private JLabel label2;
private JTextField tf2;
private JLabel label3;
private JTextField tf3;
private JLabel label4;
private JComboBox combo1;
private JLabel label5;
private JTextField tf5;
private JButton btn1;
private JButton btn2;
public MainWindow() {
setSize(500, 300);
// при натискане на Х на проореца, да се затвори приложението
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new GridLayout(0, 2, 10, 10));
// Добавяме инв. номер в контейнера
label1 = new JLabel("Инвертарен номер");
tf1 = new JTextField();
window.add(label1);
window.add(tf1);
// Добавяме заглавие в контейнера
label2 = new JLabel("Заглавие");
tf2 = new JTextField();
window.add(label2);
window.add(tf2);
// Добавяме режисьор в контейнера
label3 = new JLabel("Режисьор");
tf3 = new JTextField();
window.add(label3);
window.add(tf3);
// Добавяме жанр в контейнера
label4 = new JLabel("Жанр");
String[] items = { "Комедия", "Екшън", "Драма" };
combo1 = new JComboBox(items);
window.add(label4);
window.add(combo1);
// Добавяме година на излизане в контейнера
label5 = new JLabel("Година на излизане");
tf5 = new JTextField();
window.add(label5);
window.add(tf5);
// Добавяме бутоните в контейнера
btn1 = new JButton("Справка");
btn2 = new JButton("Добави");
window.add(btn1);
window.add(btn2);
// При кликването върху бутоните, добавя евент, който се хендълва по-долу
btn1.addActionListener(this);
btn2.addActionListener(this);
setVisible(true);
}
// Извиква се при натискане на бутон, регистриран с addActionListener(this)
public void actionPerformed(ActionEvent e) {
// Извиква се, когато се кликне на бутон `Справки`.
if (e.getSource() == btn1)
{
// Показване на диалогов прозорец
new Dialog(movies);
}
// Извиква се, когато се кликне на бутон `Добавяне`.
else if (e.getSource() == btn2)
{
// Запазване на въведените данни в динамичния масив `movies`.
String id = tf1.getText();
String title = tf2.getText();
String director = tf3.getText();
String genre = tf5.getText();
String year = combo1.getSelectedItem().toString();
System.out.println("Инвертарен номер: " + id);
System.out.println("Заглавие: " + title);
System.out.println("Режисьор: " + director);
System.out.println("Жанр: " + genre);
System.out.println("Година на излизане: " + year);
Movie movie = new Movie();
movie.setId(id);
movie.setTitle(title);
movie.setDirector(director);
movie.setGenre(genre);
movie.setYear(year);
movies.add(movie);
System.out.println("Успешно добавен!");
}
}
}
public class Movie {
private String id;
private String title;
private String director;
private String genre;
private String year;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
public class Dialog extends JDialog {
private JTable table1;
public Dialog(List<Movie> movies) {
setTitle("Справка");
setSize(500, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Container window = getContentPane();
window.setLayout(null);
String[] col = new String[] { "Инв. номер", "Заглавие", "Режисьор", "Жанр", "Година на излизане" };
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
for (int i = 0; i < movies.size(); i++) {
String id = movies.get(i).getId();
String title = movies.get(i).getTitle();
String director = movies.get(i).getDirector();
String genre = movies.get(i).getGenre();
String year = movies.get(i).getYear();
Object[] data = { id, title, director, genre, year };
tableModel.addRow(data);
}
//TableModel tableModel = new DefaultTableModel(movies.toArray(new Object[][] {}), columns.toArray());
table1 = new JTable(tableModel);
window.add(table1);
setVisible(true);
}
}
Here are a few things that I would change in your code. (Only considering the part regarding your dialog)
window.setLayout(null); // (1)
Don't use null layout. Learn to use appropriate Layout Managers, as swing was designed to be used with in conjunction with these. In your case, you can simply keep the default layout used by the JDialog, as you only have the JTable displayed anyways.
window.add(table1); // (2)
JTables are best used in combination in a JScrollPane, as this will automatically display the table header without you having to worry about it. Also, consider the How to Use Tables section of the Oracle Swing tutorial for more information on JTable usage.
Also (3), Java Swing applications should be run on the Event Dispatch Thread (see Concurrency in Swing).
Container window = getContentPane();
In your case, there is no need to explicitly retrieve the content pane from the dialog. This is just unnecessary overhead which you should not worry about. Calling add() on the dialog is enough in this case to add the component without having to deal with the content pane.
I took the "Dialog" portion of your code, including a excerpt of your Movie class and created a small working example (while trying not to change too much of your original code):
import java.util.Arrays;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // (3) - run on EDT
Test t = new Test();
List<Movie> movies = Arrays.asList(t.new Movie("Movie1", "Title1"), t.new Movie("Movie2", "Title2"));
MyDialog dialog = t.new MyDialog(movies);
});
}
public class MyDialog extends JDialog {
public MyDialog(List<Movie> movies) {
setTitle("Title");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
String[] col = new String[] { "ID", "Title" };
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
for (int i = 0; i < movies.size(); i++) {
String id = movies.get(i).getId();
String title = movies.get(i).getTitle();
Object[] data = { id, title };
tableModel.addRow(data);
}
JTable table = new JTable(tableModel);
add(new JScrollPane(table)); // (2) - use a JScrollPane to display the table
pack(); // pack the dialog, components are sized according to their preferred size
setVisible(true);
}
}
class Movie {
private String id;
private String title;
public Movie(String id, String title) {
this.id = id;
this.title = title;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
}
}
Result:
Considering these changes, you should be able to update your code to correctly display the JTable in your JDialog.
Sidenote:
I also don't really see a need here to extends JDialog. In your case, it would probably suffice to use a normal JDialog and simply add the JTable to it.

How to count data in jtable and show on the bottom of my gui

I have such an api. It shows JTable with 3 columns. I want that when I insert price and quantity to the jtable result will be seen on the bottom of my jframe. For example I insert data like on the picture and then get the result (2*5)+(2*5)=20. My result will be 20. And this result will be seen on the bottom of the gui window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener{
private static void createAndShowUI() {
JFrame frame = new JFrame("Customer Main");
frame.getContentPane().add(new FuGui(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class FuGui extends JPanel {
FuDisplayPanel displayPanel = new FuDisplayPanel();
FuButtonPanel buttonPanel = new FuButtonPanel();
FuInformationPanel informationPanel = new FuInformationPanel();
public FuGui() {
//JTextField textField;
//textField = new JTextField(20);
//textField.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createHorizontalStrut(10));
bottomPanel.add(informationPanel);
setLayout(new BorderLayout());
add(displayPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
buttonPanel.addInfoBtnAddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = informationPanel.getName();
String price = informationPanel.getPrice();
String quantity = informationPanel.getQuantity();
displayPanel.addRow(name, price, quantity);
}
});
}
}
class FuDisplayPanel extends JPanel {
private String[] COLUMNS = {"Name", "Price", "Quantity"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 1);
private JTable table = new JTable(model);
public FuDisplayPanel() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
}
}
class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public FuButtonPanel() {
add(addInfoButton);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
}
class FuInformationPanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JTextField quantityField = new JTextField(10);
public FuInformationPanel() {
add(new JLabel("Kwota:"));
add(nameField);
add(Box.createHorizontalStrut(10));
// add(new JLabel("Price:"));
// add(priceField);
//add(new JLabel("Quantity:"));
// add(quantityField);
}
public String getName() {
return nameField.getText();
}
public String getPrice() {
return priceField.getText();
}
public String getQuantity() {
return quantityField.getText();
}
}
update your addRow method in class FuDisplayPanel to return the total like this and
public int addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
int total = 0;
for (int count = 0; count < model.getRowCount(); count++){
price = model.getValueAt(count, 1).toString();
quantity = model.getValueAt(count, 2).toString();
if(price != null && !price.trim().equals("") && quantity != null && !quantity.trim().equals("")) {
total += Integer.parseInt(price) * Integer.parseInt(quantity);
}
}
return total;
}
public class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public JLabel total = new JLabel("Total : ");
public FuButtonPanel() {
add(addInfoButton);
add(total);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
public void setTotal(int total) {
this.total.setText("Total : " + total);
}
}
and do this at FuGui.class
int total = displayPanel.addRow(name, price, quantity);
buttonPanel.setTotal(total);
Access the underlying data in the table via the model (Swing fundamental):
TableModel model = table.getModel();
Add a listener to the table model to do the automatic updates:
TableModelListener listener = new TableModelListener(tableChanged(TableModelEvent e) {
// update code here
}};
table.getModel().addTableModelListener(listener);

Displaying the values of an Arraylist with a JTable

I created a class named EmployeeGUI that is able to create any amount of user Employee objects and add them to an arraylist. The problem i have is that i have a JTable at the bottom of my GUI that i want to display all the objects that i've created but in my case the GUI Creates a new Table Object each time it goes through a for loop with the details of an object but as the for loop goes on the new details overwrites the old details rather than being added to the bottom of a jtable. Can anyone help me debug my errors?
Here is my Code
import java.awt.event.*;
public class EmployeeGUI extends JFrame implements ActionListener{
/**
* #param args
*/
JFrame frame;
JButton button1, button2, button3, button4;
JTextField box1, box2, box3;
JLabel label1, label2, label3;
JTable table1;
int length = 0;
ArrayList<Employee> empArray = new ArrayList<Employee>();
public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeGUI empG = new EmployeeGUI();
empG.frame.setVisible(true);
}
public EmployeeGUI()
{
initialize();
}
public void initialize() {
// TODO Auto-generated method stub
frame = new JFrame("A Sample Window");
frame.setBounds(50,50,680,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("F-Name:");
label1.setBounds(30,33,54,25);
frame.getContentPane().add(label1);
box1 = new JTextField();
box1.setBounds(94, 35, 128,20);
frame.getContentPane().add(box1);
label2 = new JLabel("S-Name:");
label2.setBounds(250,33,54,25);
frame.getContentPane().add(label2);
box2 = new JTextField();
box2.setBounds(305, 35, 128,20);
frame.getContentPane().add(box2);
label3 = new JLabel("Phone:");
label3.setBounds(461,33,54,25);
frame.getContentPane().add(label3);
box3 = new JTextField();
box3.setBounds(500, 35, 128,20);
frame.getContentPane().add(box3);
button1 = new JButton("Add Employee");
button1.addActionListener(this);
button1.setBounds(71,131,113,39);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Employee");
button2.addActionListener(this);
button2.setBounds(194,131,128,39);
frame.getContentPane().add(button2);
button3 = new JButton("Display Employee");
button3.addActionListener(this);
button3.setBounds(332,131,128,39);
frame.getContentPane().add(button3);
button4 = new JButton("Quit Program");
button4.addActionListener(this);
button4.setBounds(475,131,113,39);
frame.getContentPane().add(button4);
table1 = new JTable();
table1.setBounds(0,184,664,178);
frame.getContentPane().add(table1);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = ((JButton) e.getSource()).getActionCommand();
if(action.equals("Add Employee"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
int mobile = Integer.parseInt(pNo);
Employee ee = new Employee(fName,lName,mobile);
empArray.add(ee);
length++;
JOptionPane.showMessageDialog(null, "Employee Added");
}
if(action.equals("Remove Employee"))
{
String fName = box1.getText(), lName = box2.getText();
int mobile = Integer.parseInt(box3.getText());
Employee ee = new Employee(fName,lName,mobile);
if(length>0)
{
for(int i=0; i<empArray.size(); i++)
{
if(empArray.get(i).getLName() == ee.getLName())
{
empArray.remove(i);
JOptionPane.showMessageDialog(null, "Employee Removed");
}
}
}
else{
throw new ListEmptyException("List is Empty");
}
}
if(action.equals("Display Employee"))
{
for(int i = 0; i <empArray.size(); i++)
{
table1.setModel(new DefaultTableModel(
new Object[][] {
{empArray.get(i).getFName(),empArray.get(i).getLName(),empArray.get(i).getMobile()}
},
new String[] {
"First Name", "Surname", "Phone Number"
}
));
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
and the Employee Class
public class Employee {
private String fName,lName;
private int mobile;
public Employee(String fName, String lName, int mobile)
{
setFName(fName);
setLName(lName);
setMobile(mobile);
}
private void setMobile(int mobile) {
// TODO Auto-generated method stub
this.mobile = mobile;
}
public void setLName(String lName) {
// TODO Auto-generated method stub
this.lName = lName;
}
public void setFName(String fName) {
// TODO Auto-generated method stub
this.fName = fName;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public int getMobile()
{
return mobile;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getMobile();
}
public void print()
{
System.out.println(toString());
}
}
only comment, longer
see number of table1.setModel(new DefaultTableModel( created in loop for(int i = 0; i <empArray.size(); i++)
new Object[][] {{empArray.get(i).getFName(), empArray.get(i).getLName(),empArray.get(i).getMobile()}}, is converted to DataVector, you lost, haven't access to this array
(if is there reason to hold two the same arrays in your program then) use array based on util.List in AbstractTableModel
the new details overwrites the old details rather than being added to the bottom of a jtable.
First add all the record in a List then set the model just once otherwise it will override the last one in loop.
sample code:
if (action.equals("Display Employee")) {
List<Object[]> list = new ArrayList<Object[]>();
for (int i = 0; i < empArray.size(); i++) {
list.add(new Object[] {
empArray.get(i).getFName(),
empArray.get(i).getLName(),
empArray.get(i).getMobile()
});
}
table1.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}
You can use the addRow() method of the DefaultTableModel, like this:
((DefaultTableModel)table1.getModel()).addRow(new Object[] {
empArray.get(i).getFName(),
empArray.get(i).getLName(),
empArray.get(i).getMobile()
});

Posting from JTextFields into array

Ok So i have made my array and added an action listener so that when the button named "Submit" is clicked all data from my JTextFields should be entered into an ArrayList although this is not happening, any help on why not would be appreciated. below is the Action Listener action Performed.
public class Main {
String HouseNumber, StreetName, Town, Postcode, Beds, Price, Type;
JTextField HouseNumber1, StreetName1, Town1, Postcode1, Beds1, Price1,
Type1;
JLabel HouseNumberLabel, StreetNameLabel, TownLabel, PostcodeLabel,
BedsLabel, PriceLabel, TypeLabel;
JButton Submit;
JPanel panel;
JFrame frame;
public static void main(String[] args) {
Main gui = new Main();
gui.go();
}
public void go() {
frame = new JFrame();
panel = new JPanel();
HouseNumberLabel = new JLabel("House Number");
HouseNumber1 = new JTextField("");
StreetNameLabel = new JLabel("Street name");
StreetName1 = new JTextField("");
TownLabel = new JLabel("Town");
Town1 = new JTextField("");
PostcodeLabel = new JLabel("Postcode");
Postcode1 = new JTextField("");
BedsLabel = new JLabel("Number of beds");
Beds1 = new JTextField("");
PriceLabel = new JLabel("Price (£)");
Price1 = new JTextField("");
TypeLabel = new JLabel("Building Type");
Type1 = new JTextField("");
Submit = new JButton("Submit");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
// Add contents to JFrame and JPanel
panel.add(HouseNumberLabel);
panel.add(HouseNumber1);
panel.add(StreetNameLabel);
panel.add(StreetName1);
panel.add(TownLabel);
panel.add(Town1);
panel.add(PostcodeLabel);
panel.add(Postcode1);
panel.add(BedsLabel);
panel.add(Beds1);
panel.add(PriceLabel);
panel.add(Price1);
panel.add(TypeLabel);
panel.add(Type1);
panel.add(Submit);
frame.pack();
frame.show();
final ArrayList<Main> p = new ArrayList<Main>();
Submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main array = new Main();
HouseNumber = HouseNumber1.getText();
StreetName = StreetName1.getText();
Town = Town1.getText();
Postcode = Postcode1.getText();
p.add(array);
}
});
}
}
Although your Main class has the fields, since it's also managing the GUI, you don't want to create an ArrayList<Main>
If you just need to collect all the strings then you can create
ArrayList<String> houseDetails = new ArrayList<String>();
houseDetails.add(HouseNumber);
houseDetails.add(StreenName);
houseDetails.add(Town);
houseDetails.add(Postcode);
but the cleaner thing to do would be to create a class to manage these
class House
{
private String houseNumber;
private String streetName;
private String town;
private String postcode;
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
and then create a House and set all the valuse.
final ArrayList<House> houses = new ArrayList<House>();
and in your actionPerformed event
House house = new House();
house.setHouseNumber(HouseNumber);
...
houses.add(house);

How do i add values entered into TextFields in a JPanel to an array?

I would like to add the values of "HouseNumber,StreetName,Town,Postcode" which are the textfields on my JPanel to the "Address" Array, What would be the best way to go about this? Thanks
Main Class
public class Main{
public static void main(String[] args){
JFrame frame = new JFrame("Burgess-Brown-Pearson Homes");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel HouseNumberLabel = new JLabel("House Number");
JTextField HouseNumber = new JTextField("");
JLabel StreetNameLabel = new JLabel("Street Name");
JTextField StreetName = new JTextField("");
JLabel TownLabel = new JLabel("Town");
JTextField Town = new JTextField("");
JLabel PostCodeLabel = new JLabel("PostCode");
JTextField PostCode = new JTextField("");
JLabel BedsLabel = new JLabel("Number of Beds");
JTextField Beds = new JTextField("");
JLabel PriceLabel = new JLabel("Price");
JTextField Price = new JTextField("");
JLabel TypeLabel = new JLabel("Building Type");
JTextField Type = new JTextField("");
JButton Submit = new JButton("Submit");
frame.setSize(500,500);
panel.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
panel.add(HouseNumberLabel);
panel.add(HouseNumber);
panel.add(StreetNameLabel);
panel.add(StreetName);
panel.add(TownLabel);
panel.add(Town);
panel.add(PostCodeLabel);
panel.add(PostCode);
panel.add(BedsLabel);
panel.add(Beds);
panel.add(PriceLabel);
panel.add(Price);
panel.add(TypeLabel);
panel.add(Type);
panel.add(Submit);
frame.pack();
frame.show();
//Create new Person objects
Address p[] = new Address[3];
p[0] = new Address("27","Abbey View","Hexham","NE46 1EQ");
p[1] = new Address("15", "Chirdon Crescent", "Hexham", "NE46 1LE");
p[2] = new Address("6", "Causey Brae", "Hexham", "NE46 1DB");
Details c[] = new Details[3];
c[0] = new Details ("3", "175,000", "Terraced");
c[1] = new Details ("6", "300,000", "Bungalow");
c[2] = new Details ("4", "250,000", "Detached");
//Send some messages to the objects
c[0].setBeds("3 ");
c[1].setBeds("6");
c[2].setBeds("4");
c[0].setPrice("175,000");
c[1].setPrice("300,000");
c[2].setPrice("250,000");
c[0].setType("Terraced");
c[1].setType("Bungalow");
c[2].setType("Detached");
//Set up the association
p[0].ownsDetails(c[0]);
p[1].ownsDetails(c[1]);
p[2].ownsDetails(c[2]);
System.exit(0);
}
}
Address Class
public final class Address{
//Class properties
private String HouseNumber, StreetName, Town, Postcode;
//Allow this person to own a car
private Details owns;
//Constructor
public Address(String aHouseNumber, String aStreetName, String Town, String Postcode)
{
setHouseNumber(aHouseNumber);
setStreetName(aStreetName);
setTown(Town);
setPostcode(Postcode);
}
public Address(){
}
}
//Add a house
public void ownsDetails(Details owns){
this.owns = owns;
}
//Set methods for properties
public void setHouseNumber(String aName){
HouseNumber = aName;
}
public void setStreetName(String aName){
StreetName = aName;
}
public void setTown(String anName){
Town = anName;
}
public void setPostcode (String anName){
Postcode = anName;
}
//Get methods for properties
public String getHouseNumber(){
return HouseNumber;
}
public String setStreetName(){
return StreetName;
}
public String setTown(){
return Town;
}
public String setPostcode(){
return Postcode;
}
** Details Class **
public final class Details{
//Class properties
private String Type, Beds, Price;
//Constructor
public Details(String aType, String aBeds, String aPrice){
setType(aType);
setBeds(aBeds);
setPrice(aPrice);
}
//Set methods for properties
public void setType(String aType){
Type = aType;
}
public void setBeds(String aBeds){
Beds = aBeds;
}
public void setPrice(String aPrice){
Price = aPrice;
}
//Get methods for properties
public String getType(){
return Type;
}
public String getBeds() {
return Beds;
}
public String getPrice(){
return Price;
}
}
I really don't understand the problem. You have all the methods that you need.
I'll try to give you some tips anyway.
First of all, if the JTextField are used to create new address, and not updating one of the existing, then a static array may not be the right choice. You should use ArrayList instead:
ArrayList<Address> p = new ArrayList<Address>();
Then simply retrieve the data from the JTextFields and construct another Address object:
Address newAddress = new Address(HouseNumber.getText(),
StreetName.getText(),
Town.getText(),
Postcode.getText());
p.add(newAddress);
Is this enough to solve your doubts ?

Categories