I can set the default File Name: in a JFileChooser window using:
fileChooser.setSelectedFile();
I was wondering if it is also possible to select it, so that if you want to save the file as something else you can immediately start to overtype it. Thanks for any help on this.
package filetest;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
#SuppressWarnings("serial")
class Editor {
public static class TextClass extends JTextArea {
FileClass fileClass = new FileClass();
public void setKeyboardShortcuts() {
fileClass.setKeyboardShortcuts();
}
private class FileClass {
private File directory;
private String filepath = "";
private String filename = "";
private void setKeyboardShortcuts() {
Action ctrlo = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
openFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl O"), "ctrlo");
getActionMap().put("ctrlo", ctrlo);
Action ctrls = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
saveFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl S"), "ctrls");
getActionMap().put("ctrls", ctrls);
}
private String selectFile(String fileaction) throws FileNotFoundException {
JFileChooser filechooser = new JFileChooser();
if (directory != null) {
filechooser.setCurrentDirectory(directory);
} else {
filechooser.setCurrentDirectory(new File("."));
}
filechooser.setSelectedFile(new File(filepath));
int r = 0;
if (fileaction.equals("openfile"))
r = filechooser.showDialog(new JPanel(), "Open file");
else
r = filechooser.showDialog(new JPanel(), "Save file");
if (r == JFileChooser.APPROVE_OPTION) {
try {
directory = filechooser.getSelectedFile().getParentFile();
filename = filechooser.getSelectedFile().getName();
return filename;
} catch (Exception exception) {
return "";
}
} else {
return "";
}
}
private void openFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("openfile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void saveFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("savefile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
createAndShowGui();
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
JTextArea textArea = new TextClass();
frame.add(textArea);
((TextClass) textArea).setKeyboardShortcuts();
frame.setVisible(true);
}
}
It does that by default on the machine I'm typing from:
package stackoverflow;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* #author ub
*/
public class StackOverflow
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png");
chooser.setFileFilter(filter);
chooser.setSelectedFile(new File("C:\\Users\\ub\\Pictures\\Capt.PNG"));
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
}
}
It's because when you first call .setSelectedFile your filepath is an empty string.
You set your filepath variable after having shown the file chooser to the user.
If you print to console the string value of filepath, right before invoking .showDialog, you should see this.
The problem seems to be caused by these lines:
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
If they are removed, the file name is highlighted as in Unai Vivi's example.
Related
I don't know what is wrong with the code. Can you help me figure it out?
private void doOpenFile() {
int result = myFileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
Path path = myFileChooser.getSelectedFile().toPath();
try {
String contentString = "";
for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
contentString += s;
}
jText.setText(contentString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void doSaveFile() {
int result = myFileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
// We'll be making a mytmp.txt file, write in there, then move it to
// the selected
// file. This takes care of clearing that file, should there be
// content in it.
File targetFile = myFileChooser.getSelectedFile();
try {
if (!targetFile.exists()) {
targetFile.createNewFile();
}
FileWriter fw = new FileWriter(targetFile);
fw.write(jText.getText());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm not sure how do you use your myFileChooser and how do you instantiate them but this code works well :
public class ForTestApplication {
public static void main(String[] args) {
Window window = new Window();
window.setVisible(true);
window.showFileChooser();
}
static class Window extends JFrame {
JFileChooser jFileChooser = new JFileChooser();
public void showFileChooser() {
jFileChooser.showDialog(this, "Just for test");
}
}
}
Here is screenshot :
Please, provide more code to figure out what is going on.
I read a file and set the text(about 4000KB of size) into a JTextArea. It freezes my application. Following is my code snippet. I appreciate your suggestions....
public void setText(final JTextArea textArea)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
BufferedReader from = null;
try
{
from = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
System.out.println("Started..........");
textArea.read(from, file.getName());
System.out.println("Completed..........");
}
catch (Exception ex)
{
Logger.getLogger(FileTools.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try
{
from.close();
}
catch (IOException ex)
{
Logger.getLogger(FileTools.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
Below is my code:-
public class MainScreen extends javax.swing.JFrame {
private TableRowSorter<TableModel> sorter;
public MainScreen() {
initComponents();
this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
sorter = new TableRowSorter<>(tblCustomer.getModel());
tblCustomer.setRowSorter(sorter);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
System.out.println("I'm here "+findAll.size());
((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
tblCustomer.setAutoCreateRowSorter(true);
tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);
}
public static Vector getDataVector(List<BasicDetailsDTO> listData) {
Vector dataVector = new Vector();
for (BasicDetailsDTO instance : listData) {
Vector row = new Vector();
row.add(instance.getId());
row.add(instance.getParticulars());
row.add(instance.getBookedBy());
row.add(instance.getContactPerson());
row.add(instance.getMobileNo());
row.add(instance.getEmail_id());
dataVector.add(row);
}
return dataVector;
}
public static Vector getVectorHeader() {
Vector header = new Vector();
header.add("ID");
header.add("Particulars");
header.add("BOOKED BY");
header.add("CONTACT PERSON");
header.add("MOBILE NO");
header.add("EMAIL ID");
return header;
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
}
private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please Select the Record");
return;
}
int option = displayConfirmDialog("Do you Really want to delete Record ?");
if (option == JOptionPane.YES_OPTION) {
String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));
instance.setDeleted(Boolean.TRUE);
UtilDAO.getDaoBasicDetails().remove(instance);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
getDataVector(findAll);
displayMessage(" Record Deleted ");
}
}
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);
}
private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() == 2) {
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
}
}
private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
}
private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
}
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
if (txtSearch.getText().trim().length() > 0) {
RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
String search = txtSearch.getText().trim().toLowerCase();
// System.out.println(entry.getStringValue(1));
return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
}
};
sorter.setRowFilter(filter);
//sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
// System.out.println("New Row is " + filter);
} else {
sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
}
} else {
if (tblCustomer.getRowCount() > 0) {
tblCustomer.requestFocus();
tblCustomer.setRowSelectionInterval(0, 0);
} else {
txtSearch.requestFocus();
}
}
}
private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
IContext context = report.createContext();
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
context.put("Customer", instance);
OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
report.process(context, out);
Desktop desktop = Desktop.getDesktop();
File f = new File("Passenger Name_Out.docx");
desktop.open(f);
} catch (IOException | XDocReportException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
new MainScreen().setVisible(true);
}
});
}
public static void setlblMessageDetail(String msg) {
MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
MainScreen.lblMessage.setText(msg);
}
// Variables declaration - do not modify
}
Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window.
Kindly help me through.
Thanks in advance.
why voids for DefaultTableModel and JTableHeader are static
remove rows from DefaultTableModel
use DocumentListener instead of KeyListener for RowFilter
why is there initialized two different LookAndFeels
updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread
search for ResultSetTableModel, TableFromDatabase, BeanTableModel
rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class
Hello guys i want to make ProgressBar who will loading till the song starts ...
i have this code but the ProgressBar is starting when the song starts and also its maked to finish it about 5 sec. so please someone help me make it right ... Thanks :)
package passwordsaver1;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
public final class Music extends javax.swing.JFrame {
void centreWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - getWidth()) / 2);
int y = (int) ((dimension.getHeight() - getHeight()) / 2);
setLocation(x, y);
}
public Music(String mainAccName) {
initComponents();
centreWindow();
setTitle("PasswordSaver - Music");
this.mainAccName = mainAccName;
}
String mainAccName;
private void pitbullActionPerformed(java.awt.event.ActionEvent evt) {
try {
URL url = new URL("http://mini-mk-market.com/music/PitBulll.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais;
ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.loop(5);
clip.start();
new Thread(new Start()).start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Can't find Internet Connection !");
}
}
// this is just for testing does the song will stop after clicking the new... but cant..
private void afrojackActionPerformed(java.awt.event.ActionEvent evt) {
try {
URL url = new URL("http://mini-mk-market.com/music/PitBulll.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais;
ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.loop(0);
clip.start();
new Thread(new Start()).start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Can't find Internet Connection !");
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info:
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//new Music().setVisible(true);
}
});
}
private class Start implements Runnable {
#Override
public void run() {
for (int x = 0; x < 101; x++) {
ProgressBar.setValue(x);
ProgressBar.repaint();
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
}
}
You may be looking for ProgressMonitorInputStream. There 's a discussion in How to Use Progress Monitors, and an example in ProgressMonitorDemo.
I wrote program that listen Clipboard and worked correctly, but i saw that the program use more CPU usage. CPU usage is more 70%. Why? Can i reduce it? or i want Listener that listen windows's copy action. Is there Listener in java for this?
This is my code:
package yoxlama;
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;
import java.net.MalformedURLException;
class ClipBoardListener extends Thread implements ClipboardOwner {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
static ClipBoardListener b;
Interlsoft interlsoft = new Interlsoft();
public void run() {
try{
Transferable trans = sysClip.getContents(this);
regainOwnership(trans);
}catch (Exception e) {
try {
b.finalize();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
b= new ClipBoardListener();
b.start();
System.out.println("NESE1");
}
System.out.println("Listening to board...");
while(true) {}
}
public void lostOwnership(Clipboard c, Transferable t) {
try {
Thread.sleep(50);
} catch(Exception e) {
System.out.println("Exception: " + e);
}
try{
Transferable contents = sysClip.getContents(this);
processContents(contents);
regainOwnership(contents);
}catch (Exception e) {
try {
b.finalize();
b= new ClipBoardListener();
b.start();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("nese");
}
}
void processContents(Transferable t) throws MalformedURLException, IOException {
String str = getClipboard(t);
if(str!=null){
str= str.replace("\n", "%0D%0A");
str= str.replace("\r", "");
str= str.replace("\t", "");
str= str.replace("/", "");
str= str.replace("-", "");
interlsoft.translate(str);
}
// System.out.println("Processing: " + getClipboard(t));
}
void regainOwnership(Transferable t) {
sysClip.setContents(t, this);
}
public static void main(String[] args) {
b = new ClipBoardListener();
b.start();
}
public static String getClipboard(Transferable t) {
// Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String)t.getTransferData(DataFlavor.stringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
System.out.println("BURDA1");
} catch (IOException e) {
System.out.println("BURDA1");
}
return null;
}
}
This: while(true) {}
Your poor CPU. Instead of while true, just make that thread sleep indefinitely. See: How do you hang a thread in Java in one line?