How to load a JList in horizontal manner? - java

How to load a JList in horizontal fashion?? Here is my code,I am trying to display the JListsimilar to the screen shot provided.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.BorderLayout;
import java.io.File;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class Test extends JFrame{
private JList toolsList;
private ArrayList<File> toolXmlList;
public Test()
{
toolXmlList = new ArrayList<File>();
toolXmlList = loadFiles();
setVisible(true);
setSize(300,300);
setTitle("Test Jlist");
createComponents();
}
public void createComponents()
{
toolsList = new JList();
toolsList.setModel(displayDefaltTools());
toolsList.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP);
setLayout(new BorderLayout());
add(toolsList,BorderLayout.CENTER);
}
/**
* Creates a list model and add the tools to it
*
* #return DefaultListModel
*/
public DefaultListModel displayDefaltTools() {
DefaultListModel dlistModel = new DefaultListModel();
String presentation = "";
for (int i = 0; i < toolXmlList.size(); i++) {
//System.out.println(idSet.get(i));
presentation = presentation + toolXmlList.get(i).getName() ;
dlistModel.addElement(presentation);
presentation = "";
}
return dlistModel;
}
public ArrayList loadFiles()
{
ArrayList<File> xmlFiles = new ArrayList<File>();
File f = new File(".");
File [] folList = f.listFiles();
for(int i=0;i<folList.length;i++)
{
if(folList[i].getName().startsWith("Tool_Frag"))
{
File[] fileList=folList[i].listFiles();
for(int j=0;j<fileList.length;j++)
{
System.out.println(fileList[j].getName());
xmlFiles.add(fileList[j]);
}
}
}
return xmlFiles;
}
public static void main(String[] args)
{
new Test();
}
}
I am trying to get a jlist in this manner,items displayed one next to another

You will have to do two things:
Set the LayoutOrientation to JList.HORIZONTAL_WRAP or JList.VERTICAL_WRAP as per the documentation.
Make the list wide enough that it can display more than one element per row. Use setVisibleRowCount() for this.
Calling setPreferredSize() also works but can cause trouble when you use layout managers.
Alternatively, consider using a JTable if you must make sure a certain number of rows/columns (like all elements in a single line).

Related

Getting the cost of an enum through a JList

so I have 4 JLists to contain 4 different parts of a skateboard, the trucks, the wheels, miscellaneous, and decks.
I have four enums set up in my class SkateBoardParts, as such:
public class SkateBoardParts {
public enum Decks {
FIRST_DECK(10),
....
}
double cost;
private Decks(double c){
cost = c;
}
... getCost blah
}
In my GUI, I have a button to calculate. I have an action listener on that button. My goal is to get the cost of all the selected values in the JLists and add them together to get a total. I have the JLists set up as fields. How do I do this? Would I get the index and then use that index to select the value in the enum? Something like this? (I get an error on truckIndex)
double total = 0;
int truckIndex = trucksList.getSelectedIndex();
total += SkateBoardParts.Trucks.truckIndex.getCost();
if you want my entire code for my GUI thus far:
https://pastebin.com/CiSsV8qR
my enum:
https://pastebin.com/WqXs05aK
A simple solution is to store the value of each component at the point at which the user selects the part:
private double partCost = 0.0;
...
JList<SkateBoardPart> list = new JList(SkateBoardPart.values());
list.addListSelectionListener(ev -> partCost = list.getSelectedValue().getCost());
That will keep the cost up to date each time the user selects a part.
Define your JList as follows
private final JList<SkateBoardParts> trucksList = new JList(trucksArray);
In your action listener do the following
JList<SkateBoardParts> list = (JList<SkateBoardParts>) e.getSource();
SkateBoardParts obj = (SkateBoardParts) list.getSelectedValue();
obj.getCost();
Update
Here is an example of SSCCE. Please try to post something similar for better help sooner.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class JListExample extends JFrame {
private final JList<Trucks> trucksList;
public JListExample() {
//create the model and add elements
DefaultListModel<Trucks> listModel = new DefaultListModel<>();
for (Trucks truk: Trucks.values()) {
listModel.addElement(truk);
}
//create the list
trucksList = new JList<>(listModel);
trucksList.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
JList<Trucks> list = (JList<Trucks>) me.getSource();
Trucks truck = (Trucks) list.getSelectedValue();
System.out.println("Cost " + truck.getCost());
}
});
add(trucksList);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JList Example");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JListExample();
}
});
}
}
enum Trucks {
SEVEN_INCH_AXLE(35),
EIGHT_INCH_AXLE(40),
EIGHT_AND_HALF_INCH_AXLE(45);
double cost;
private Trucks(double c) {
cost = c;
}
public double getCost() {
return cost;
}
}

JTable with Comparator accessed wrong row data after sort; removing getModel() fixed it. Why?

It was remarkably easy to introduce sorting for my JTable:
//Existing code
dftTableModel = new DefaultTableModel(0 , 4);
tblOutput = new JTable(dftTableModel);
//Added code
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(dftTableModel);
tblOutput.setRowSorter(sorter);
But since I formatted the Size column as text with commas, it didn't sort:
I had never used a Comparator but found an example that I modified.
public class RowSorterWithComparator
{
static Comparator compareNumericStringsWithCommas;
static TableRowSorter sorter;
static JTable tblOutput;
static JScrollPane pane;
static JFrame frame;
static DefaultTableModel dftTableModel;
// static TableColumnAdjuster tca ;
static DefaultTableCellRenderer rightRenderer;
static JButton btnOpen;
static String[] columnNames = { "Date", "Size" };
static Object rows[][] =
{
{"7/27/2015","96","mavenVersion.xml","C:\\Users\\Dov\\.AndroidStudio1.2\\config\\options\\"},
{"7/27/2015","120","keymap.xml","C:\\Users\\Dov\\.AndroidStudio1.2\\config\\options\\"},
{"7/27/2015","108","Default.xml","C:\\Users\\Dov\\.AndroidStudio1.2\\config\\inspection\\"},
{"4/27/2015","392","key pay.txt","C:\\Users\\Dov\\A\\"},
{"6/13/2015","161","BuildConfig.java","C:\\Users\\Dov\\androidfp2_examples\\eclipse_projects\\FlagQuiz\\gen\\com\\deitel\\flagquiz\\"}
};
public static void main(String args[])
{
compareNumericStringsWithCommas = (Comparator) new Comparator()
{
#Override public int compare(Object oo1, Object oo2)
{
String o1 = oo1.toString().replace(",", "");
String o2 = oo2.toString().replace(",", "");
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
};
dftTableModel = new DefaultTableModel(0 , columnNames.length);
tblOutput = new JTable(dftTableModel);
dftTableModel.setColumnIdentifiers(new Object[]{"Date", "Size", "File name", "Path to file"});
rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
tblOutput.getColumnModel().getColumn(1).setCellRenderer(rightRenderer);
sorter = new TableRowSorter<>(dftTableModel);
sorter.setModel(tblOutput.getModel());
sorter.setComparator(1,compareNumericStringsWithCommas);
tblOutput.setRowSorter(sorter);
tblOutput.setAutoResizeMode(AUTO_RESIZE_OFF);
// tca = new tablecolumnadjuster.TableColumnAdjuster(tblOutput);
// tca.setDynamicAdjustment(true);
tblOutput.setFont(new Font("Courier New",Font.PLAIN,12));
pane = new JScrollPane(tblOutput);
for (int i = 0; i < 5; i++)
dftTableModel.addRow(rows[i]);
btnOpen = new JButton("Open selected file");
btnOpen.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e)
{
int row = tblOutput.getSelectedRow();
String entry = (String)tblOutput.getModel().getValueAt(row, 3)
+ "\\" + (String)tblOutput.getModel().getValueAt(row, 2);
try
{
Desktop.getDesktop().open(new File((entry.trim())));
} catch (IOException ex) {System.out.println("Can't open file"); }
}
});
frame = new JFrame("Sort Table Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane, BorderLayout.CENTER);
frame.add(btnOpen, BorderLayout.AFTER_LAST_LINE);
frame.setSize(800, 350);
frame.setVisible(true);
}
}
Works great.
It was easy to right-justify the size column:
rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
I added a button to open the selected file. But after sorting, the wrong file opened.
So I removed getModel from the statement in the mouse listener:
String entry = (String)tblOutput.getValueAt(row, 3)
+ "\\" + (String)tblOutput.getValueAt(row, 2);
I don't know why it was there in the first place since I've been stealing all
kinds of code from various places.
Anyway, everything works now.
But I have questions:
(1) When would getModel be required in the context of getting a table row's values?
I thought since dftTableModel was used for tblOutput that surely it was proper.
(2) Is the row returned by getModel the row that the data originally was at?
If so, I guess that could be useful on occasion. Not sure when.... To "un-sort"?
(3) Is the fact that I used TableRowSorter the reason getModel didn't get the
right data? (I.e., are the two incompatible?)
(4) Is dftTableModel equivalent to tblOutput.getModel()?
...............................
imports for program:
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import static javax.swing.JTable.AUTO_RESIZE_OFF;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
//import tablecolumnadjuster.TableColumnAdjuster;
So I removed getModel from the statement in the mouse listener:
The data in the TableModel is NOT sorted. The View (JTable) displays the data in a sorted order
You get the data from the view using:
table.getValueAt(row, column);
if you want to get the data from the TableModel you use:
int modelRow = table.convertRpwIndexToModel(row);
table.getModel().getValueAt(modelRow, column);
There are also method for converting the column indexes back and forth.
So you always need to know whether you are trying to access the data the way it is displayed on the JTable or the way it was loaded into the TableModel and then use the appropriate index which may (or may) not involve an index conversion.
String entry = (String)tblOutput.getValueAt(row, 3) ...
When you hardcode a value you need to know what the hard coded value represents. In this case you are accessing a dynamic row value from the table and a column from the model.
So in the above statement you need to convert the "3" from the model to the view since you are using the getValueAt(...) method of the table.
int viewColumn3 = table.convertColumnIndexToView(3);
String entry = (String)tblOutput.getValueAt(row, viewColumn3)
Or, since you are referencing hardcoded values multiple times (ie. columns 2 and 3) it may be easier to keep the hardcoded column indexes and only convert the row index once and then access the data from the TableModel:
String entry = (String)tblOutput.getModel().getValueAt(modelRow, 3) ...
This IS NOW A SSCCE (see comments) but it is a revision of the original code based on suggestions in comments above and below by #camickr.
THIS PROBLEM IS FIXED At present, after dragging column, if filename or path column position has changed, clicking button results in error such as The file: xml\C:\Users\Dov\.AndroidStudio1.2\config\options doesn't exist. This occurred after moving Extension column (which was before Filename column) to after Path column.
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import static javax.swing.JTable.AUTO_RESIZE_OFF;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
//import tablecolumnadjuster.TableColumnAdjuster;
public class RowSorterWithComparator
{
static final int DATE_COLUMN = 0;
static final int SIZE_COLUMN = 1;
static final int EXTENSION_COLUMN= 2;
static final int FILENAME_COLUMN = 3;
static final int PATH_COLUMN = 4;
public static void main(String args[])
{
Comparator compareNumericStringsWithCommas;
TableRowSorter sorter;
JTable tblOutput;
JScrollPane pane;
JFrame frame;
DefaultTableModel dftTableModel;
// TableColumnAdjuster tca ;
DefaultTableCellRenderer rightRenderer;
JButton btnOpen;
Object[] columnNames = new Object[]{"Date", "Size", "Extension", "File name", "Path to file"};
Object rows[][] =
{
{"7/27/2015","9,600","xml","mavenVersion.xml","C:/Users/Dov/.AndroidStudio1.2/config/options/"},
{"7/27/2015","120,000","xml","keymap.xml","C:/Users/Dov/.AndroidStudio1.2/config/options/"},
{"7/27/2015","108","xml","Default.xml","C:/Users/Dov/.AndroidStudio1.2/config/inspection/"},
{"4/27/2015","39,200","txt","key pay.txt","C:/Users/Dov/A/"},
{"6/13/2015","91","java","BuildConfig.java","C:/Users/Dov/androidfp2_examples/eclipse_projects/FlagQuiz/gen/com/deitel/flagquiz/"}
};
compareNumericStringsWithCommas = (Comparator) new Comparator()
{
#Override public int compare(Object oo1, Object oo2)
{
String o1 = oo1.toString().replace(",", "");
String o2 = oo2.toString().replace(",", "");
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
};
dftTableModel = new DefaultTableModel(0 , columnNames.length);
tblOutput = new JTable(dftTableModel);
dftTableModel.setColumnIdentifiers(columnNames);
rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
tblOutput.getColumnModel().getColumn(1).setCellRenderer(rightRenderer);
sorter = new TableRowSorter<>(dftTableModel);
sorter.setModel(tblOutput.getModel());
sorter.setComparator(1,compareNumericStringsWithCommas);
tblOutput.setRowSorter(sorter);
tblOutput.setAutoResizeMode(AUTO_RESIZE_OFF);
// tca = new tablecolumnadjuster.TableColumnAdjuster(tblOutput);
// tca.setDynamicAdjustment(true);
tblOutput.setFont(new Font("Courier New",Font.PLAIN,12));
pane = new JScrollPane(tblOutput);
for (Object[] row : rows)
dftTableModel.addRow(row);
btnOpen = new JButton("Open selected file");
btnOpen.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
int viewFilenameCol = tblOutput.convertColumnIndexToView(FILENAME_COLUMN);
int viewPathCol = tblOutput.convertColumnIndexToView(PATH_COLUMN);
int row = tblOutput.getSelectedRow();
String entry = (String)tblOutput.getValueAt(row, viewPathCol)
+ (String)tblOutput.getValueAt(row, viewFilenameCol);
try
{
Desktop.getDesktop().open(new File((entry.trim())));
}
catch
(
Exception ex) {System.out.println("Can't open file <" + entry + ">");
}
}
});
frame = new JFrame("Sort Table Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane, BorderLayout.CENTER);
frame.add(btnOpen, BorderLayout.SOUTH);
frame.setSize(800, 350);
frame.setVisible(true);
}
}

Two jcombobox options displaying path

I need to display two connected combo boxes with directory names. There is a start path which contains multiple directories that are displayed in the first jcombobox, and when a directory is selected, the sub directories need to be displayed in the second jcombobox. The second jcombobox should be able to select one of those sub directories. Each of sub sub directories contains multiple .txt files. I managed to display the directories and sub directories on both jcomboboxes including the files.
package calc.my.pay;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JComboBox;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.JScrollPane;
public class CalcMyPay extends JFrame implements ActionListener {
private JPanel contentPane;
private JScrollPane scrollPane;
private JComboBox folderSelector, subFolderSelector;
private File[] directory, subDirectory;
private String subPath, finalSubPath, selectedSubDirectory, finalSubDirectory;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CalcMyPay frame = new CalcMyPay();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public CalcMyPay()
{
setBackground(Color.LIGHT_GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(350, 10, 1000, 700);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
scrollPane = new JScrollPane();
scrollPane.setBounds(12, 120, 958, 300);
String startPath = "C:/Users/Zeus/Desktop/Content/";
// The starting path of the file
directory = new File(startPath).listFiles();
// Folders dropdown box
folderSelector = new JComboBox();
folderSelector.setBounds(60, 13, 200, 22);
folderSelector.insertItemAt("Choose directory", 0);
folderSelector.setSelectedIndex(0);
for(int i=0; i < directory.length; i++) {
System.out.println(directory[i]);
folderSelector.addItem(directory[i].getName());
}
contentPane.add(folderSelector);
// Sub folder dropdown box
subFolderSelector = new JComboBox();
subFolderSelector.setBounds(300, 13, 200, 22);
subFolderSelector.insertItemAt("Choose subdirectory", 0);
subFolderSelector.setSelectedIndex(0);
contentPane.add(subFolderSelector);
folderSelector.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the folder dropdown selected item
selectedSubDirectory = folderSelector.getSelectedItem().toString();
//System.out.println("Folder selected: " + Arrays.asList(directory).toString().contains(selectedSubDirectory));
//System.out.println("Subfolders based on folder selected : " + Arrays.asList(directory) + " " + selectedSubDirectory);
//subFolderSelector.addItem(folderSelector.getSelectedItem());
// Check if the array from the main directory contains the selected directory
if(Arrays.asList(directory).toString().contains(selectedSubDirectory)) {
// Make a new file that list all the directories in the given path
subPath = startPath + selectedSubDirectory;
subDirectory = new File(subPath).listFiles();
// Sort the array directory in a descending order
Arrays.sort(subDirectory, Collections.reverseOrder());
// Delete the previous list items, if any
subFolderSelector.removeAllItems();
// Iterate through all the directories in the selected folder
for(int i=0; i < subDirectory.length; i++) {
// Pass only directories (files will be omitted)
// ### Should check if directory contains only 4 numbers here
if(subDirectory[i].isDirectory()) {
//subFolderSelector.addItem(folderSelector.getSelectedItem());
subFolderSelector.addItem(subDirectory[i].getName());
}
}
}
}
});
subFolderSelector.addActionListener(new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
count++;
if(count == 3) {
selectedSubSubDirectory = subFolderSelector.getSelectedItem().toString();
// Make an new file that list all the file in the selected sub folder
if(Arrays.asList(subDirectory).toString().contains(selectedSubDirectory)) {
//textFiles = new File(finalSubPath).listFiles();
subSubPath = startPath + selectedSubDirectory + "/" + selectedSubSubDirectory;
textFiles = new File(subSubPath).listFiles();
for(File file: textFiles) {
if(file.isFile() && file.toString().toLowerCase().endsWith("_110.txt")) {
System.out.println(file);
}
}
}
count = 0;
}
}
});
}
}
However as you can see in the second actionListener for the subDirectorySelector i have a counter. The code there executes three times (because the second jcombobox changes value). There is an error if you select the same path twice in the first jcombobox. There must be a better (and possibly) shorter way to do this. What would you change?
Thanks
I tried to make my own version but it's really similar, except I removed the actionListener before updating the subFolder selector and I added more checks.
Here is my code :
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ComboDemo extends JFrame implements ActionListener {
private String rootDir;
private JComboBox box1;
private JComboBox box2;
/**
* Create the frame.
*/
public ComboDemo () {
super("Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGui();
this.rootDir = "/home";
setRootDir(new File(this.rootDir));
}
/**
* Create the gui components.
*/
private void createGui () {
this.box1 = new JComboBox();
this.box2 = new JComboBox();
this.box1.addActionListener(this);
this.box2.addActionListener(this);
this.box1.insertItemAt("Choose directory :", 0);
this.box1.setSelectedIndex(0);
this.box2.insertItemAt("Choose subdirectory :", 0);
this.box2.setSelectedIndex(0);
setLayout(new FlowLayout(FlowLayout.LEADING));
add(this.box1);
add(this.box2);
}
/**
* Show the gui.
*/
private void showGui () {
setSize(500, 250);
setLocationRelativeTo(null);
setVisible(true);
}
/**
* Update the first selector with the directories listed under the specified
* root directory.
*
* #param dir
* Root directory.
*/
private void setRootDir (File dir) {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
this.box1.addItem(file.getName());
}
}
}
#Override
public void actionPerformed (ActionEvent e) {
if (e.getSource() instanceof JComboBox) {
JComboBox box = (JComboBox) e.getSource();
// Box 1
if (this.box1.equals(box)) {
String dirName = box.getSelectedItem().toString();
// RootDir / Folder
File dir = new File(this.rootDir + File.separator + dirName);
System.out.println("# Folder : " + dir.getPath());
// Check if there is a least one file
if (dir.exists() && dir.listFiles().length > 0) {
Arrays.sort(dir.listFiles(), Collections.reverseOrder());
// Reset box2
this.box2.removeAllItems();
this.box2.insertItemAt("Choose subdirectory :", 0);
// Update Box2
this.box2.removeActionListener(this);
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
this.box2.addItem(file.getName());
}
}
this.box2.addActionListener(this);
this.box2.setSelectedIndex(0);
}
}
// Box 2
else if (this.box2.equals(box)) {
// Check if box2 is empty
if (box.getItemCount() > 0) {
String dirName = box.getSelectedItem().toString();
// RootDir / Folder / SubFolder
File dir = new File(this.rootDir + File.separator + this.box1.getSelectedItem().toString()
+ File.separator + dirName);
System.out.println("# SubFolder : " + dir.getPath());
// Check if there is a least one file
if (dir.exists() && dir.listFiles().length > 0) {
Arrays.sort(dir.listFiles(), Collections.reverseOrder());
// Print .txt files
for (File file : dir.listFiles()) {
if (file.isFile() && file.getName().endsWith(".txt")) {
System.out.println("\t" + file.getName());
}
}
}
}
}
}
}
public static void main (String[] args) {
ComboDemo demo = new ComboDemo();
demo.showGui();
}
}

Instead of the picture it shows me the x.png inside the cell, how can i make it SHOW the actual picture or put some background color when value=="1"

package dmaze2;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Dmaze2 extends JPanel
{
JTable jt;
public Dmaze2()
{
String[] columns = {"1","2","3","4","5","6","7","8"};
Object[][] table={{"f","f","f","f","f","f","f","f"},
//if this table is string makes problem to add picture
{"f","f","f","f","f","f","f","f"},
{"f","f","f","f","f","f","f","f"},
{"f","f","f","f","f","f","f","f"},
{"f","f","f","o","f","f","f","f"},
{"f","f","f","f","f","f","f","f"},
{"f","f","f","f","f","f","f","f"},
{"f","f","f","f","f","f","f","f"}};
int num=0;
ImageIcon Icon = new ImageIcon("x.png");
//i have the image in all files of the project to be sure it finds it
for (int i = 0; i < 8 ; i++)
{
int a=1;
for (int j = 0; j<7 && a<8; j++,a++)
{
if(table[i][j]=="f" && table[i][a]=="f")
{
num=num+1;
table[i][j]=Icon;
//if i try to enter the image here it will show it as x.png (as string) instead of the actual picture
table[i][a]="u";
}
}
//int b=1;
for (int j = 0; j<8 && i<7; j++)
{
if(table[i][j]=="f" && table[i+1][j]=="f")
{
num=num+1;
table[i][j]="u";//we put the block used
table[i+1][j]="u";
}
}
System.out.println("");
}
jt = new JTable(table,columns);
{
}
jt.setPreferredScrollableViewportSize(new Dimension(350,363));
jt.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(jt);
add(jps);
}
public static void main(String[] args)
{
JFrame jf = new JFrame();
Dmaze2 t = new Dmaze2();
jf.setTitle("Depth First Search");
jf.setSize(500, 500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}
You need to #Override the getColumnClass() of the table's XxxTableModel. If you don't the renderer will render the column as the Object.toString(). See more at Concepts: Editors and Renderers
DefaultTableModel model = new DefaultTableModel(tableData, columns) {
#Override
public Class<?> getColumnClass(int column) {
switch(column) {
case 1: return ImageIcon.class; // or whichever column you want
default: return String.class;
}
}
};
JTable table = new JTable(model);
Side Notes:
Have a look at How Do I Compare Strings in Java
Set your frame visible after adding all your components
Swing apps should be run on the Event Dispatch Thread. See more at Initial Threads
You may want to read your image files from the class path if the images are resources of your application. Passing a String path to the ImageIcon signifies a read from the local file system. At time of deployment, the path you use will no longer be valid. See the answers from this question and this question for more details on how you can accomplish this task of reading from the class path and embedding your resources.

Simple Java editor GUI

Hello i create the GUI code for simple Java editor
i create the menu but i need to match
File: New: Create a new file. asking for the name of the file (and therefore the public class) and the directory in which it will be stored. With the creation of the file is inserted into the structure of the public class, for example public class MyClass{ }.
Open: opens files with source code java ( .java).
Save : saves the current snippet on the same file with this established during the creation of.
Save as : displays the dialog box where you requested the name of the file, the format of the directory in which it will be stored. The format will be java file ( .java). The main part of the window will have the editor to be used by the user to edit a file source Java.
The main part of the window will have the editor to be used by the user to edit a file source Java. information which will be renewed during the processing of a snippet: Number lines Number reserved words in java source code
Formatting Text
Each file will open formatted and will formatted when processed in the following rules: The reserved words of java will appear with color blue.
The comments will appear in green
The String Literals with orange
All other with black
The Font will be Courier Font size 12pt
i will provide the GUI code can anyone help me with the above ?
Regards
Antonis
// ClassEEFrame
package editor.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class EEFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -1709009137090877913L;
private GridBagLayout layout;
private GridBagConstraints constraints;
private EEMenuBar menuBar;
private EETextPane editor;
private EEConsole console;
private EEStatusBar statusBar;
private File file;
public EEFrame() throws HeadlessException {
super("Elearn Editor");
JScrollPane scrollPane;
layout = new GridBagLayout();
setLayout(layout);
constraints = new GridBagConstraints();
menuBar = new EEMenuBar();
setJMenuBar(menuBar);
editor = new EETextPane();
scrollPane = new JScrollPane(editor);
scrollPane.setBorder(new TitledBorder("Editor"));
setConstraints(1, 100, GridBagConstraints.BOTH);
addComponent(scrollPane, 0, 0, 1, 1);
console = new EEConsole();
scrollPane = new JScrollPane(console);
scrollPane.setBorder(new TitledBorder("Console"));
setConstraints(1, 40, GridBagConstraints.BOTH);
addComponent(scrollPane, 1 ,0 ,1, 1);
statusBar = new EEStatusBar();
setConstraints(1, 0, GridBagConstraints.BOTH);
addComponent(statusBar, 2, 0, 1, 1);
file = null;
}
public JTextPane getTextPane() {
return this.editor;
}
public void setLines(int lines) {
this.statusBar.setLines(lines);
}
public void setWords(int words) {
this.statusBar.setJavaWords(words);
}
private void setConstraints(int weightx, int weighty, int fill) {
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.fill = fill;
}
private void addComponent(Component component, int row, int column, int width, int height) {
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
add(component);
}
private class EEMenuBar extends JMenuBar {
/**
*
*/
private static final long serialVersionUID = -2176624051362992835L;
private JMenu fileMenu, compilationMenu;
private JMenuItem newItem, openItem, saveItem, saveAsItem, exportItem, compileProcessItem, compileClassItem;
public EEMenuBar() {
super();
fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/* TODO Dispay dialog with inputs class name and file path */
}
});
fileMenu.add(newItem);
openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Open existing java source file*/
}
});
fileMenu.add(openItem);
saveItem = new JMenuItem("Save");
saveItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO save changes to file*/
}
});
fileMenu.add(saveItem);
saveAsItem = new JMenuItem("Save As");
saveAsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Save as new java source file*/
}
});
fileMenu.add(saveAsItem);
exportItem = new JMenuItem("Export to pdf");
exportItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO save as pdf(formatted)
}
});
fileMenu.add(exportItem);
add(fileMenu);
compilationMenu = new JMenu("Compilation");
compileProcessItem = new JMenuItem("Compile with system jdk");
compileProcessItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Compile java source code and show results in teminal(inside editor)*/
}
});
compilationMenu.add(compileProcessItem);
compileClassItem = new JMenuItem("Compile with JavaCompiler Class");
compileClassItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Call system compiler for file*/
}
});
compilationMenu.add(compileClassItem);
add(compilationMenu);
}
}
private class EETextPane extends JTextPane {
/**
*
*/
private static final long serialVersionUID = -7437561302249475096L;
public EETextPane() {
super();
//add styles to document
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
StyleConstants.setForeground(def, Color.BLACK);
StyleConstants.setFontFamily(def, "Courier");
StyleConstants.setFontSize(def, 12);
Style keyword = addStyle("keyword", def);
StyleConstants.setForeground(keyword, Color.BLUE);
Style literal = addStyle("literal", def);
StyleConstants.setForeground(literal, Color.ORANGE);
Style comment = addStyle("comment", def);
StyleConstants.setForeground(comment, Color.GREEN);
}
}
private class EEConsole extends JTextPane {
/**
*
*/
private static final long serialVersionUID = -5968199559991291905L;
public EEConsole() {
super();
//add styles to document
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
StyleConstants.setForeground(def, Color.BLACK);
StyleConstants.setFontFamily(def, "Courier");
StyleConstants.setFontSize(def, 12);
Style keyword = addStyle("error", def);
StyleConstants.setForeground(keyword, Color.RED);
Style literal = addStyle("success", def);
StyleConstants.setForeground(literal, Color.GREEN);
}
}
private class EEStatusBar extends JPanel {
/**
*
*/
private static final long serialVersionUID = 185007911993347696L;
private BoxLayout layout;
private JLabel linesLabel, lines, wordsLabel, words;
public EEStatusBar() {
super();
layout = new BoxLayout(this, BoxLayout.X_AXIS);
setLayout(layout);
linesLabel = new JLabel("Lines : ");
linesLabel.setAlignmentX(LEFT_ALIGNMENT);
add(linesLabel);
lines = new JLabel("");
lines.setAlignmentX(LEFT_ALIGNMENT);
add(lines);
add(Box.createRigidArea(new Dimension(10,10)));
wordsLabel = new JLabel("Java Words : ");
wordsLabel.setAlignmentX(LEFT_ALIGNMENT);
add(wordsLabel);
words = new JLabel("");
words.setAlignmentX(LEFT_ALIGNMENT);
add(words);
}
public void setLines(int lines) {
/*TODO set line numbers */
}
public void setJavaWords(int words) {
/*TODO set java keyword numbers*/
}
}
}
//class Main
package editor.app;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import elearning.editor.gui.EEFrame;
import elearning.editor.util.EECodeFormater;
import elearning.editor.util.EEJavaWordCounter;
import elearning.editor.util.EELineCounter;
public class EEditor {
/**
* #param args
*/
public static void main(String[] args) {
try {
// Set cross-platform Java L&F (also called "Metal")
//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
//Set Motif L&F
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
//Set Nimbus L&F
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
//Set System L&F
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//Set GTK L&F --> Same as System L&F on Linux and Solaris\
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
//Set Windows L&F --> Same as System L&F on Windows
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (UnsupportedLookAndFeelException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
catch (InstantiationException e) {
// handle exception
}
catch (IllegalAccessException e) {
// handle exception
}
EEFrame frame = new EEFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
/* TODO Instatiate Threads */
/*TODO Start Threads */
}
}
Also i provide a mockup of it:
Mockup
First you should have a look at the File class. It provides you methods to create, open, modify and save files. To read files you also might want to give BufferedReader or any other Reader a shot.
Creating a file: File has the method createNewFile(), use it in combination with exists().
To open and read a file use a try-with-resource (There's actually a nice tutorial about it in the Java Manuals).
To save a file you should check out the FileWriter, it can write strings or append them to files.
For your editor you might want to replace the before mentioned BufferedReader with a LineReader, which also provides methods to get the line number. Other than that you have to figure out yourself how to number the lines. (Actually it's just googling around a lot, there will be some ideas like this one - which I didn't check in detail but it might help).
Of course for the editor you should first read the file into a string, use a formatter for it and then you can present it and reformat it when needed.
Apart from these hints I can not provide you with more detailed answers, as you can also read in the comments it would be easier if you would provide more detailed questions. You now just gave us a GUI which has almost nothing to do with your actual problems.
Show us some of your (problematic) work and we can help you, but otherwise we can not do much more than giving you some hints as I just did. So try to think about your problems, try how to ask for more precise answers and open some new questions if you want.
But don't forget to check out the site for answers, for me almost all of my questions I'd like to ask are already asked somewhere in a similar manner.
Hello again lets split work into steps ,
firstly i would like to create the new,open,save ,save as , export into pdf menu and event
below is the code that i used ,the GUI frame open correctly with new ,open,save, save as ,export into pdf labels but as action nothing happened.
Could someone write to me the correct code for that? be in mind i am very java beginner.
public EEMenuBar() {
super();
fileMenu = new JMenu("File");
//Create the New menu item
newItem = new JMenuItem("New");
newItem.setMnemonic(KeyEvent.VK_N);
newItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
fileMenu.add(newItem);
openItem = new JMenuItem("Open");
openItem.setMnemonic(KeyEvent.VK_0);
openItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Open existing java source file*/
}
});
fileMenu.add(openItem);
saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_S);
saveItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO save changes to file*/
}
});
fileMenu.add(saveItem);
saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic(KeyEvent.VK_A);
saveAsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Save as new java source file*/
}
});
fileMenu.add(saveAsItem);
exportItem = new JMenuItem("Export to pdf");
exportItem.setMnemonic(KeyEvent.VK_E);
exportItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO save as pdf(formatted)
}
});
fileMenu.add(exportItem);

Categories