Java code needs to restrict the user input - java

I got a serious problem on my code.
I got a swing JDBC code which I need to fill a table of names, addresses and an ID for the person, different than the table's ID. I created a swing input code for it, however, I wish it NOT to include the ID number's possibility - therefore, to make the swing have nothing else but the name and address being able to be set by the used, and not to show the ID at all.
Is there a possibility for it?
The creation of new partner, which has the name, address and the IdentityNumber strings, all private and their getters and setters public.
{
protected final String FRAME_TITLE = "Vehicle Repository";
private DatabaseHandler dbHandler;
private JTabbedPane tabbedPane;
private JTable partnerTable;
private JpaControlledTableModel<Partner> partnerTableModel;
#Override
public void onCreate() {
setDefaults(FRAME_TITLE);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
dbHandler = new DatabaseHandler();
dbHandler.open();
tabbedPane = new JTabbedPane();
partnerTableModel = new AsyncFullQueryingTableModel<>(dbHandler.getPartnerJpaController(), dbHandler.getEntityClassesToControllersMap());
parterTable = new JTable(partnerTableModel);
tabbedPane.addTab("Partners", new JScrollPane(parterTable));
getContentPane().add(tabbedPane, BorderLayout.CENTER);
}
#Override
public JMenuBar createJMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Data");
menuBar.add(menu);
JMenuItem menuItem;
menuItem = new JMenuItem(newPartnerAction);
menu.add(menuItem);
return menuBar;
}
private Action newPartnerAction = new AbstractAction("New parnter") {
#Override
public void actionPerformed(ActionEvent e) {
Partner partner = new Partner();
EntityEditorDialog<Partner> editorDialog = EntityEditorDialogFactory.createEditorDialog(partner, dbHandler.getPartnerJpaController());
editorDialog.setVisible(true);
if (partner.getId() != null) {
partnerTableModel.refresh();
}
}
};
private String getString(String message) {
return JOptionPane.showInputDialog(rootPane, message, "Data input", JOptionPane.QUESTION_MESSAGE);
}
private Partner getPartner(String message) {
Object[] partners = dbHandler.getPartnerJpaController().findEntities().toArray();
if (partners.length == 0) {
return null;
} else {
return (Partner) JOptionPane.showInputDialog(rootPane, message, "Data input", JOptionPane.QUESTION_MESSAGE, null, partners, partners[0]);
}
}
#Override
public void dispose() {
dbHandler.close();
super.dispose();
}
}
};

and not to show the ID at all
You can remove a column from display in the JTable:
table.removeColumn( table.getColumn(...) );

Related

JList using HashMap key (String) as its display?

I've been self studying Java for a couple months and have run into a challenge. I'm making a contact list application. I chose to use HashMap<String, Contact> as my storage for the contacts. The challenge I'm running into is the my unfamiliarity with Swing. I'm trying for the first time to use JList. I have got JList to work with a normal array of strings but now I want to use the Key value from the HashMap for the JList display.
I have read elsewhere that a custom ListModel will do, but I have failed to find anything concrete. The oracle document How to Use Lists uses the DefaultListModel in its examples. I have read using AbstractListModel or ListModel are steps in the right direction. There are three main classes so far:
Class Contact
public class Contact {
private String name;
private String phoneNumber;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Class Book
import java.util.HashMap;
import java.util.Map;
public class Book {
private Map<String, Contact> addressbook = new HashMap<String, Contact>();
public Map<String, Contact> getAddressbook() {
return addressbook;
}
public void setAddressbook(Map<String, Contact> addressbook) {
this.addressbook = addressbook;
}
}
Class UserInterface
This is where I'm having difficulty creating a custom list model that takes the String keys from my HashMap located in class Book.
import java.awt.BorderLayout;
public class UserInterface extends JPanel implements ActionListener {
private static final long serialVersionUID = 2161244209167568887L;
// Contact list display
JList contactList;
// Menu bar and accompanying menu items
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem newContactMenuButton;
private JMenuItem exitAppMenuButton;
// Buttons
private JButton newContactButton;
private JButton openContactButton;
private JButton deleteContactButton;
// Panels to place components into
private JPanel mainPanel;
private JPanel buttonPanel;
// For message dialogs
private JFrame messageDialog;
public UserInterface() {
// Add the JList
contactList = new JList(new ContactListModel()); // ??
// Creating the menu bar and its items
// Adding ActionListeners to the menu buttons
menuBar = new JMenuBar();
menu = new JMenu("File");
newContactMenuButton = new JMenuItem("New Contact");
exitAppMenuButton= new JMenuItem("Exit");
newContactMenuButton.addActionListener(this);
exitAppMenuButton.addActionListener(this);
menu.add(newContactMenuButton);
menu.add(exitAppMenuButton);
menuBar.add(menu);
// Creating the Buttons
// Adding ActionListeners to the buttons
newContactButton = new JButton("New Contact");
openContactButton = new JButton("Open Contact");
deleteContactButton = new JButton("Delete Contact");
newContactButton.addActionListener(this);
openContactButton.addActionListener(this);
deleteContactButton.addActionListener(this);
// Creating the Panels with Grid Layouts
mainPanel = new JPanel(new GridLayout());
buttonPanel = new JPanel(new GridLayout(0, 1));
// Adding components to the Panels
mainPanel.add(contactList);
buttonPanel.add(newContactButton);
buttonPanel.add(openContactButton);
buttonPanel.add(deleteContactButton);
// Adding and aligning the Panels
setBorder(BorderFactory.createEmptyBorder(45, 45, 45, 45));
add(mainPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.EAST);
}
public void CreateAndShowUI() {
JFrame frame = new JFrame("Addressbook Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new UserInterface());
frame.setJMenuBar(this.menuBar);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == newContactButton) {
JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
}
if (e.getSource() == openContactButton) {
JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
}
if (e.getSource() == deleteContactButton) {
if(contactList.isSelectionEmpty()) {
JOptionPane.showMessageDialog(messageDialog, "No contact selected.");
} else if(!contactList.isSelectionEmpty()) {
}
}
if (e.getSource() == newContactMenuButton) {
JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
}
if (e.getSource() == exitAppMenuButton) {
System.exit(0);
}
}
}
final class ContactListModel extends AbstractListModel {
Book book = new Book();
Map<String, Contact> bookList = book.getAddressbook();
public Object getElementAt(int keys) {
keys = // ??
return keys;
}
#Override
public int getSize() {
return bookList.size();
}
}
Any genuine point in the right direction is highly appreciated. In the meantime I'll keep searching.
EDIT: Updated & Answered
Here are the relevant updated code bits. As user carmickr suggested I used DefaultListModel to handle the data from the address book HashMap.
private DefaultListModel<Set<String>> model;
private JList<Set<String>> contactList;
Then inside the UserInterface constructor:
// Create the DefaultListModel object
// Add the JList
model = new DefaultListModel<Set<String>>();
model.addElement(book.AB.keySet());
contactList = new JList<Set<String>>(model);
I'm having difficulty creating a custom list model that takes the String keys from my HashMap located in class Book.
You don't need to create a custom model. You can just add each Contact object to the DefaultListModel. The point of using models is that the model holds all the data and you use methods of the model to access the data.
Then the simplest way to get the JList to work is to implement the toString() method in your Contact object to return the property that you want to see in the JList.
EDIT: Updated & Answered
Here are the relevant updated code bits. As user carmickr suggested I used DefaultListModel to handle the data from the address book HashMap.
private DefaultListModel<Set<String>> model;
private JList<Set<String>> contactList;
Then inside the UserInterface constructor:
// Create the DefaultListModel object
// Add the JList
model = new DefaultListModel<Set<String>>();
model.addElement(book.AB.keySet());
contactList = new JList<Set<String>>(model);

JCheckBox State Remain Consistent Among Classes

I have a help pane which appears at the start of a program, but can be turned off. If the user wants it to return, there is an option in the menu bar to reactivate it. However, when they choose to show it from the help menu, it automatically rechecks the "do not show again" box. How do I keep the box in the same state the user originally had it, but still open the help pane?
Gui:
public class Gui {
private Game game;
private JFrame frame;
private MenuBar menuBar;
private HelpDialog helpMenu;
private boolean showHelp;
public Gui(Game game) {
this.game = game;
this.showHelp = true;
this.createAndShowGUI();
}
public boolean shouldShowHelpDialog() {
return this.showHelp;
}
public void displayHelp() {
this.helpMenu.showHelpDialog();
}
MenuBar:
public class MenuBar {
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem;
private JFrame frame;
private Gui gui;
private Game game;
public MenuBar(JFrame frame, Gui gui, Game game) {
this.menuBar = new JMenuBar();
this.frame = frame;
this.gui = gui;
this.game = game;
}
public void buildMenuBar() {
this.buildFileMenu();
this.buildSettingsMenu();
this.buildHelpMenu();
this.frame.setJMenuBar(this.menuBar);
}
private void buildHelpMenu() {
this.menu = new JMenu("Information");
this.menu.setMnemonic(KeyEvent.VK_I);
this.menu.getAccessibleContext().setAccessibleDescription("Help menu");
JMenuItem menuHelp = new JMenuItem("Help", KeyEvent.VK_H);
menuHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MenuBar.this.gui.displayHelp();
}
});
this.menu.add(menuHelp);
this.menuBar.add(this.menu);
}
HelpDialog:
public class HelpDialog {
private boolean shouldShowHelpDialog;
private JFrame theFrame;
public HelpDialog(boolean helpDialog, JFrame frame) {
this.shouldShowHelpDialog = helpDialog;
this.theFrame = frame;
}
public boolean showHelpDialog() {
if (!this.shouldShowHelpDialog) {
return false;
}
JCheckBox shouldShowCheckBox = new JCheckBox("Do not show this message again", this.shouldShowHelpDialog);
Object[] msgContent = { this.buildHelpPane(), shouldShowCheckBox };
JOptionPane.showMessageDialog(this.theFrame, msgContent, "Help", JOptionPane.INFORMATION_MESSAGE);
return shouldShowCheckBox.isSelected();
}
private Object buildHelpPane() {
String helpMessage = "Game rules: This is how you play.";
JTextArea helpTextArea = new JTextArea(helpMessage);
helpTextArea.setRows(6);
helpTextArea.setColumns(40);
helpTextArea.setLineWrap(true);
helpTextArea.setWrapStyleWord(true);
helpTextArea.setEditable(false);
helpTextArea.setOpaque(false);
JScrollPane helpPane = new JScrollPane(helpTextArea);
return helpPane;
}
}
EDIT:
Updated HelpDialog class:
public class HelpDialog {
private boolean shouldShowHelpDialog;
private JFrame theFrame;
private JCheckBox shouldShowCheckBox;
public HelpDialog(boolean helpDialog, JFrame frame) {
this.shouldShowHelpDialog = helpDialog;
this.theFrame = frame;
this.shouldShowCheckBox = new JCheckBox("Do not show this message again", this.shouldShowHelpDialog);
}
public boolean showHelpDialog() {
if (!this.shouldShowHelpDialog) {
return false;
}
Object[] msgContent = { this.buildHelpPane(), shouldShowCheckBox };
JOptionPane.showMessageDialog(this.theFrame, msgContent, "Help", JOptionPane.INFORMATION_MESSAGE);
return shouldShowCheckBox.isSelected();
}
The checkbox remains unmarked now when displaying the help menu through the menu bar. However, now when a new game is created, it will show the help dialog even if the box is unchecked.
Full answer includes this change to the method in the GUI:
public void displayHelp() {
this.showHelp = this.helpMenu.showHelpDialog();
}
Your showHelpDialog() method creates a new checkbox each time it is called. You should create the dialog once in the constructor, and showHelpDialog() should just display it.
You can add a parameter to showHelpDialog which overrides your request
public boolean showHelpDialog(boolean override) {
if(!override){
if (!this.shouldShowHelpDialog) {
return false;
}
}
JCheckBox shouldShowCheckBox = new JCheckBox("Do not show this message again", this.shouldShowHelpDialog);
Object[] msgContent = { this.buildHelpPane(), shouldShowCheckBox };
JOptionPane.showMessageDialog(this.theFrame, msgContent, "Help", JOptionPane.INFORMATION_MESSAGE);
return shouldShowCheckBox.isSelected();
}
and call
showHelpDialog(true);
when clicked from menu.

List of Values in Java Swing Form

How can I display an LoV in a Java Swing form as shown in Oracle Forms?
I have data concerning user identifiers and user names. And I want to display the user names in LoV, but if a user selects a name corresponding to a user, its identifier should be returned.
EDIT 1:
Here is the form code that I've used to display 'Lov'
import db.DBHelper;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class LovForm extends JDialog implements ActionListener {
private Connection conn;
private DBHelper db;
private JList list;
private DefaultListModel model;
private UserDetail userDetail;
private JButton btnOk;
public LovForm(Connection c, UserDetail u) {
this.conn = c;
this.userDetail = u;
initComponents();
}
private void initComponents() {
db = new DBHelper(this.conn);
btnOk = new JButton("Ok");
btnOk.addActionListener(this);
Container c = this.getContentPane();
c.setLayout(new FlowLayout());
model = new DefaultListModel();
try {
ResultSet rs = db.getAllAppUsers();
if (rs != null) {
while (rs.next()) {
String name = rs.getString("NAME");
model.addElement(name);
}
list = new JList(model);
}
} catch (Exception e) {
list = new JList();
}
list.setPreferredSize(new Dimension(150, 250));
JScrollPane listScroller = new JScrollPane(list);
JLabel lbl = new JLabel("Select an application user");
c.add(lbl);
c.add(listScroller);
c.add(btnOk);
this.setTitle("List of Users");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(new Dimension(200, 250));
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setModal(true);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e
) {
if (e.getSource() == btnOk) {
String selectedItem = (String) list.getSelectedValue();
userDetail.setUserName(selectedItem);
this.dispose();
}
}
}
I would add a wrapper class for the User, which contains its name and its id.
Do not forget to override the toString() method of the User (that method will be used when rendering the list).
While populating the list, create User objects, and therefore you will have access to both its name and its id.
See code bellow:
private void initComponents() {
// your code....
try {
ResultSet rs = db.getAllAppUsers();
if (rs != null) {
while (rs.next()) {
String name = rs.getString("NAME");
int id = rs.getInt("ID");
model.addElement(new User(name, id));
}
list = new JList(model);
}
} catch (Exception e) {
list = new JList();
}
// your code...
}
#Override
public void actionPerformed(ActionEvent e
) {
if (e.getSource() == btnOk) {
User selectedItem = (User) list.getSelectedValue();
userDetail.setUserName(selectedItem.getName());
int id = selectedItem.getId();
this.dispose();
}
}
public class User {
private String name;
private Integer id;
public User(String name, Integer id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Integer getId() {
return id;
}
#Override
public String toString() {
return name;
}
}
You could use a JComboBox.
You would create a custom Object to store both pieces of data. Then you would create a custom renderer to display whatever data you want in the combo box. Your processing code would then use the other property.
Check out Combo Box With Custom Renderer for an example of the rendering code you would use. This renderer is more complete than most rendering code you will find in the forum because it will still support selection of the item from the combo box using the keyboard.
I see you updated your question to show you are using a JList. Well the answer is still the same. You need a custom renderer for your JList. You can base your renderer off the example from the above link except you would extend the DefaultListCellRenderer.

menu items and modal windows are multiplying every time I open them

I've created a vaadin table. When I do right-click it shows context menu with +New... text and when I click on it - it shows modal window with two tables. Every table has the same fuctionality.
The problem is that every time I open and close modal window it adds duplicates for context menu items on modal tables(on the main page it works correct). Moreover - it adds several modal windows when I click on modal table context menu (for example if I open window 5 times - it add 5 context menu items and 5 modal windows for clicked modal context menus)
The only way to return to one item - restart whole application.
What is the problem?
Every my table looks like this
#Component("taskTable")
#Scope("prototype")
public class TaskTable extends AbstractObjectTable {
#Autowired
private TaskService taskService;
#Autowired
private NewTaskWindow taskWindow;
#Autowired
private ShowTaskDetailsWindow detailsWindow;
private Action[] action = new Action[] { new Action("+New...") };
#Override
public Table createTable() {
caption = "Tasks";
headers = new String[] { "Description", "Project", "Status", "Weight", "Developer", "ID" };
this.addActionHandler(new Handler() {
#Override
public Action[] getActions(Object target, Object sender) {
return action;
}
#Override
public void handleAction(Action action, Object sender, Object target) {
switch(action.getCaption()) {
case "+New...": {
PmcUi.getCurrent().addWindow(taskWindow.createWindow());
break;
}
}
//what to do for action
}
});
this.addItemClickListener(new ItemClickListener(){
#Override
public void itemClick(ItemClickEvent event) {
if (event.isDoubleClick()) {
PmcUi.getCurrent().addWindow(detailsWindow.createWindow());
}
return;
}
});
return super.createTable();
}
#Override
protected IndexedContainer projectDatasource() {
IndexedContainer indexedContainer = new IndexedContainer();
for(String header: headers) {
indexedContainer.addContainerProperty(header, String.class, "");
}
List<Task> tasks = taskService.findAllTasks();
for(int i = 0; i < tasks.size(); i++) {
Object id = indexedContainer.addItem();
Task item = tasks.get(i);
indexedContainer.getContainerProperty(id, headers[0]).setValue(item.getDescription());
indexedContainer.getContainerProperty(id, headers[1]).setValue(item.getTaskProject());
indexedContainer.getContainerProperty(id, headers[2]).setValue(item.getStatus());
indexedContainer.getContainerProperty(id, headers[3]).setValue(item.getWeight());
indexedContainer.getContainerProperty(id, headers[4]).setValue(item.getTaskDeveloper());
indexedContainer.getContainerProperty(id, headers[5]).setValue(item.getTaskId());
}
return indexedContainer;
}
}
Where AbstractObjectTable
public abstract class AbstractObjectTable extends Table {
protected String caption;
protected String[] headers = null;
protected Table createTable() {
this.setContainerDataSource(projectDatasource());
this.setVisibleColumns(headers);
this.setSelectable(true);
this.setImmediate(true);
return this;
}
protected abstract IndexedContainer projectDatasource();
}
My +New... modal windows looks similar to that
#Component("newTaskWindow")
public class NewTaskWindow {
private Window createTaskWindow;
#Autowired
private TaskService taskService;
public Window createWindow() {
createTaskWindow = new Window("New Task");
initWindow();
fillWindow();
return createTaskWindow;
}
private void initWindow() {
createTaskWindow.setSizeUndefined();
createTaskWindow.setResizable(false);
createTaskWindow.setModal(true);
createTaskWindow.addCloseListener(new CloseListener() {
#Override
public void windowClose(CloseEvent e) {
Notification.show("Closed");
}
});
}
private void fillWindow() {
final TextField taskDescription = new TextField("Description");
final ComboBox taskProject = new ComboBox("Select project");
final ComboBox taskDeveloper = new ComboBox("Select developer");
final TextField taskWeight = new TextField("Task weight");
final TextField taskStatus = new TextField("Task status");
Button create = new Button("Create");
create.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Task task = new Task();
task.setTaskId(UUID.randomUUID().toString());
task.setStatus(taskStatus.getValue());
task.setTaskDeveloper(taskDeveloper.getValue().toString());
task.setTaskProject(taskProject.getValue().toString());
task.setWeight(taskWeight.getValue());
task.setDescription(taskDescription.getValue());
taskService.insertTask(task);
createTaskWindow.close();
}
});
Button close = new Button("Cancel");
close.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
createTaskWindow.close();
}
});
HorizontalLayout layout = new HorizontalLayout(create, close);
FormLayout formLayout = new FormLayout(taskProject, taskDeveloper, taskWeight, taskStatus,
taskDescription, layout);
formLayout.setMargin(true);
createTaskWindow.setContent(formLayout);
}
}
And my details windows also have similar architecture.
#Component("showTaskDetailsWindow")
public class ShowTaskDetailsWindow {
private Window showDetailsWindow;
#Autowired
private TaskService taskService;
public Window createWindow() {
showDetailsWindow = new Window("Show details");
initWindow();
fillWindow();
return showDetailsWindow;
}
private void initWindow() {
showDetailsWindow.setSizeUndefined();
showDetailsWindow.setResizable(false);
showDetailsWindow.setModal(true);
showDetailsWindow.addCloseListener(new CloseListener() {
#Override
public void windowClose(CloseEvent e) {
Notification.show("Closed");
}
});
}
private void fillWindow() {
final TextField taskDescription = new TextField("Description");
final TextField taskProject = new TextField("Task project");
final TextField taskDeveloper = new TextField("Task developer");
final TextField taskWeight = new TextField("Task weight");
final TextField taskStatus = new TextField("Task status");
FormLayout formLayout = new FormLayout(taskProject, taskDeveloper, taskWeight, taskStatus, taskDescription);
formLayout.setMargin(true);
showDetailsWindow.setContent(formLayout);
}
}
What is the problem? Why it is continuously multiplying?
The problem is your getActions implementation
#Override
public Action[] getActions(Object target, Object sender) {
return new Action[] { new Action("+New...")};
}
You should create one instance of the "new Action("+New...")" item and store it for example in the TaskTable object.
The getActions(..) should alsways return the same instance.
If you always create a new action, it just adds them to the already existing actions.
Looks like the createTable() method of the TaskTable class is called too many times but the provided code doesn't show where that method is called. That causes that multiple action handlers and item click listeners are added to a table.

How to use a variable which is used in an ActionListener?

as you can see in the picture I'm setting up a table which shows all files from a specific path (later I'll implement a filter for pdf files only). First, all files are simultaneously shown, but I want to see each single file of the path during the build up of the table. So I've changed it to a array list, but there a two errors which I really couldn't resolve...
Hope that you can help me ;-)
class FileModel extends AbstractTableModel implements FilenameFilter {
String titles[] = new String[] { "Path" };
Class<?> types[] = new Class[] { String.class, String.class };
private List<Object[]> data = new ArrayList<>();
public FileModel() {
this("C:\\");
}
public FileModel(String dir) {
File pwd = new File(dir);
setFileStats(pwd);
}
// Implement the methods of the TableModel interface we're interested
// in. Only getRowCount(), getColumnCount() and getValueAt() are
// required. The other methods tailor the look of the table.
#Override
public int getRowCount() {
return this.data.size();
}
#Override
public int getColumnCount() {
return this.titles.length;
}
#Override
public String getColumnName(int c) {
return this.titles[c];
}
#Override
public Class<?> getColumnClass(int c) {
return this.types[c];
}
#Override
public Object getValueAt(int r, int c) {
return this.data.get(r)[c];
}
// Our own method for setting/changing the current directory
// being displayed. This method fills the data set with file info
// from the given directory. It also fires an update event so this
// method could also be called after the table is on display.
public void setFileStats(File dir) {
System.out.println("SET MY DIR " + dir);
this.data = new ArrayList<>();
this.fireTableDataChanged();
String files[] = dir.list();
this.data = new Object[files.length][this.titles.length]; **// Here error #1**
for (int i = 0; i < files.length; i++) {
File tmp = new File(files[i]);
this.data[i][0] = tmp.getAbsolutePath(); **// Here error #2**
}
this.fireTableDataChanged();
}
#Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return false;
}
}
Here's the code of the JFrame windows:
public class FileFrame extends JFrame {
protected FileModel fileModel = new FileModel();
{
this.setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JTable FileTable = new JTable(this.fileModel);
TableRowSorter<TableModel> TableRowSorter = new TableRowSorter<TableModel>(this.fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
}
public static void main(String args[]) {
final FileFrame FileFrame = new FileFrame();
// Create menubar
JMenuBar menubar = new JMenuBar();
// Create JMenu object
JMenu menu = new JMenu("File");
// Create JMenuItem object
final JMenuItem openItem = new JMenuItem("Open");
JMenuItem exititem = new JMenuItem("Exit");
// Add JMenuItem to JMenu
menu.add(openItem);
menu.add(exititem);
// Add menu to menubar
menubar.add(menu);
// Add menubar to dialog
FileFrame.setJMenuBar(menubar);
// Show dialog
FileFrame.setVisible(true);
// Integrate ActionListener as anonymous class
openItem.addActionListener(new java.awt.event.ActionListener() {
public File savedPath;
public final JFileChooser FileChooser = new JFileChooser("C:\\");
// Initialize actionPerformed
#Override
public void actionPerformed(ActionEvent e) {
// Generate choose file
this.FileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
this.FileChooser.setDialogTitle("Selection of pdf directory");
this.FileChooser.setAcceptAllFileFilterUsed(false);
// Set the text
this.FileChooser.setApproveButtonText("Open directory");
// Set the tool tip
this.FileChooser.setApproveButtonToolTipText("Select pdf directory ");
if (this.savedPath != null)
this.FileChooser.setCurrentDirectory(this.savedPath);
int returnVal = this.FileChooser.showOpenDialog(openItem);
if (returnVal == JFileChooser.APPROVE_OPTION) {
this.savedPath = this.FileChooser.getSelectedFile();
FileFrame.fileModel.setFileStats(this.savedPath);
}
}
});
// Integrate ActionListener as anonymous class
exititem.addActionListener(new java.awt.event.ActionListener() {
// Initialize actionPerformed
#Override
public void actionPerformed(ActionEvent e) {
// Close program
System.exit(0);
}
});
}
}
The problem is you are trying to access data as though its an array
private List<Object[]> data = new ArrayList<>();
...
this.data = new Object[files.length][this.titles.length];
this.data[i][0] = tmp.getAbsolutePath();
But data is actually a List<Object[]>
So you might want to do
//data.add(new Object[files.length][this.titles.length]);
data.add(new Object[files.length]); // can only be one dimensional
and
((Object[])data.get(i))[0] = tmp.getAbsolutePath();
instead
See more on how to use Lists at The List Interface
UPDATE
Change your model code to this
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
File tmp = new File(files[i]);
data.add(new Object[] { tmp.getAbsolutePath()}) ;
}
All you need to do is add a new Object[] to the list (inside the loop) with just the file path, since that seems to be all you need. Don't add one before.

Categories