Java Program to read, union and save data - java

I am very new to Java and i would appreciate your help in the thema that i am trying to solve. I would like to program a small Java program that can:
read data (tables)
union them by row
display them in the frame
download the file
I got to the point where I am not sure if the code I wrote is actually productive and I got stuck at displaying the data.
I have prepared a small example of two data files:
car
Row Description Type Example
1 Name String XX
2 Year int 2021
3 Value double 0.37
4 Area double 2.84
5 Weight double 1000
6 Tyre String 210/10 R1
motor
Row Description Type Example
1 A String XY
2 B double 230
3 C int 1000
4 D int 3400
5 E int 1000
You can find my Java code, which at the moment is able to open dialog, select the file with JFileChooser, display the path and read the data (1). I got stuck with displaying the union of two tables and downloading the file. Thanks for any help!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.*;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
#SuppressWarnings("serial")
public class JFileChooserExample extends JPanel {
// use a list model and JList that works *directly* with Files
private DefaultListModel<File> fileListModel = new DefaultListModel<>();
private JList<File> fileJList = new JList<>(fileListModel);
List<String> kfz_list = new ArrayList<>();
List<String> motor_list = new ArrayList<>();
static Path filePath;
static Path filePath2;
static Path car;
static Path motor;
public JFileChooserExample() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new SelectFilesAction("Select Files", KeyEvent.VK_S)));
// help set the width and height of the JList
fileJList.setVisibleRowCount(10);
fileJList.setPrototypeCellValue(new File("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
JScrollPane scrollPane = new JScrollPane(fileJList);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(buttonPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
private class SelectFilesAction extends AbstractAction {
public SelectFilesAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fc.showOpenDialog(JFileChooserExample.this);
if(result == JFileChooser.APPROVE_OPTION) {
fileListModel.clear(); // clear the model of prior files
File[] files = fc.getSelectedFiles();
for (File file : files) {
// add all files to the model
boolean matches = Pattern.matches(".*car*.", file.getPath());
boolean matches2 = Pattern.matches(".*motor*.", file.getPath());
if(matches) {
car = file.toPath();
}
if(matches2) {
motor = file.toPath();
}
System.out.println("car path");
System.out.println(car);
System.out.println("motor path");
System.out.println(motor);
Charset charset = StandardCharsets.UTF_8;
// car read ans instantiate
try (BufferedReader bufferedReader = Files.newBufferedReader(car, charset)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
// System.out.println(line);
kfz_list.add(line);
}
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
Kfz kfz1 = new Kfz();
//kfz1.Kfz("A", 2015, 23.5, 2.3, "B", 12.0);
kfz1.Kfz(kfz_list.get(0), Integer.parseInt(kfz_list.get(1)), Double.parseDouble(kfz_list.get(2)), Double.parseDouble(kfz_list.get(3)), Double.parseDouble(kfz_list.get(4)), kfz_list.get(5));
System.out.println("checking kfz1");
System.out.println(kfz1.getName() + " " + kfz1.getBaujahr());
// motor read and instantiate
try (BufferedReader bufferedReader2 = Files.newBufferedReader(motor, charset)) {
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
// System.out.println(line2);
motor_list.add(line2);
}
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
Motor motor1 = new Motor();
motor1.Motor(motor_list.get(0), Double.parseDouble(motor_list.get(1)), Integer.parseInt(motor_list.get(2)), Integer.parseInt(motor_list.get(3)), Integer.parseInt(motor_list.get(4)));
System.out.println("checking motor1");
System.out.println("Bezeichnung: " + motor1.getBezeichnung() + " " + "Max_drehmoment: " + motor1.getMax_drehmoment());
// end
fileListModel.addElement(file);
}
}
}
}
private static void createAndShowGui() {
JFileChooserExample mainPanel = new JFileChooserExample();
JFrame frame = new JFrame("JFileChooser Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

When working with GUI programs I suggest following the MVC paradigm where all GUI components located at the Gui class. Controller class receiving GUI calls and save them in models and update GUI calls from models.
For your convenience use NetBeans IDE there you have integrated Visual GUI builder
I am intentionally omitting source code examples, because as you can see, you will need a pretty few examples, From the following topics:
GUI
The class extends from javax.swing.JFrame
Controller
Will implement all the listeners like ActionListener, MouseListener, KeyListener and will init all Models. Will sync from GUI to Model
Models
One of the Models is TableModel
To create a custom TableModel simply extend your class from AbstractTableModel and override methods use a 2-dimensional array to store table data.
Download file
To download data from the Model to a file you will need to create a Java object and implement a Serializable interface
To save as Java
try {
FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(cars);
out.close();
} catch (IOException ex) {
Logger.getLogger(CarCatalog.class.getName()).log(Level.SEVERE, null, ex);
}

Related

How to refresh/reload an image in Swing GUI as the real image file changes?

I am trying to implement Remote FrameBuffer Protocol using Java socket programming.
I have a server side program that takes screenshot of the entire screen using robot and store it in BufferedImage .Then I converted it into a byte array and sending it to the client .
Objective :
To display the entire screen of the server side machine in a Swing GUI of the client side.
Problem i am facing :
i am able to send the image in bytes from server and receive it from the server by the client (client.java) and convert it into a jpg image (output.jpg) using ImageIO and put that image in a Swing frame.
But i am able to see the first image in the Swing and whenever the image gets updated ,the image in the Swing is not updating or refreshing .
What I want :
I want the image to refresh and show updated image every time the server sends the image data .
client.java
package remoteclient;
import java.lang.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class client {
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",5900);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int width=0,height=0;
try {
width = din.readInt(); //getting width and height from server thru socket.
height = din.readInt();
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame("Client");
JLabel label = new JLabel();
f.setSize(width, height);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
boolean continueLoop = true;
while(continueLoop)
{
try {
int len = din.readInt();
byte[] imageInByte = new byte[len];
System.out.println(len);
din.readFully(imageInByte);
System.out.println(imageInByte);
ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
BufferedImage bImage2 = ImageIO.read(bis);
// Image im1 = bImage2.getScaledInstance(width,height, Image.SCALE_SMOOTH);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
bImage2 = ImageIO.read(new File("output.jpg"));
label.setIcon(new ImageIcon(im1));
ImageIcon icon = new ImageIcon(bImage2);
icon.getImage().flush();
label.setIcon( icon );
f.getContentPane().add(label, BorderLayout.CENTER);
f.pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What I want :
I want the image to refresh and show updated image every time the server sends the image data .
Updated code with comments about demo code that should be removed from your working code:
Here's an example, using default UIManager icons, and SwingWorker, as noted in the comments to the original posting. You would instead use images from your server connection.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
public class SwingLabelWithUpdatedImage {
public static void main(String args[]) throws Exception {
final JLabel label = new JLabel("", SwingConstants.CENTER);
final JFrame frame = new JFrame("Client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label, BorderLayout.CENTER);
final Dimension preferredSize = new Dimension(200, 100);
frame.setPreferredSize(preferredSize);
frame.setVisible(true);
frame.pack();
final ImageUpdateWorker task = new ImageUpdateWorker(label);
task.execute();
}
public static class ImageUpdateWorker extends SwingWorker<Void, IconInfo> {
// iconInfoList is not need in your code. It's here so I can
// supply a dummy set of icons to demonstrate UI updates.
final List<IconInfo> iconInfoList;
private JLabel label;
ImageUpdateWorker(JLabel label) {
this.label = label;
// Delete this in your code
this.iconInfoList = initIconInfoList();
}
#Override
public Void doInBackground() {
boolean isTrue = true;
while (isTrue) {
// Put your socket code to read the next icon from a server.
// You don't need to do the ImageIO.write(), ImageIO.read() dance,
// unless you must save the icon to disk. In that case, you don't need
// to read it back in.
// Here, I just rotate the iconInfoList to make it
// appear as though a new icon was received.
// Your code will not have any need to do this.
Collections.rotate(iconInfoList, -1);
// Just publish the icon you create from the image
// you receive from your remote server.
publish(iconInfoList.get(0));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void process(List<IconInfo> icons) {
// You might check for an empty list.
// #kleopatra's suggestion to get the last icon is correct.
// See https://docs.oracle.com/javase/tutorial/uiswing/concurrency/interim.html
IconInfo iconInfo = icons.get(icons.size() - 1);
label.setIcon(iconInfo.icon);
// Your code will not do this
label.setText(iconInfo.name);
// You can get the icon dimensions just from the icon,
// so you don't really need the IconInfo class.
label.setSize(iconInfo.dimension);
}
/** Demo code only. It doesn't belong in your working code.
*/
protected List<IconInfo> initIconInfoList() {
// Just a quick way to get some icons; don't need to
// fetch from a server just to demonstrate how to
// refresh the UI.
List<IconInfo> iconInfoList = UIManager.getDefaults().keySet().stream()
.filter(this::isIconKey)
.map(IconInfo::new)
.filter(iconInfo -> iconInfo.icon != null)
.collect(Collectors.toList());
return iconInfoList;
}
/** Demo code only. It doesn't belong in your working code.
*/
protected boolean isIconKey(Object key) {
return String.class.isAssignableFrom(key.getClass())
&& ((String) key).toLowerCase().contains("icon");
}
}
/** This is just a convenience to convey
* the icon and its UIManager key (i.e., name).
* Your remote server doesn't supply a name,
* so you don't really need this class.
* It's just to make the demo more expressive.
*/
public static class IconInfo {
final private String name;
final private Icon icon;
final private Dimension dimension;
IconInfo(Object name) {
this.name = name.toString();
icon = UIManager.getIcon(name);
dimension = icon == null
? new Dimension(32, 32)
: new Dimension(icon.getIconWidth(), icon.getIconHeight());
}
}
}

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);
}
}

fileName cannot be found in addActionListener, JAVA

I'm trying to make a function to play an audio when an user clicks a button. The problem is that when I tried to pass in the fileName from the parameter using "fileName.addActionListener", it says that fileName cannot be found even though it's referenced in the parameter. What did I do wrong, and how can I fix this? Thanks.
package sunaudiodemo;
import static java.awt.Color.blue;
import static java.awt.Color.green;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import sun.audio.*; //import the sun.audio package
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class SunAudioDemo {
public static void playAudioOnClick (final String fileName) {
//*******************************************
fileName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
playAudio(fileName);
} catch (Exception ex) {
Logger.getLogger(SunAudioDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
//*******************************************
}
public static void playAudio (String text) throws Exception {
// identify the sound file as a File class object
File soundFile = new File(text);
// Open an input stream for the File object soundFile
// This allows Java to read the file.
InputStream inFile = new FileInputStream(soundFile);
// Create an AudioStream from the input stream.
// This tells Java to read the incoming data as sound data.
AudioStream audio = new AudioStream(inFile);
// play the sound file using the start method from Audioplayer.player
AudioPlayer.player.start(audio);
}
public static void main(String[] args) throws Exception {
// create a frame to hold our components
JFrame myJFrame = new JFrame();
// create a new a grid layout for the frame - 5 rows x 2 cols, gaps=20
GridLayout myLayout = new GridLayout(5,2);
myLayout.setHgap(20);
myLayout.setVgap(20);
// assign myLayout to be the layout for MyJFrame
myJFrame.setLayout(myLayout);
// Create a button with text OK
JButton wav1 = new JButton("Play Audio 1");
myJFrame.add(wav1); // Add the OK button
playAudioOnClick("wav2.wav");
// set the title, size, location and exit behavior for the JFrame
myJFrame.setTitle("Play Audio");
myJFrame.setSize(360, 480);
myJFrame.setLocation(200, 100);
myJFrame.getContentPane().setBackground( green );
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// make the frame visible (activate the frame)
myJFrame.setVisible(true);
} // end main()
} // end class SunAudioDemo
In the code above, fileName is defined as a String. Assuming this is java.lang.String, there is no method addActionListener(). You need to pass in a reference to your button so you can add the ActionListener to it.

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();
}
}

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