I'm using IntelliJ GUI Builder to design a GUI for my application. In it, there is a JTable inside a JScrollPane that doesn't seem to be working. Firstly, I can't get the column headers to display. Second, table clicking is not working. It acts as if I'm clicking 3 rows down from where I actually am, both in default row selection and in any MouseListeners I implement. Lastly, if the table exceeds the size of the JScrollPane, it just ignores the last X rows and doesn't provide a scroll bar to view them.
I've reworked the project a couple times now, trying extensions of AbstractTableModel, then DefaultTableModel, and lately I have tried ditching a custom TableModel altogether and just using a DefaultTableModel constructor to no avail. Here is all relevant code (some of it is auto-generated by the GUI Builder and I can't modify it directly).
BaldGUI.java (the main gui)
package client;
import client.DataTypes.Record;
import client.DataTypes.RecordSet;
import client.GuiElements.FileTree;
import client.GuiElements.RecordsTable;
import client.GuiElements.TextConsole;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
public class BaldGUI extends JFrame {
//Menu
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem newBatchItem = new JMenuItem("New Batch");
private JMenuItem saveBatchItem = new JMenuItem("Save Batch");
private JMenuItem loadBatchItem = new JMenuItem("Load Batch");
private static String rootDir = "C:/Users/wf1946/IdeaProjects/DocumentumLoaderTest01/data";
private JPanel mainPanel;
private JPanel LeftSideBarPanel;
private JTree fileTree;
private JButton AddFileButton;
private JButton ChangeDirectoryButton;
private JButton AddDirectoryButton;
private JCheckBox IncludeSubDirectoriesCheckBox;
private JScrollPane DataTableWrapper;
private JTable DataTable;
private JEditorPane Console;
private JScrollPane ConsoleScroller;
public BaldGUI() {
$$$setupUI$$$();
this.loadComponents();
this.AddFileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((RecordsTable) DataTable).addItem(new Record());
}
});
this.add(this.mainPanel);
}
private void loadComponents() {
//Menu
this.setJMenuBar(this.menuBar);
this.menuBar.add(this.fileMenu);
this.fileMenu.add(this.newBatchItem);
this.fileMenu.add(this.saveBatchItem);
this.fileMenu.add(this.loadBatchItem);
//Selection handler for the file tree
this.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
#Override
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getPath();
if (!fileTree.getModel().isLeaf(path.getLastPathComponent())) { //Directory
AddDirectoryButton.setEnabled(true);
IncludeSubDirectoriesCheckBox.setEnabled(true);
AddFileButton.setEnabled(false);
} else { //File
AddFileButton.setEnabled(true);
AddDirectoryButton.setEnabled(false);
IncludeSubDirectoriesCheckBox.setEnabled(false);
}
}
});
}
//Getters
public JEditorPane getConsole() {
return Console;
}
public JPanel getMainPanel() {
return mainPanel;
}
public JTree getFileTree() {
return fileTree;
}
public JTable getDataTable() {
return this.DataTable;
}
public JCheckBox getIncludeSubDirectoriesCheckBox() {
return IncludeSubDirectoriesCheckBox;
}
public JScrollPane getDataTableWrapper() {
return DataTableWrapper;
}
private void createUIComponents() {
this.Console = new TextConsole();
this.fileTree = new FileTree(this, new File(this.rootDir));
RecordSet rs = new RecordSet();
for (int i = 0; i < 10; i++) rs.add(new Record());
this.DataTable = new RecordsTable(new DefaultTableModel(rs.getData(), RecordsTable.colNames), this);
this.DataTableWrapper = new JScrollPane(this.DataTable);
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
mainPanel.setMinimumSize(new Dimension(1080, 810));
mainPanel.setPreferredSize(new Dimension(1080, 810));
LeftSideBarPanel = new JPanel();
LeftSideBarPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
LeftSideBarPanel.setMinimumSize(new Dimension(220, 35));
LeftSideBarPanel.setPreferredSize(new Dimension(220, 600));
mainPanel.add(LeftSideBarPanel);
fileTree.setPreferredSize(new Dimension(200, 530));
fileTree.setShowsRootHandles(true);
LeftSideBarPanel.add(fileTree);
AddFileButton = new JButton();
AddFileButton.setPreferredSize(new Dimension(100, 25));
AddFileButton.setText("Add File");
LeftSideBarPanel.add(AddFileButton);
ChangeDirectoryButton = new JButton();
ChangeDirectoryButton.setPreferredSize(new Dimension(100, 25));
ChangeDirectoryButton.setText("Change Root");
LeftSideBarPanel.add(ChangeDirectoryButton);
AddDirectoryButton = new JButton();
AddDirectoryButton.setPreferredSize(new Dimension(100, 25));
AddDirectoryButton.setText("Add Directory");
LeftSideBarPanel.add(AddDirectoryButton);
IncludeSubDirectoriesCheckBox = new JCheckBox();
IncludeSubDirectoriesCheckBox.setPreferredSize(new Dimension(100, 22));
IncludeSubDirectoriesCheckBox.setText("Subdirectories");
LeftSideBarPanel.add(IncludeSubDirectoriesCheckBox);
DataTableWrapper.setPreferredSize(new Dimension(845, 600));
mainPanel.add(DataTableWrapper);
DataTable.setFillsViewportHeight(true);
DataTableWrapper.setViewportView(DataTable);
ConsoleScroller = new JScrollPane();
mainPanel.add(ConsoleScroller);
Console.setEnabled(false);
Console.setPreferredSize(new Dimension(1070, 195));
ConsoleScroller.setViewportView(Console);
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainPanel;
}
}
RecordsTable.java
package client.GuiElements;
import client.ActionListeners.RightClickMenuItemClick;
import client.ActionListeners.TableRightClickHandler;
import client.BaldGUI;
import client.DataTypes.Record;
import client.DataTypes.RecordSet;
import javax.swing.*;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.util.ArrayList;
//Table to store the records
public class RecordsTable extends JTable {
//Status codes returned to calling functions to indicate the success or failure of the new record
public static final int APPEND_SUCCESS_CODE = 1;
public static final int APPEND_FAIL_DUPLICATE_CODE = 2;
public static final String[] colNames = {"Status", "File", "Full Path", "Title", "Form Date",
"Form No.", "Language Code", "Filed", "Approval Date", "Filed Form No."};
private RecordSet data = new RecordSet();
//Parent form
BaldGUI parent;
//Right-click menu for table item
JPopupMenu itemRightClickMenu = new JPopupMenu();
JMenuItem itemEdit = new JMenuItem("Edit Record");
JMenuItem itemDelete = new JMenuItem("Remove Record");
public RecordsTable(DefaultTableModel model, BaldGUI form) {
super(model);
this.parent = form;
this.itemRightClickMenu.add(itemEdit);
this.itemRightClickMenu.add(itemDelete);
this.itemEdit.addMouseListener(new RightClickMenuItemClick(this, itemEdit));
this.itemDelete.addMouseListener(new RightClickMenuItemClick(this, itemDelete));
this.addMouseListener(new TableRightClickHandler(this));
this.updateTable();
}
//Attempts to add a new row to the table
//Returns APPEND_FAIL_DUPLICATE_CODE if the selected file is already in the table
//Returns APPEND_SUCCESS_CODE if the record is successfully added
public int addItem(Record newRecord) {
TextConsole tc = ((TextConsole)this.parent.getConsole());
if(this.itemInData(newRecord)) {
tc.addText(
"File " + newRecord.getFileName() + " already included.\n", TextConsole.redStyle
);
return this.APPEND_FAIL_DUPLICATE_CODE;
}
this.data.add(newRecord);
tc.addText("File " + newRecord.getFileName() + " added successfully.\n", TextConsole.greenStyle);
this.updateTable();
return this.APPEND_SUCCESS_CODE;
}
//Updates the table to display any new data
public void updateTable() {
}
//Returns true if the record is already in the table
//Record equality is defined based on the full path to the file
public boolean itemInData(Record item) {
for( Record r : data) {
if(r.equals(item)) return true;
}
return false;
}
public JPopupMenu getItemRightClickMenu() {
return itemRightClickMenu;
}
public JMenuItem getItemEdit() {
return itemEdit;
}
public BaldGUI getParent() {
return parent;
}
}
The Record type is just a basic data container, and RecordSet is just an extension of ArrayList{Record} with a method to turn the data therein into an Object[][] for the DefaultTableModel.
So, as I expected, it was a really simple, dumb mistake. In my RecordsTable class, I stored off the parent GUI (BaldGUI) as a variable called parent. I then had a method getParent() to fetch that parent, and I didn't realize that JTable comes with a method getParent() which gets the surrounding component. By overriding that method, the entire program more or less broke. I changed the method, and it works as it should.
Related
I am making a GUI utility that will allow to create a question paper through it. A question can have multiple parts. I have made a basic wireframe for this:
My problem is that I can easily make text fields for questions and adding further questions, but how will I associate the parts of a question to it? Basically I have a JSON array in the back end where a question will be stored along with its parts.
QuestionModel represents question-data where all strings forming a question are stored in a collection.
QuestionView represents a view of a single question.
Questionnaire acts as a controller which also creates a dynamic view of QuestionViews.
For convenience the entire code can be copied into Questionnaire.java and run:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.TextField;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//Questionnaire acts as a controller which also creates a dynamic view of QuestionViews.
public class Questionnaire implements ChangeListener{
private final List<QuestionView> questions;
private final List<QuestionModel> questionModels;
private JPanel questionPanel;
private JFrame frame;
Questionnaire() {
questions = new ArrayList<>();
questionModels = new ArrayList<>();
createAndShowGui();
}
private void createAndShowGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
questionPanel = new JPanel();
BoxLayout layout = new BoxLayout(questionPanel, BoxLayout.Y_AXIS);
questionPanel.setLayout(layout);
addQuestion();
JButton addQuestionButton = new JButton("Add Question");
addQuestionButton.addActionListener(e->addQuestion());
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(e->collectQuestion());
JPanel buttonsPanel = new JPanel(new BorderLayout(10,10));
buttonsPanel.add(addQuestionButton, BorderLayout.WEST);
buttonsPanel.add(submitButton, BorderLayout.EAST);
JPanel mainPane = new JPanel(new BorderLayout(10,10));
mainPane.add(questionPanel,BorderLayout.CENTER);
mainPane.add(buttonsPanel,BorderLayout.SOUTH);
frame.add(mainPane);
frame.pack();
frame.setVisible(true);
}
//adds a question to the questionnaire
private void addQuestion() {
QuestionModel model = new QuestionModel();
QuestionView view = new QuestionView(model);
view.setListener(this);
questions.add(view);
questionModels.add(model);
questionPanel.add(view.getView());
refresh();
}
//refresh view whan something changed
void refresh(){
frame.pack();
}
// ChangeListener implementation
#Override
public void changed() {
refresh();
}
//collect all strings from text fields and update models
private void collectQuestion() {
for(QuestionView view : questions){
view.collectQuestions();
}
//for testing
printQuestions();
}
void printQuestions(){
for(QuestionModel model : questionModels){
System.out.println(model.getQuestion());
}
}
public static void main(String[] args) {
new Questionnaire();
}
}
//QuestionModel represents question-data where all strings forming a question are stored in a collection.
class QuestionModel {
private final List<String> questionParts;
QuestionModel() {
questionParts = new ArrayList<>();
}
void addQuestionPart(String text){
questionParts.add(text);
}
List<String> getQuestionParts() {
return questionParts;
}
//return the whole question as one string
String getQuestion(){
StringBuilder sb = new StringBuilder();
for(String part : questionParts){
sb.append(part).append(" ");
}
return sb.toString();
}
}
//QuestionView represents a view of a single question
class QuestionView {
private final List<TextField> questionPartsTf;
private final JPanel tfPanel, mainPanel;
private ChangeListener listener; //used to notify that view changed
private final QuestionModel model;
QuestionView(QuestionModel model) {
this.model = model;
questionPartsTf = new ArrayList<>();
tfPanel = new JPanel(new GridLayout(1, 0, 0, 10));
JLabel addLabel = new JLabel("Add question: ");
tfPanel.add(addLabel);
addTextField();
JButton addButton = new JButton("Add question part");
addButton.addActionListener(e->addTextField());
mainPanel = new JPanel(new BorderLayout(10,10));
mainPanel.add(tfPanel, BorderLayout.WEST);
mainPanel.add(addButton, BorderLayout.AFTER_LINE_ENDS);
}
private void addTextField() {
TextField tf= new TextField(15);
tfPanel.add(tf);
questionPartsTf.add(tf);
if(listener != null){
listener.changed();
}
}
//collect all strings from text fields and update model
void collectQuestions(){
for(TextField tf : questionPartsTf){
if(!tf.getText().isEmpty()){
model.addQuestionPart(tf.getText());
}
}
}
JComponent getView(){
return mainPanel;
}
void setListener(ChangeListener listener) {
this.listener = listener;
}
}
//interface for listening to view changes
interface ChangeListener{
void changed();
}
Run it on line: https://repl.it/repls/VastNaiveModules
If I understand your question correctly, you want to associate parts with questions. Here's a plain Java class that holds one question and as many parts as needed.
import java.util.ArrayList;
import java.util.List;
public class Question {
private String question;
private List<String> parts;
public Question(String question) {
this.question = question;
this.parts = new ArrayList<>();
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public void addPart(String part) {
this.parts.add(part);
}
public List<String> getParts() {
return parts;
}
}
You would keep a List of Question instances in another class, your application model class.
As far as the view, you would create an additional JTextField each time the user clicks on the add parts JButton. You associate those JTextFields with the parts in the Question class.
Alright, since it didn't work out last time. I'm going to post my full code here and i hope i can get some replies as to why it's not working. I'm not getting any compiling errors, the applet runs and then nothing shows up and at the bottom it says "applet not initialized." I'm using blueJ. I apologize for the length of this post, I could not figure out how to make this same error with a shorter code.
I have a JApplet program with multiple classes. RegPanel,WorkshopPanel, ConferenceGUI, ConferenceHandler and ConferenceClient. Basically RegPanel and WorkShop panel are added to the ConferenceGUI, which also creates and adds a couple small panels. The ConferenceClient class is just used to initaite the class to run the applet. The ConferenceHandler is used to handle the action events for the JButtons, JTextArea, JCheckBox, etc... Normally this whole program works fine. Except when i add a listener for the JCheckBox, it stops working. The problem area is in the ConferenceGUI class, it is commented with stars to be clear what's causing the problem.
I've been stuck on this error for about a day now and the frustration i'm feeling is overwhelming. So, to get to the point, here's the complete code:
(please, i don't need tips on any other part of the code, I just need help with that error). You may want to skip over the code and just read the ConferenceGUI class where the error is located. If you could also explain to me why this isn't working, it would be very helpful to me. Thank you in advance!
RegPanel Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class RegPanel extends JPanel
{
protected JTextField regNameTextBox;
protected JCheckBox keynoteCheckBox;
protected final String[] REGTYPES = {"Please select a type","Business","Student","Complimentary"};
protected JPanel registrationPanel, keynotePanel;
protected final double BUSINESSFEE = 895,STUDENTFEE = 495,COMPLIMENTARYFEE = 0;
protected JComboBox regTypeComboBox;
public RegPanel()
{
//Set the layout for the RegPanel to be 2 rows and 1 column.
setLayout(new GridLayout(2, 1));
//initiate the registration panel and add a border
registrationPanel = new JPanel();
registrationPanel.setLayout(new FlowLayout());
registrationPanel.setBorder(BorderFactory.createTitledBorder("Registrant's Name & Type"));
//initiate the comboBox and add the registration types
regTypeComboBox = new JComboBox(REGTYPES);
//Initiate the textfield with a size of 20
regNameTextBox = new JTextField(20);
//Add the registration name textbox and type combobox to the registration panel
registrationPanel.add(regNameTextBox);
registrationPanel.add(regTypeComboBox);
//initiate the second panel for the checkbox
keynotePanel = new JPanel();
keynotePanel.setLayout(new FlowLayout());
//initiate the checkbox and add it to the keynote panel
JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
keynotePanel.add(keynoteCheckBox);
//Add the two panels to the main panel
add(registrationPanel);
add(keynotePanel);
}
public double getRegistrationCost()
{
double regFee = 0;
String comboBoxAnswer = (String)regTypeComboBox.getSelectedItem();
switch (comboBoxAnswer)
{
case "Business": regFee = BUSINESSFEE;
break;
case "Student": regFee = STUDENTFEE;
break;
}
return regFee;
}
public double getKeynoteCost()
{
double keynoteCost = 0;
if(keynoteCheckBox.isSelected())
{
keynoteCost = 30;
}
return keynoteCost;
}
public String getRegType()
{
String regType = (String)regTypeComboBox.getSelectedItem();
return regType;
}
}
WorkshopPanel Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class WorkshopPanel extends JPanel
{
protected final double ITFEE = 295, DREAMFEE = 295, JAVAFEE = 395, ETHICSFEE = 395;
protected final String[] WORKSHOPS = {"IT Trends in Manitoba","Creating a Dream Career","Advanced Java Programming","Ethics: The Challenge Continues"};
protected JList workshopList;
public WorkshopPanel()
{
setLayout(new FlowLayout());
workshopList = new JList(WORKSHOPS);
workshopList.setSelectionMode(2);
BorderFactory.createTitledBorder("Workshops");
add(workshopList);
}
public double getWorkshopCost()
{
Object[] workshops = workshopList.getSelectedValues();
double cost = 0;
String workshopString;
for (int i = 0; i < workshops.length; i++)
{
workshopString = (String)workshops[i];
switch(workshopString)
{
case "IT Trends in Manitoba":
cost += ITFEE;
break;
case "Creating a Dream Career":
cost += DREAMFEE;
break;
case "Advanced Java Programming":
cost += JAVAFEE;
break;
case "Ethics: The Challenge Continues":
cost += ETHICSFEE;
break;
}
}
return cost;
}
public Object[] getWorkshopList()
{
Object[] workshopListArray = workshopList.getSelectedValues();
return workshopListArray;
}
}
ConferenceGUI class (THIS CONTAINS THE ERROR):
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceGUI extends JPanel
{
protected JPanel titlePanel, buttonPanel;
protected RegPanel regPanel;
protected WorkshopPanel workshopPanel;
protected JLabel titleLabel;
protected JButton calculateButton, clearButton;
protected JTextArea resultArea;
protected JScrollPane textScroll;
public ConferenceGUI()
{
setLayout(new BorderLayout());
titlePanel = new JPanel();
titleLabel = new JLabel("Select Registration Options",JLabel.CENTER);
Font titleFont = new Font("SansSerif", Font.BOLD, 18);
titleLabel.setFont(titleFont);
titlePanel.add(titleLabel);
add(titlePanel, BorderLayout.NORTH);
regPanel = new RegPanel();
add(regPanel, BorderLayout.WEST);
workshopPanel = new WorkshopPanel();
add(workshopPanel, BorderLayout.EAST);
buildButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
ConferenceHandler handler = new ConferenceHandler(this);
regPanel.regTypeComboBox.addItemListener(handler);
regPanel.regNameTextBox.addFocusListener(handler);
//****************************************************************
//The line below is what causes the error. Without it the code
//Works, with it it doesn't and i get the aforementioned error.
//regPanel.keynoteCheckBox.addItemListener(handler);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
calculateButton = new JButton("Calculate Charges");
buttonPanel.add(calculateButton);
clearButton = new JButton("Clear");
buttonPanel.add(clearButton);
resultArea = new JTextArea(5,30);
textScroll = new JScrollPane(resultArea);
buttonPanel.add(textScroll);
ConferenceHandler handler = new ConferenceHandler(this);
calculateButton.addActionListener(handler);
clearButton.addActionListener(handler);
}
}
ConferenceHandler class( this class is unfinished until i get that error straightened out) :
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceHandler implements ActionListener, ItemListener, FocusListener
{
protected ConferenceGUI gui;
public ConferenceHandler(ConferenceGUI gui)
{
this.gui = gui;
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == gui.calculateButton)
{
String regType = gui.regPanel.getRegType();
Object[] workshopList = gui.workshopPanel.getWorkshopList();
String workshopString;
if (regType == "Please select a type")
{
JOptionPane.showMessageDialog(null,"Please select a registration type","Type Error",JOptionPane.ERROR_MESSAGE );
}
else
{
if(gui.regPanel.keynoteCheckBox.isSelected())
{
gui.resultArea.append("Keynote address will be attended/n");
}
else
{
gui.resultArea.append("Keynot address will not be attended/n");
}
}
}
if (e.getSource() == gui.clearButton)
{
gui.resultArea.append("CLEAR");
}
}
private double getTotalCharges()
{
double charges = 0;
return charges;
}
public void itemStateChanged(ItemEvent e)
{
}
public void focusLost(FocusEvent e)
{
}
public void focusGained(FocusEvent e)
{
}
}
ConferenceClient Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceClient extends JApplet
{
private final int WINDOW_HEIGHT = 700, WINDOW_WIDTH = 250;
private ConferenceGUI gui;
private Container c;
public ConferenceClient()
{
gui = new ConferenceGUI();
c = getContentPane();
c.setLayout(new BorderLayout());
c.add(gui, BorderLayout.CENTER);
setSize(WINDOW_HEIGHT, WINDOW_WIDTH);
}
}
You're shadowing your keynoteCheckBox variable. First you create a instance field in RegPanel, but in the constructor, you redeclare it...
public class RegPanel extends JPanel {
protected JCheckBox keynoteCheckBox;
//...
public RegPanel() {
//...
//initiate the checkbox and add it to the keynote panel
JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
keynotePanel.add(keynoteCheckBox);
This leaves the instance field as null which will cause a NullPointerException
Also, this: regType == "Please select a type" is not how to compare Strings in Java, you want to use something more like "Please select a type".equals(regType)
I have design a frame in which i have used JFileChooser and JList. now i want to perform drag and drop feature from JfileChooser to JList contianing Folder (Such as in my screen Short JList contians folder name a,b,c) suppose from JFileChooser i open a folder and from this folder i select (example.txt)file and then i perform drag and drop of this to JList contianing folder a. so i want (example.txt) file should be in folder a.
how to do this things.and i have one more problem. in my screenshot Jlist contian Three folder(a,b,c).
so when i click on folder a but i m not able to get inside folder a.
this is my code by using this i have create screenshot.
In this code i have create JFileChooser and JList. I have add all the folder into the JList.
now i want to perform Drag and Drop from JFileChooser to JList containing folder.
this is my code by using this i have create screenshot.
In this code i have create JFileChooser and JList. I have add all the folder into the JList.
now i want to perform Drag and Drop from JFileChooser to JList containing folder.
package com.dhananjaynet.swing;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.*;
import com.dhananjay.swing.upload.ReadAllFolderName;
import java.util.ArrayList;
import java.util.List;
public class ConsolidatorDemo extends JPanel implements ActionListener {
private static final long serialVersionUID = -4487732343062917781L;
JFileChooser fc;
JButton clear;
JTextArea console;
JList dropZone;
DefaultListModel listModel;
JSplitPane childSplitPane, parentSplitPane;
PrintStream ps;
ArrayList<String > directyName;
public ConsolidatorDemo() {
super(new BorderLayout());
fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setControlButtonsAreShown(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
JPanel fcPanel = new JPanel(new BorderLayout());
fcPanel.add(fc, BorderLayout.CENTER);
clear = new JButton("Clear All");
clear.addActionListener(this);
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
buttonPanel.add(clear, BorderLayout.LINE_END);
JPanel leftUpperPanel = new JPanel(new BorderLayout());
leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);
JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
listModel = new DefaultListModel();
directyName=ReadAllFolderName.ReadDirectory();
dropZone = new JList(listModel);
dropZone.setListData(directyName.toArray());
dropZone.setCellRenderer(new FileCellRenderer());
dropZone.setTransferHandler(new ListTransferHandler(dropZone));
dropZone.setDragEnabled(true);
dropZone.setDropMode(javax.swing.DropMode.INSERT);
dropZone.setBorder(new TitledBorder("Selected files/folders"));
leftLowerPanel.setViewportView(new JScrollPane(dropZone));
childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
leftUpperPanel, leftLowerPanel);
childSplitPane.setDividerLocation(400);
childSplitPane.setPreferredSize(new Dimension(480, 650));
console = new JTextArea();
console.setColumns(40);
console.setLineWrap(true);
console.setBorder(new TitledBorder("Console"));
parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
childSplitPane, console);
parentSplitPane.setDividerLocation(480);
parentSplitPane.setPreferredSize(new Dimension(800, 650));
add(parentSplitPane, BorderLayout.CENTER);
}
public void setDefaultButton() {
getRootPane().setDefaultButton(clear);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clear) {
listModel.clear();
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.![this is my GUI][2]
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
try {
//UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
//Create and set up the window.
JFrame frame = new JFrame("Consolidator!");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//Create and set up the menu bar and content pane.
ConsolidatorDemo demo = new ConsolidatorDemo();
demo.setOpaque(true); //content panes must be opaque
frame.setContentPane(demo);
//Display the window.
frame.pack();
frame.setVisible(true);
demo.setDefaultButton();
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class FileCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
if (c instanceof JLabel && value instanceof File) {
JLabel l = (JLabel)c;
File f = (File)value;
l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
l.setText(f.getName());
l.setToolTipText(f.getAbsolutePath());
}
return c;
}
}
class ListTransferHandler extends TransferHandler {
private JList list;
ListTransferHandler(JList list) {
this.list = list;
}
#Override
public boolean canImport(TransferHandler.TransferSupport info) {
// we only import FileList
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
return true;
}
#Override
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop()) {
return false;
}
// Check for FileList flavor
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
displayDropLocation("List doesn't accept a drop of this type.");
return false;
}
// Get the fileList that is being dropped.
Transferable t = info.getTransferable();
List<File> data;
try {
data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
}
catch (Exception e) { return false; }
DefaultListModel model = (DefaultListModel) list.getModel();
for (Object file : data) {
model.addElement((File)file);
}
return true;
}
private void displayDropLocation(String string) {
System.out.println(string);
}
}
this my other class for Populating all the folder name into JList
package com.dhananjay.swing.upload;
import java.io.File;
import java.util.ArrayList;
public class ReadAllFolderName {
public static ArrayList<String> ReadDirectory() {
String path = "C:\\Users\\SonyBastian\\Desktop\\DMC";
ArrayList<String> files = new ArrayList<String>();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
System.out.println("method 1");
if (listOfFiles[i].isDirectory()) {
files.add(listOfFiles[i].getName());
/*if (files.endsWith(".txt") || files.endsWith(".TXT")) {
System.out.println(files);
}*/
}
}
return files;
}
}
![enter image description here][3]
[1]: http://i.stack.imgur.com/YAP60.png
Thanks
You have problems with JList model, you create it with DefaultListModel, but then you use dropZone.setListData(directyName.toArray()); which recreate model, because of you get Exception at next line DefaultListModel model = (DefaultListModel) list.getModel();.
So, try to create and populate JList like next:
directyName=ReadAllFolderName.ReadDirectory();
listModel = new DefaultListModel();
for(String s : directyName){
listModel.addElement(s);
}
dropZone = new JList(listModel);
I have created a JTable with GlazedList eventList.
I searched the API but i couldn't figure out how to add undo/redo possibility to this table. I found in the API following classes:
UndoRedoSupport undoRedoSupport = new UndoRedoSupport<"what here?">("argument?");
UndoSupport undoSupport = new UndoSupport<"what to write here?">("argument?");
Does any body know how to use it?
private void createComponents() {
EventList<Dien> eventList = new BasicEventList<Dien>();
actionList = GenericsUtil.makeList();
table = new WebTable();
searchField = new WebTextField(60);
String[] headers = new String[]{"Code", "Name", "Number"};
String[] properties = new String[]{"Code", "Name", "Number"};
TextFilterator<Dien> dienFilterator = new TextFilterator<Dien>() {
public void getFilterStrings(List baseList, Dien dien) {
baseList.add(dien.getCode());
baseList.add(dien.getName());
baseList.add(dien.getNumber());
}
};
MatcherEditor<Dien> textMatcherEditor = new TextComponentMatcherEditor<Dien>(searchField, dienFilterator);
eventList = toolModel.getDiens();
FilterList<Dien> filterList = new FilterList<Dien>(eventList, textMatcherEditor);
TableFormat tableFormat = GlazedLists.tableFormat(properties, headers, new boolean[]{true,true,true});
model = new EventTableModel<Dien>(filterList, tableFormat);
model.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
if(e.getType()==TableModelEvent.UPDATE){
if(!panel.isPendingChanges())
panel.setPendingChange(true);
}
}
});
selectionModel = new EventSelectionModel<Dien>(filterList);
table.setSelectionModel(selectionModel);
table.setModel(model);
}
The Undo/Redo classes built in to GlazedLists does not come with a public constructor; instead you install support to a particular eventlist via the UndoRedoSupport.install() static method.
Of course, if you're using Swing then it makes sense to leverage Swing's UndoManager class and GlazedLists provides a simple wrapper with its UndoSupport class. Again this is simply initialised with its install() method.
I've created a simple Swing sample application as an example to illustrate how to use these classes. In my example I'm using a simple EventList of Strings and a JList. But it will apply the same to any GlazedList-backed component -- UndoRedoSupport applies to the EventList itself and not the Swing component.
import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.swing.EventListModel;
import ca.odell.glazedlists.swing.UndoSupport;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.undo.UndoManager;
public class GlazedListsUndoSample {
private JFrame mainFrame;
private JButton addItemButton;
private JButton undoButton;
private JButton redoButton;
private UndoManager undoManager;
private EventList<String> eventList = new BasicEventList<String>();
public GlazedListsUndoSample() {
//populateAvailableBooks();
createGui();
mainFrame.setVisible(true);
}
private void updateButtons() {
//addBookButton.setEnabled(!books.isEmpty());
undoButton.setEnabled(undoManager.canUndo());
redoButton.setEnabled(undoManager.canRedo());
}
private void createGui() {
undoManager = new UndoManager();
UndoSupport.install(undoManager, eventList);
mainFrame = new JFrame("GlazedLists Undo Example");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EventListModel model = new EventListModel(eventList);
JList list = new JList(model);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JScrollPane(list), BorderLayout.CENTER);
JPanel addBookPanel = new JPanel(new BorderLayout());
addBookPanel.add(new JLabel("Item"), BorderLayout.WEST);
final JTextField titleTextField = new JTextField(50);
addBookPanel.add(titleTextField, BorderLayout.CENTER);
addItemButton = new JButton("Add Item");
addItemButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
eventList.add(titleTextField.getText());
updateButtons();
}
});
addBookPanel.add(addItemButton, BorderLayout.EAST);
JPanel buttonPanel = new JPanel();
undoButton = new JButton("Undo");
undoButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canUndo()) {
undoManager.undo();
}
updateButtons();
}
});
redoButton = new JButton("Redo");
redoButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canRedo()) {
undoManager.redo();
}
updateButtons();
}
});
updateButtons();
buttonPanel.add(undoButton);
buttonPanel.add(redoButton);
mainPanel.add(addBookPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainFrame.getContentPane().setLayout(new BorderLayout());
mainFrame.getContentPane().add(mainPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GlazedListsUndoSample();
}
});
}
}
It's worth noting that the documentation does strongly hint at its functional limitations:
Not every change described in a ListEvent results in an undoable edit.
Specifically, a mutation of a list element IN PLACE does not produce
an undoable edit. For example, an ObservableElementList which observes
a change of an element, or a call to List.set(int, E) with the same
object at that index produce a ListEvent that does not have a
corresponding UndoRedoSupport.Edit object. These ListEvents are
ignored because they lack sufficient information to undo or redo the
change.
In general UndoRedoSupport only makes sense for use with a
BasicEventList or a trivial wrapper around a BasicEventList which does
not affect the order or type of the elements, such as an
ObservableElementList. Advanced transformations, such as SortedList or
FilterList will not work as expected with this UndoRedoSupport class
since their contents are controlled by information outside of
themselves (Comparators and Matchers).
I am working on a project (yes it is for school, no I don't want anyone to write it for me. I have too much pride!) using some of the GUI components of java. It is still in a fairly rough stage, and a single thing is keeping me from getting this finished. I try not to ask for help unless I really need it because usually when I do ask it turns out to be a simple mistake, so if that is the case here, take it easy on me. Anyway, so on to the code. This is a group project so some of my comments are to my partner. I would ask them, but it is 4am... Anyway, here it is. Not sure why it is in all these separate boxes. The listener I am messing with is ActionPerformed, near the bottom. I thank you graciously in advance for any help.
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame
{
private JPanel panel;
private JFrame frame;
private JTextArea text;
private MP3List list = new MP3List();
private JList songList;
private JScrollPane scrollList;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuAdd;
private String[] songs;
private static String mp3msg = "Project 2: MP3 Tracker"; // Header for JOptionPane
public GUI()
{
super("mp3");
panel = new JPanel();
createGUI();
add(panel);
}
public void createGUI()
{
//This creates the frame(createGUI)
frame = new JFrame();
//Here, I made an array of the song titles and gave them to a JList
//for display. Do you think we should sort the songs?
songs = new String[list.getSize()];
for (int i = 0; i < list.getSize(); i++)
{
songs[i] = list.get(i).getSongTitle();
}
songList = new JList(songs);
//Set the selection mode to single as I want to fill in fields with info on a clicked song. More on
//that to come.
songList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Made a scroll bar(vertical and horizontal just in case)
scrollList = new JScrollPane(songList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
text = new JTextArea(30, 30);
text.setText("This section will hold information about songs and somesuch.");
menuBar = new JMenuBar();
menu = new JMenu("File");
menuAdd = new JMenuItem("Add Song");
menuAdd.addActionListener(new menuListener());
menu.add(menuAdd);
menuBar.add(menu);
frame.setLayout(new Border());
songList.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
int selectedVar;
selectedVar = songList.getSelectedIndex();
text.setText(("Song Title: " + list.get(selectedVar).getSongTitle())
+ ("\nArtist: " + list.get(selectedVar).getArtistName())
+ ("\nPlayback Time: " + list.get(selectedVar).getPlayBackTime())
+ (" || Cost: " + list.get(selectedVar).getDownloadCost())
+ (" || Size: " + list.get(selectedVar).getFileSize()));
}
});
}
public class Border extends JFrame implements LayoutManager
{
private static final long serialVersionUID = 1L;
private final int WINDOW_WIDTH = 400;
private final int WINDOW_HEIGHT = 300;
public Border()
{
super("MP3 Editor");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(scrollList, BorderLayout.CENTER);
add(text, BorderLayout.SOUTH);
setJMenuBar(menuBar);
setVisible(true);
}
#Override
public void addLayoutComponent(String name, Component comp)
{
// TODO Auto-generated method stub
}
#Override
public void layoutContainer(Container parent)
{
// TODO Auto-generated method stub
}
#Override
public Dimension minimumLayoutSize(Container parent)
{
// TODO Auto-generated method stub
return null;
}
#Override
public Dimension preferredLayoutSize(Container parent)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void removeLayoutComponent(Component comp)
{
// TODO Auto-generated method stub
}
}
public class menuListener extends JMenuItem implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
/*public menuListener()
{
menuItem.addActionListener(this);
}*/
public void actionPerformed(ActionEvent e)
{
MP3 aSong = getInfo();
list.add(aSong);
songs = new String[list.getSize()];
for (int i = 0; i < list.getSize(); i++)
{
songs[i] = list.get(i).getSongTitle();
}
songList = new JList(songs);
scrollList = new JScrollPane(songList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
int index = 0;
songList.setSelectedIndex(index);
songList.ensureIndexIsVisible(index);
}
}
/**
* Input one set of MP3 file information and produce a report <br>
* <p/>
* <hr>
* Date created: Sep 22, 2010 <br>
* Date last modified: Sep 22, 2010 <br>
* <p/>
* <hr>
*/
public static MP3 getInfo()
{
// Gather all information using JOptionPane
String title = JOptionPane.showInputDialog(null,
"Enter Title: ",
mp3msg,
JOptionPane.QUESTION_MESSAGE);
String artist = JOptionPane.showInputDialog(null,
"Enter Artist: ",
mp3msg,
JOptionPane.QUESTION_MESSAGE);
int seconds = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter playback time in seconds: ",
mp3msg,
JOptionPane.QUESTION_MESSAGE));
double cost = Double.parseDouble(JOptionPane.showInputDialog(null,
"Enter download cost: ",
mp3msg,
JOptionPane.QUESTION_MESSAGE));
double size = Double.parseDouble(JOptionPane.showInputDialog(null,
"Enter file size in megabytes (MB): ",
mp3msg,
JOptionPane.QUESTION_MESSAGE));
MP3 asong = new MP3(title, artist, seconds, cost, size);
return asong;
}
}
There are a number of little issues with your code, but I think the most important one for you is the part where you add a new MP3 in the action listener (the part you said you want help with). Here, you create a brand new JList and you overwrite the previous JList, and you create a new scroll pane for it, but you don't add the new JList to your GUI so the old one remains (and so you never see any changes).
Ideally, you should keep the same list throughout, and just update the contents. There are several ways to do that, but one of the easiest is to simply call songList.setListData(songs). Or, instead of creating an array of Strings, create a Vector because JLists work with Vectors too.
Other issues you might want to look at:
private JFrame frame; is never used.
Your class Border is a JFrame but is also used as a LayoutManager, which is extremely confusing and wrong. You should get rid of that.
Personally, I'd recommend you rewrite the GUI from scratch. Here's a simple example with a working JList for you to examine:
package examples;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
public class GUI extends JFrame {
private final Vector<String> myVector = new Vector<String>();
private final JList myList = new JList();
public static void main(String... args) {
new GUI().setVisible(true);
}
public GUI() {
super("List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new JButton(new AddItemAction()), BorderLayout.NORTH);
add(new JScrollPane(myList), BorderLayout.CENTER);
pack();
}
private class AddItemAction extends AbstractAction {
public AddItemAction() {
super("Add Item");
}
#Override
public void actionPerformed(ActionEvent e) {
String newItem = JOptionPane.showInputDialog("Add a new item:");
if (newItem != null) {
myVector.add(newItem);
myList.setListData(myVector);
}
}
}
}
Read the JList API and follow the link to the secton in the Swing tutorial on "How to Use Lists" which gives a working examples of adding a value to a JList when a button is clicked. Compare you code with the working code to see what the difference is.