im working with Java Swing.
Im trying with print method of Jtable...
public void actionPerformed(java.awt.event.ActionEvent ignore) {
MessageFormat header = new MessageFormat("Page {0,number,integer}");
try {
table.print(JTable.PrintMode.FIT_WIDTH, header, null);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
}
To show a printing dialog . Its work fine ..
The printing dialog
But i want to change the text dialog language to Spanish with a Locale class , how can i do it ???
Thanks!
#Diego
I copied your solution here so it can be more easily read.
It was inspire by the old forum entry here: https://forums.oracle.com/thread/1287832
---- Begin ----
Just adding reflection to change the ResourceBlunde before Jtable.print() method...
try {
Class cl = Class.forName("sun.print.ServiceDialog");
if (cl != null) {
Field fld = cl.getDeclaredField("messageRB");
if (fld != null) {
fld.setAccessible(true);
fld.set(cl, ResourceBundle.getBundle("sun.print.resources.serviceui_es"));
}
}
} catch (Exception ex11) {
ex11.printStackTrace();
}
---- End ----
I may want to search and find it someday.
Related
I am quite new to Eclipse Plugin development so I need a bit of help.
I have a project in which I must get the current position of the cursor within an active editor and upon clicking a button, I am to display in a dialog box the method directly surrounding it. I have tried the following and I am so far only able to get the name of the method, but not the entire source code as I want. If I try only with compilationUnit I can also get the entire source code of the active editor. Other questions seem to only require the name of the method, but I'm interested in getting the full source code of the method. Is there any way I can get the source code of only the method directly surrounding the cursor?
IWorkbenchPage page = window.getActivePage();
IEditorPart editor = page.getActiveEditor();
ITextEditor textEditor = (ITextEditor) page.getActiveEditor();
IJavaElement element = JavaUI.getEditorInputJavaElement(textEditor.getEditorInput());
if (element instanceof ICompilationUnit) {
ITextSelection selection = (ITextSelection) ((JavaEditor) textEditor).getSelectionProvider().getSelection();
IJavaElement selected;
try {
selected = ((ICompilationUnit) element).getElementAt(selection.getOffset());
if (selected != null && selected.getElementType() == IJavaElement.METHOD) {
return (IMethod) selected;
}
MessageDialog.openInformation(
window.getShell(),
editor.getTitle(),
selected +"\n"); //(IMethod)
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Yeah so I found an answer. It took a while but I finally figured it out.
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
try {
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelection selection = workbenchWindow.getSelectionService().getSelection();
ITextSelection textSelection;
if (selection instanceof ITextSelection)
textSelection = (ITextSelection) selection;
else
throw new RuntimeException("No text selection");
IEditorInput editorInput = workbenchWindow.getActivePage().getActiveEditor().getEditorInput();
ICompilationUnit compilationUnit = JavaUI.getWorkingCopyManager().getWorkingCopy(editorInput);
IJavaElement elementWithCursorInside = compilationUnit.getElementAt(textSelection.getOffset());
ISourceReference sourceReference;
if (elementWithCursorInside instanceof ISourceReference)
sourceReference = (ISourceReference) elementWithCursorInside;
else
throw new RuntimeException("Not an ISourceReference");
MessageDialog.openInformation(window.getShell(), "Source Code of the Method", sourceReference.getSource());
} catch (Exception e) {
e.printStackTrace();
}
return null;
this seems to work well for me now. I hope maybe my solution will help someone else with the same problem
I'm build one application that needs a request from the user. The first version of the app I made one input window myself, but I found better change to the showInputDialog since it's it's a pre-molded tool from JOptionFrame. Now I'm having problems with the event trigger; check out the code below:
SearchScreen:
public class SearchScreen extends EventSearch{
...
public SearchScreen(){
userQuery = (String) JOptionPane.showInputDialog("Type Keywords in english to be requested below:");
}
...
}
EventSearch:
public class EventSearch extends TabBuilder{
public EventSearch() {
}
public void actionPerformed(ActionEvent Ev) {
try {
System.out.println("worked");
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "FAIL");
}
};
}
TabBuilder:
public class TabBuilder implements ActionListener {
.....
}
Then I ask, How am I supposed to call an event through showInputDialog? is it possible? Who is gonna be the listener? Thanks in Advance
I found my own answer - its indeed to carry on the code the Event Search class and pull the trigger to one action like this, Instead it's better to do:
public SearchScreen(){
userQuery = (String) JOptionPane.showInputDialog("Type Keywords in english to be requested below:");
try {
//Your Action with the String
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "FAILURE");
}
}
I've created a localization table in my project's res-file using LWUIT Resource editor. But it turns out, that I don't know how to switch through different localizations. How can I set up a global language for my program?
This code can merge two diffrent localizations to one.(the default save in bundle and merge with new localization mergeL10N(these objects are hashTable))
if (themeName != null && !themeName.equals(this.currThemeName)) {
try {
if (themeName.equals(DEFAULT_THEME_NAME)) {
defaultTheme = Resources.open(DEFAULT_THEME_NAME);
bundle = null;
} else {
defaultTheme = Resources.open(DEFAULT_THEME_NAME);
bundle = Resources.open(themeName);
}
mergeL10N = defaultTheme.getL10N("Localization (L10N) 1", "iw");
if (bundle != null) {
mergeHashtable(mergeL10N, bundle.getL10N("Localization (L10N) 1", "iw"));
}
UIManager.getInstance().setResourceBundle(mergeL10N);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You must open your res and use the table that you want to use, here you can find an example
try {
Constants.res = Resources.open("/Lang.res");
} catch (Exception e){
System.err.println("can't load resource file:" + e);
}
Hashtable h = Constants.res.getL10N("English.res","en");
There are several components in Java that have predefined look and strings of text that are automatically printed on them. Examples is JFileChooser.
Also, there is a JDialog (or JOptionPane) that pops up when you try to do illegale rename in JFileChooser...
In what *.java file(s) can string keys that represent that keys and where do they get their values?
I'm talking about Nimbus L&F... I couldn't locate them in Nimbus nor Synth (which doesn't necessary mean they're not there)... I did found JFileChooser Strings in BasicFileChooser.
Bottom line:
I'm translating my program and I don't want any surprises, so I'd like to know which components have predefined strings and where to find them, that JDialog from above especially...
EDIT:
I have found BasicFileChooserUI, and this is one of the methods:
protected void installStrings(JFileChooser fc) {
Locale l = fc.getLocale();
newFolderErrorText = UIManager.getString("FileChooser.newFolderErrorText",l);
newFolderErrorSeparator = UIManager.getString("FileChooser.newFolderErrorSeparator",l);
newFolderParentDoesntExistTitleText = UIManager.getString("FileChooser.newFolderParentDoesntExistTitleText", l);
newFolderParentDoesntExistText = UIManager.getString("FileChooser.newFolderParentDoesntExistText", l);
fileDescriptionText = UIManager.getString("FileChooser.fileDescriptionText",l);
directoryDescriptionText = UIManager.getString("FileChooser.directoryDescriptionText",l);
saveButtonText = UIManager.getString("FileChooser.saveButtonText",l);
openButtonText = UIManager.getString("FileChooser.openButtonText",l);
saveDialogTitleText = UIManager.getString("FileChooser.saveDialogTitleText",l);
openDialogTitleText = UIManager.getString("FileChooser.openDialogTitleText",l);
cancelButtonText = UIManager.getString("FileChooser.cancelButtonText",l);
updateButtonText = UIManager.getString("FileChooser.updateButtonText",l);
helpButtonText = UIManager.getString("FileChooser.helpButtonText",l);
directoryOpenButtonText = UIManager.getString("FileChooser.directoryOpenButtonText",l);
saveButtonMnemonic = getMnemonic("FileChooser.saveButtonMnemonic", l);
openButtonMnemonic = getMnemonic("FileChooser.openButtonMnemonic", l);
cancelButtonMnemonic = getMnemonic("FileChooser.cancelButtonMnemonic", l);
updateButtonMnemonic = getMnemonic("FileChooser.updateButtonMnemonic", l);
helpButtonMnemonic = getMnemonic("FileChooser.helpButtonMnemonic", l);
directoryOpenButtonMnemonic = getMnemonic("FileChooser.directoryOpenButtonMnemonic", l);
saveButtonToolTipText = UIManager.getString("FileChooser.saveButtonToolTipText",l);
openButtonToolTipText = UIManager.getString("FileChooser.openButtonToolTipText",l);
cancelButtonToolTipText = UIManager.getString("FileChooser.cancelButtonToolTipText",l);
updateButtonToolTipText = UIManager.getString("FileChooser.updateButtonToolTipText",l);
helpButtonToolTipText = UIManager.getString("FileChooser.helpButtonToolTipText",l);
directoryOpenButtonToolTipText = UIManager.getString("FileChooser.directoryOpenButtonToolTipText",l);
}
I want to know from where is the getString("FileChooser.updateButtonText",l) method pulling out strings... I tried looking for it, but I had no luck...
Also, I know there are some strings in JFileChooser that are not defined in BasicFileChooserUI.java...
which one you want to change, but I don't know answer now
DYM???
look in:
file name:
files of type:
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
class ChooserFilterTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
String[] properties = {"os.name", "java.version", "java.vm.version", "java.vendor"};
for (String property : properties) {
System.out.println(property + ": " + System.getProperty(property));
}
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
jfc.addChoosableFileFilter(new FileFilter() {
#Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".obj");
}
#Override
public String getDescription() {
return "Wavefront OBJ (*.obj)";
}
#Override
public String toString() {
return getDescription();
}
});
int result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
System.out.println("Displayed description (Metal): " + (result == JOptionPane.YES_OPTION));
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(jfc);
} catch (Exception e) {
e.printStackTrace();
}
jfc.showOpenDialog(null);
result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
System.out.println("Displayed description (System): " + (result == JOptionPane.YES_OPTION));
result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
System.out.println("Displayed description (Metal): " + (result == JOptionPane.YES_OPTION));
try {
for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
SwingUtilities.updateComponentTreeUI(jfc);
break;
}
}
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
}
jfc.showOpenDialog(null);
result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
System.out.println("Displayed description (System): " + (result == JOptionPane.YES_OPTION));
}
};
SwingUtilities.invokeLater(r);
}
private ChooserFilterTest() {
}
}
Do you want this one
from code
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;
public class CrazyFileChooser {
public static void main(String[] args) {
try {
for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CrazyFileChooser().makeUI();
}
});
}
public void makeUI() {
JFileChooser chooser = new JFileChooser();
for (AbstractButton button : SwingUtils.getDescendantsOfType(AbstractButton.class, chooser)) {
button.setUI(new XORButtonUI());
button.setForeground(Color.GREEN);
}
for (JList list : SwingUtils.getDescendantsOfType(JList.class, chooser)) {
list.setBackground(Color.PINK);
}
JTextField jTextField = SwingUtils.getDescendantOfType(JTextField.class, chooser, "Text", "");
jTextField.setEditable(false);
for (JLabel label : SwingUtils.getDescendantsOfType(JLabel.class, chooser)) {
label.setFont(new Font("Dialog", Font.ITALIC, 18));
label.setForeground(Color.RED);
}
chooser.showOpenDialog(null);
}
}
class XORButtonUI extends MetalButtonUI {
#Override
public void paint(Graphics g, JComponent c) {
g.setXORMode(Color.YELLOW);
super.paint(g, c);
}
}
based on code Swing Utils, by Darryl Burke, one of top Swing gurus (once told us, to pay me for the programming, is how to pay a small child for licking ice cream)
Many such user interface elements are already localized for supported languages, as shown in JDK 6 and JRE 6 Supported Locales: User Interface Translation.
Addenda: See also Internationalization: Understanding Locale in the Java Platform. The manner in which UIManager.getLookAndFeelDefaults() obtains the L&F defaults is not specified; changing the source data is not supported. The (non-localized) names of the properties found in the returned Map may be used to override the defaults. As discussed in How to Write a Custom Look and Feel, the source text is stored in a properties file for each L&F and each supported locale. QuaQua is an example. On my platform, for example, the English strings for com.apple.laf.AquaLookAndFeel are in
$JAVA_HOME/Resources/English.lproj/aqua.properties
which warns:
# When this file is read in, the strings are put into the
# defaults table. This is an implementation detail of the current
# workings of Swing. DO NOT DEPEND ON THIS. This may change in
# future versions of Swing as we improve localization support.
See also How can I add localization to JFileChooser for a locale that is not supported by default?
These keys are provided by Swing PLAF resource bundles, and you can find them in the JDK sources. See e.g.:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/swing/internal/plaf/basic/resources/basic.java
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/java/swing/plaf/windows/resources/windows.java
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/java/swing/plaf/gtk/resources/gtk.java
...
String values for languages other than English are provided by adjacent bundle files.
And you can add one more bundle to any of these families just by creating one more file for desired human language and placing it anywhere on your classpath. Bundles in .java and .properties format work equally well, though .java format may be slightly more Unicode-friendly...
It may be good to keep in mind though that direct adding of content to com.sun package may violate the Java license. So to be on the safe side, it may be wise to move your extra resources to a package of your own and register it with UIManager like this:
UIManager.getDefaults().addResourceBundle("mypackage.swing.plaf.basic.resources.basic");
And as for Nimbus, I did not find any special resources for it, so going with "basic" may do the job...
**** Please note that my question is regarding the answers in another thread. However, when I posted the question in that thread, it was deleted. So I'm reposting the question here (with a link to the exact post that I'm referring to). ****
I have a couple of questions that go along with this thread. If I have a Timer (updateTimer), which I want to cancel when the window is closing, can I put that in place of the System.out.println("Windows Closing"); statement? Or would I have to put it in the actual "View" class (I have three classes DesktopApplication.App, DesktopApplication.View, and DesktopApplication.AboutBox and the configure Window method is in the .App class).
Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?
What I want to do is the following: When my application starts (and the main window opens) I want to check for a configuration file. If it exists, then I want to get the username, password, tunnel ID, and IP Address from that file--and populate their respective text boxes in the main jPanel. If it doesn't exist, then I won't do anything with it.
On closing the application, I want two things to happen: 1) any UpdateTimers that are running will be cancelled (to effectively and cleanly close the application) and 2) write the username, password, tunnel ID and IP Address to the configuration file for the next run.
I've created the file in Netbeans, so the "exitMenu" is automatically generated, and there is no "close button" configured. So I need to use WindowClosing to accomplish this (or hack the "exitMenu" method in a text editor and hope it doesn't create issues with Netbeans).
I should also add that the username and password are actually MD5 hashes of the real username and password. So, while someone can possibly open the text file and read them, they'll only see something like this:
c28de38997efb893872d893982ac
3289ab83ce8f398289d938999cab
12345
192.168.2.2
Thanks, and have a great day:)
Patrick.
Edited to include information about the "Username and Password" that will be stored.
can I put that in place of the System.out.println("Windows Closing"); statement?
Yes, you can put arbitrary code in your listener
Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?
Yes
How I ended up accomplishing this is like this.
In my "TunnelbrokerUpdateView" class (the one that actually handles the main frame), I added the following code:
WindowListener wl = new WindowListener(){
public void windowOpened(WindowEvent e)
{
try
{
FileReader fr = new FileReader (new File("userinfo.txt"));
BufferedReader br = new BufferedReader (fr);
jTextField1.setText(br.readLine());
jPasswordField1.setText(br.readLine());
jTextField2.setText(br.readLine());
oldIPAddress = br.readLine();
br.close();
}
catch (FileNotFoundException ex) {
// Pop up a dialog box explaining that this information will be saved
// and propogated in the future.. "First time running this?"
int result = JOptionPane.showConfirmDialog((Component)
null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
}
catch (java.io.IOException ea)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
}
}
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
BufferedWriter userData;
//Handle saving the user information to a file "userinfo.txt"
try
{
userData = new BufferedWriter(new FileWriter("userinfo.txt"));
StringBuffer sb = new StringBuffer();
sb.append(jTextField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jPasswordField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jTextField2.getText());
sb.append(System.getProperty("line.separator"));
sb.append(oldIPAddress);
userData.write(sb.toString());
userData.close();
}
catch (java.io.IOException ex)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
};
super.getFrame().addWindowListener(wl);
}
I added this into the "public TunnelbrokerUpdateView(SingleFrameApplication app)" method. So, everything works as I wanted it to. I'm sure there are better ways of incorporating the user information, but this was quick and dirty. In the future, I do plan on encrypting the data (or making it into a format that isn't readable normally), since there's a password hash involved.
Hopefully this will help someone else in the future.
(for reference, here's the entire method (including the stuff that Netbeans automatically puts in)
public TunnelbrokerUpdateView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
// This will take care of Opening and Closing
WindowListener wl = new WindowListener(){
public void windowOpened(WindowEvent e)
{
try
{
FileReader fr = new FileReader (new File("userinfo.txt"));
BufferedReader br = new BufferedReader (fr);
jTextField1.setText(br.readLine());
jPasswordField1.setText(br.readLine());
jTextField2.setText(br.readLine());
oldIPAddress = br.readLine();
br.close();
}
catch (FileNotFoundException ex) {
// Pop up a dialog box explaining that this information will be saved
// and propogated in the future.. "First time running this?"
int result = JOptionPane.showConfirmDialog((Component)
null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
}
catch (java.io.IOException ea)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
}
}
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
BufferedWriter userData;
//Handle saving the user information to a file "userinfo.txt"
try
{
userData = new BufferedWriter(new FileWriter("userinfo.txt"));
StringBuffer sb = new StringBuffer();
sb.append(jTextField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jPasswordField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jTextField2.getText());
sb.append(System.getProperty("line.separator"));
sb.append(oldIPAddress);
userData.write(sb.toString());
userData.close();
}
catch (java.io.IOException ex)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
};
super.getFrame().addWindowListener(wl);
}
Have a great day:)
Patrick.