change font in JOptionPane.showInputDialog - java

I'm writing a program in java language and I want to make some changes in one part of my JOptionPane.showInputDialog. My dialog is this :
JOptionPane.showInputDialog("Total Amount Deposited:\t\t" +
totalAmount + "\n Enter Coin Value \n" + "(Enter 1 to stop)");
and I want to make the part that is saying (Enter 1 to stop) a little bit smaller than the other parts.
I'm beginner in java language (roughly 2 months :D) and don't have any other experience. so, please keep your answers simple. thanks in advance.

A JOptionPane will display the text in a JLabel, which supports basic HTML. So you will need to wrap your text string in HTML, then you can use different fonts, colors or whatever.
Simple example:
String text = "<html>Normal text <b>and bold text</b></html>";
JOptionPane.showInputDialog(text);

You can also use Font.pointSize() or Font.size() from java.awt.Font.

Create a String = "the text"
put in a label pa
use setFont();
Quick example :
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test extends JFrame {
public static void main(String[] args)
{
String a = "(enter 1 to stop)";
JLabel pa = new JLabel();
JFrame fr = new JFrame();
fr.setSize(200,200);
pa.setText(a);
pa.setFont(pa.getFont().deriveFont(11.0f)); //change the font size from here
fr.add(pa);
fr.setVisible(true);
}
}

For JDK 8.x, I find the following works to enlarge the font size of most portions of the built-in JOptionPane.showInputDialog, especially buttons, textboxes and comboboxes.
It is mostly generic, except for the two parts I want to be bold font.
It even allows for exceptions (think of it as an "all except" strategy) when you want to enlarge 99% of the pieces of an input dialog, except for one or two pieces.
Sorry for the bad formatting, but the "Code Sample" tool messed up everything and I don't have time to fix it.
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.swing.*;
/**
* Changes the font size used in JOptionPane.showInputDialogs to make them more
* ADA section 508 compliant by making the text size larger, which is very nice
* for older people and anyone else with vision problems.
*
* #param fontSize
* - size of the font in pixels
*/
private static void makeDialogsEasierToSee(int fontSize)
{
// This next one is very strange; but, without it,
// any subsequent attempt to set InternalFrame.titleFont will
// be ignored, so resist the temptation to remove it.
JDialog.setDefaultLookAndFeelDecorated(true);
// define normal and bold fonts that we will use to override the defaults
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
Font boldFont = normalFont.deriveFont(Font.BOLD);
// get a list of objects that we can try to adjust font size and style for
List<Map.Entry<Object, Object>> entries = new ArrayList<>(UIManager.getLookAndFeelDefaults().entrySet());
// System.out.println(entries.size());
// remove anything that does NOT involve font selection
entries.removeIf(filter -> filter.getKey().toString().indexOf(".font") == -1);
// System.out.println(entries.size());
// Define a list of font sections of the screen that we do NOT want to
// enlarge/bold.
// The following is specific to jKarel so we do not obscure the display of
// "beeper piles" on the maps.
List<String> exempt = Arrays.asList("Panel.font");
// remove anything on the exempt list
entries.removeIf(filter -> exempt.contains(filter.getKey().toString()));
// System.out.println(entries.size());
// optional: sort the final list
Collections.sort(entries, Comparator.comparing(e -> Objects.toString(e.getKey())));
// apply normal font to all font objects that survived the filters
for (Map.Entry<Object, Object> entry : entries)
{
String key = entry.getKey().toString();
// System.out.println(key);
UIManager.put(key, normalFont);
}
UIManager.put("Label.font", boldFont);
UIManager.put("InternalFrame.titleFont", boldFont);
}

You basically have two straightforward options - Switch to JDialog or use HTML.
JOptionPane is intended for simple messages or interaction with the users. JDialog is a better choice if you want to break out of the canned use cases, and as you get more complex you will probably eventually have to switch to it.
To meet your immediate use case, you can send in an html message. The rules are:
You must begin and end with <html></html> tags. Put them in the middle and nothing happens.
You must remove all "\n"'s in your code. They don't work in html
anyway and the JPanel tries to use each line, as defined by \n's as a
separate html doc. Switch to
int totalAmount = 345; //for testing
String message = "<html>"
+ "Total Amount Deposited: " + totalAmount
+ "<br> Enter Coin Value "
+ "<br><span style='font-size:10'>(Enter 1 to stop)</span>"
+ "</html>";
JOptionPane.showInputDialog(message);

Related

GWT - Google visualization problems using layout panels?

I'm having troubles in my GWT app with a Google Visualization chart not showing up until after the user has some sort of interaction with the window (e.g. moves the mouse across the screen or presses a button). This would be fine except that the chart is suppose to show up as the first thing the user sees and since it's meant to be seen on a mobile device, it's likely they will not see the chart because their first interaction will be clicking a button that hides the chart to show other information.
Using the "Getting started tutorial" over at the Visualization code's page, the chart loads immediately fine (once some slight changes are made the fix the problems from the slightly out of date tutorial). After some trial and error to find where the difference between my code and the example code that was causing the problem, I found that it's happening because my code is using the newer layout panels instead of just regular panels in GWT.
The below code is the working tutorial code changed so that it uses a RootLayoutPanel.get() instead of a RootPanel.get(). With this, the chart doesn't load until you click to reload the page, then you can see the chart for an instant before the page reloads. This should be easily tested with the below code. To get the chart to show up for the entire time, simply change RootLayoutPanel.get() to RootPanel.get().
Something in my app is allowing the chart to load after user interaction (I'm not sure what). However, the layout panel is certainly the problem as if I change it to a regular panel it works fine. Unfortunately, my entire app is built using layout panels.
What's going on and how might I be able to make the chart show up from the start using layout panels? Thank you much!
package com.test.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.Selection;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.events.SelectHandler;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart;
import com.google.gwt.visualization.client.visualizations.corechart.Options;
public class SimpleViz implements EntryPoint {
public void onModuleLoad() {
// Create a callback to be called when the visualization API
// has been loaded.
Runnable onLoadCallback = new Runnable() {
public void run() {
LayoutPanel panel = RootLayoutPanel.get();
// Create a pie chart visualization.
PieChart pie = new PieChart(createTable(), createOptions());
pie.addSelectHandler(createSelectHandler(pie));
panel.add(pie);
}
};
// Load the visualization api, passing the onLoadCallback to be called
// when loading is done.
VisualizationUtils.loadVisualizationApi(onLoadCallback, PieChart.PACKAGE);
}
private Options createOptions() {
Options options = Options.create();
options.setWidth(400);
options.setHeight(240);
options.setTitle("My Daily Activities");
return options;
}
private SelectHandler createSelectHandler(final PieChart chart) {
return new SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
String message = "";
// May be multiple selections.
JsArray<Selection> selections = chart.getSelections();
for (int i = 0; i < selections.length(); i++) {
// add a new line for each selection
message += i == 0 ? "" : "\n";
Selection selection = selections.get(i);
if (selection.isCell()) {
// isCell() returns true if a cell has been selected.
// getRow() returns the row number of the selected cell.
int row = selection.getRow();
// getColumn() returns the column number of the selected cell.
int column = selection.getColumn();
message += "cell " + row + ":" + column + " selected";
} else if (selection.isRow()) {
// isRow() returns true if an entire row has been selected.
// getRow() returns the row number of the selected row.
int row = selection.getRow();
message += "row " + row + " selected";
} else {
// unreachable
message += "Pie chart selections should be either row selections or cell selections.";
message += " Other visualizations support column selections as well.";
}
}
Window.alert(message);
}
};
}
private AbstractDataTable createTable() {
DataTable data = DataTable.create();
data.addColumn(ColumnType.STRING, "Task");
data.addColumn(ColumnType.NUMBER, "Hours per Day");
data.addRows(2);
data.setValue(0, 0, "Work");
data.setValue(0, 1, 14);
data.setValue(1, 0, "Sleep");
data.setValue(1, 1, 10);
return data;
}
}
With the Layout panels the sizing of the widgets is done in JavaScript. When the initial page is loaded the initial sizing is done after everything else is finished. However in your case the pie is added when the library is loaded and that runs after the initial sizing. Therefor your widget isn't sized and won't show up. You need to call panel.forceLayout(); explicitly as the last method in you run method.
The google chart tools definately work with LayoutPanels. I am using it myself.
It's really difficult to say what's wrong but here are a couple of suggestions:
Check with Chrome Dev Tools (Console) if an exception is thrown.
Do you have standard mode enabled. That's important with LayoutPanels (make sure you have <!DOCTYPE html> in your HTML host page
You could try a 3rd party wrapper (supports automatic resizes)

How to prevent JComboBox drop-down list from exceeding vertical screen size

I use a JComboBox with many entries (hundreds). I want to limit the size of its drop-down list to the vertical size of the screen. Using a fixed size does not work out properly for different look&feels and screen resolutions.
I am using Java 6u25 on Windows 7.
If I set the maximum row count to a value (e.g. 100) that exceeds the number of list items (=rows) that fit on the screen (75), the drop-down list seems to be drawn in full size but the lowest entries are never visible.
Here is a screenshot for illustation (thanks for the SSCCE by #trashgod). The sceenshot was taken in a virtual machine on XP.
I also tested the code on another PC, so I think I can rule out some driver issues.
What I like to have is a drop-down list that fits on screen where I can scroll down completely to the very last value (and see that value). The other way round, I would like to see the scroll down button of the scrollbar.
Is the only possibility to render a cell of the list and use this in my calculations? Manipulation of height parameters of the combobox did not work.
Any ideas how to solve this?
What puzzles me is that I did not find any reference to that problem whatsoever. I assume that I am either missing something obvious here or that I am using the wrong keywords for my search. If any of the latter two, my apologies please give me a hint.
Thanks.
I find this description hard to believe. Can you back it up with an SSCCE?
Your skepticism is well founded; my description was based on a distant memory of a remote implementation. With the sscce below, I see a scroll bar and the truncation reported by #uhm; I can only select from among the last, half-dozen, hidden entries by using the keyboard. I get similar results on these platforms:
Mac OS X: [Aqua Look and Feel for Mac OS X - com.apple.laf.AquaLookAndFeel]
Ubuntu: [The Java(tm) Look and Feel - javax.swing.plaf.metal.MetalLookAndFeel]
Windows: [The Java(tm) Look and Feel - javax.swing.plaf.metal.MetalLookAndFeel]
import java.awt.EventQueue;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
/** #see http://stackoverflow.com/questions/8270256 */
public class TallCombo extends JPanel {
private static final int N = 128;
public TallCombo() {
final JComboBox combo = new JComboBox();
for (int i = 0; i < N; i++) {
combo.addItem("Item " + Integer.valueOf(i));
}
combo.setMaximumRowCount(N / 2);
this.add(combo);
}
private void display() {
JFrame f = new JFrame("TallCombo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
System.out.println(UIManager.getLookAndFeel());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TallCombo().display();
}
});
}
}
I found this example: http://www.javaprogrammingforums.com/awt-java-swing/11457-jcombobox-scroll-bars.html (at the bottom)

Highlighting Text in java

We are developing a plagiarism detection framework. In there i have to highlight the possible plagiarized phrases in the document. The document gets preprocessed with stop word removal, stemming and number removal first. So the highlighting gets difficult with the preprocessed token
As and example:
Orginal Text: "Extreme programming is one approach of agile software development which emphasizes on frequent releases in short development cycles which are called time boxes. This result in reducing the costs spend for changes, by having multiple short development cycles, rather than one long one. Extreme programming includes pair-wise programming (for code review, unit testing). Also it avoids implementing features which are not included in the current time box, so the schedule creep can be minimized. "
phrase want to highlight: Extreme programming includes pair-wise programming
preprocessed token : Extrem program pair-wise program
Is there anyway I can highlight the preprocessed token in the original document????
Thanx
You'd better use JTextPane or JEditorPane, instead of JTextArea.
A text area is a "plain" text component, which means taht although it can display text in any font, all of the text is in the same font.
So, JTextArea is not a convenient component to make any text formatting.
On the contrary, using JTextPane or JEditorPane, it's quite easy to change style (highlight) of any part of loaded text.
See How to Use Editor Panes and Text Panes for details.
Update:
The following code highlights the desired part of your text.
It's not exectly what you want. It simply finds the exact phrase in the text.
But I hope that if you apply your algorithms, you can easily
modify it to fit your needs.
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class LineHighlightPainter {
String revisedText = "Extreme programming is one approach "
+ "of agile software development which emphasizes on frequent"
+ " releases in short development cycles which are called "
+ "time boxes. This result in reducing the costs spend for "
+ "changes, by having multiple short development cycles, "
+ "rather than one long one. Extreme programming includes "
+ "pair-wise programming (for code review, unit testing). "
+ "Also it avoids implementing features which are not included "
+ "in the current time box, so the schedule creep can be minimized. ";
String token = "Extreme programming includes pair-wise programming";
public static void main(String args[]) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
new LineHighlightPainter().createAndShowGUI();
}
});
} catch (InterruptedException ex) {
// ignore
} catch (InvocationTargetException ex) {
// ignore
}
}
public void createAndShowGUI() {
JFrame frame = new JFrame("LineHighlightPainter demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea area = new JTextArea(9, 45);
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setText(revisedText);
// Highlighting part of the text in the instance of JTextArea
// based on token.
highlight(area, token);
frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern) {
// First remove all old highlights
removeHighlights(textComp);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp) {
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i = 0; i < hilites.length; i++) {
if (hilites[i].getPainter() instanceof MyHighlightPainter) {
hilite.removeHighlight(hilites[i]);
}
}
}
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
// A private subclass of the default highlight painter
class MyHighlightPainter
extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}
}
This example is based on Highlighting Words in a JTextComponent.
From a technical point of view: You can either choose or develop a markup language and add annotations or tags to the original document. Or you want to create a second file that records all potential plagiarisms.
With markup, your text could look like this:
[...] rather than one long one. <plag ref="1234">Extreme programming
includes pair-wise programming</plag> (for code review, unit testing). [...]
(with ref referencing to some metadata record that describes the original)
You could use java.text.AttributedString to annotate the preprocessed tokens in the original document.
Then apply TextAttributes to the relevant ones (which whould take effect in the original document.

Mouse shows color

i am trying to make an application which would show which color my mouse is pointing to, i dont mean in my own application but anywhere in windows on any screen, kind of like a tag beside my mouse pointer which shows the exact color.
I am a Java developer but i dont think this could be done in java i am thinking maybe i need some sort of script but i have no idea any help would be really appriciated
The solution consists of two parts:
Part 1: Retrieving the color:
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
Color color = new Robot().getPixelColor(mouseLocation.x, mouseLocation.y);
Part 2: Getting the color name:
You can get a list of many colors and their names from Wikipedia's List of colors. You can create a mapping in Java given the data on Wikipedia.
Perhaps you can start with a few colors, and provide a generic hex representation for unknown colors, for example #rrggbb.
Here is the runnable example,
import java.awt.AWTException;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
public class Main {
public static String getHexString(int rgb) {
String hexString = Integer.toHexString(rgb);
hexString = hexString.length() > 1 ? hexString : "0" + hexString;
return hexString;
}
public static void main(String[] a) throws AWTException {
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
Color color = new Robot().getPixelColor(mouseLocation.x,
mouseLocation.y);
System.out.println(getHexString(color.getRed())
+ getHexString(color.getGreen())
+ getHexString(color.getBlue()));
}
}
Take your pick: http://rosettacode.org/wiki/Color_of_a_screen_pixel
There is a Java/AWT example, an AutoHotKey is a simple scripted option.
The second C example shows the 3 API calls you need GetDC/GetCursorPos/GetPixel and their support code, these can be used from most languages that compile for windows.

JOptionsPane displays Components in the 'options' argument as Component.toString()

I'm trying to pop up a dialog to allow the user to select one of two colors as a background color. To make it look especially spiffy, I'd like to two choices to be displayed in the color in question, i.e.:
import java.awt.Color;
import java.awt.Label;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class JOptionPaneTest extends JFrame{
public static void main(String[] args) {
new JOptionPaneTest();
}
public JOptionPaneTest() {
Object[] possibilities = new Object[2];
JButton black = new JButton("Black");
JButton white = new JButton("White");
black.setBackground(Color.black);
white.setBackground(Color.white);
black.setForeground(Color.white);
white.setForeground(Color.black);
possibilities[0] = black;
possibilities[1] = white;
JButton l = (JButton)JOptionPane.showInputDialog(this,
"Please specify the background color", "Background check",
JOptionPane.QUESTION_MESSAGE, null, possibilities,
possibilities[0]);
System.out.println("" + l);
}
}
However, this doesn't work - it displays the JButton.toString() return values in a drop down instead of the JButton. I also tried JLabel and Label for the heck of it. According to the API, the JButtons should be added to the dialog as is since they're Components. If I add the JButton to the 'message' parameter it does display as expected.
Any idea what I'm doing wrong?
The Java API is slighly unclear about this point. At the top describes how to interpret the options, but options are the YES, NO, CANCEL... possibilities the user can choose, painted in the buttons row. You are talking about the selectionValues, and then the API (go to last method named showInputDialog) is clear:
selectionValues - an array of Objects that gives the possible selections
It is up to the UI to decide how best to represent the selectionValues, but usually a JComboBox, JList, or JTextField will be used.
From my experience, the objects passed in the selectionValues are displayed using toString()and the result is shown in a JComboBox or a JList, so you can not show selection values with custom painting; you need to implement you own dialog for that.
You can pass the message as a Component so you can provide a legend to the user about the selectionValues, where you can show labels with background colors to indicate each color available and thus provide assitance selecting a value from selectionValues.
Should be array of strings not array of jbutton (possibilites) in showInputDialog, but in this way you won't have background color. I don't think it exists any way to implement such colors chooser in showInputDialog()
String[] str = {"aaa", "bbb"};
JButton l = (JButton)JOptionPane.showInputDialog(this,
"Please specify the background color", "Background check",
JOptionPane.QUESTION_MESSAGE, null, str, str[0]);

Categories