Configure width, wrap & font of pop-up - java

I'm Java beginner. I'm using the below code to show a pop-up whenever required in my application.
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType)
{
JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
optionType);
//pane.setFont(new java.awt.Font("SansSerif", 0, 12));//Not working to change the font of pop-up text and button texts
final JDialog dialog = pane.createDialog(parentComponent, title);
dialog.setVisible(false) ;
//dialog.setFont(new java.awt.Font("SansSerif", 0, 12)); //Not working to change the font of pop-up text and button texts
dialog.setLocationRelativeTo(parentComponent);
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true) ;
dialog.dispose();
Object o = pane.getValue();
if (o instanceof Integer) {
return (Integer)o;
}
return JOptionPane.CLOSED_OPTION;
}
The pop up is being shown properly, but have following problems:
How to change the font to the pop up text/message and text of button (yes/no)?
How to restrict the pop up width to its parents width?
How to wrap the pop up text (like wrapping the text in text area)?
Update: (Answer for 1)
Get the components from JOptionPane and set the fonts as below:
private static final String key = "OptionPane.messageFont";
//Question: QUESTION_MESSAGE
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType){
UIManager.put(key, new java.awt.Font("SansSerif", 0, 12));
JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
optionType);
JPanel buttonPanel = (JPanel)pane.getComponent(1);
Object buttonOk[] = buttonPanel.getComponents();
for (int i = 0; i < buttonOk.length; i++) {
JButton button = (JButton)buttonOk[i];
button.setFont(new java.awt.Font("SansSerif", 0, 12));
button.validate();
}
pane.setFont(new java.awt.Font("SansSerif", 0, 12));
final JDialog dialog = pane.createDialog(parentComponent, title);
dialog.setVisible(false) ;
dialog.setFont(new java.awt.Font("SansSerif", 0, 12));
dialog.setLocationRelativeTo(parentComponent);
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true) ;
dialog.dispose();
Object o = pane.getValue();
if (o instanceof Integer) {
return (Integer)o;
}
return JOptionPane.CLOSED_OPTION;
}
Update 2 (Answer for 3rd question):
Use the below function which automatically wraps the text. This function inturn calls showConfirmDialog(parentComponent, message, title, optionType); The code for showConfirmDialog(...) is already given in the question.
/**
* Question/Confirmation Message Dialog Multiline.
* It DONOT require linebreak ("\n") for multiline messages. It will automatically wrap the text to new lines.
* Note: last when used was not properly working. Please verify it.
*/
public static int showConfirmDialogMultiLine(Component parentComponent,
Object message, String title, int optionType){
JTextArea textArea = new JTextArea((String)message);
textArea.setColumns(50);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setSize(textArea.getPreferredSize().width, 1);
textArea.setBackground(parentComponent.getBackground());
textArea.setFont(Usability.getFont("DialogBoxes.DialogTextFont")); //$NON-NLS-1$
textArea.setEditable(false);
message = textArea;
int retVal = showConfirmDialog(parentComponent,
message,
title,
optionType);
return retVal;
}
Do anybody know answers for 2nd question?

You can use the UIManager to change the OptionPane.messageFont, as suggested below.
private static final String key = "OptionPane.messageFont";
...
private int showConfirmDialog(...) {
UIManager.put(key, UIManager.getFont(key).deriveFont(Font.ITALIC, 20));
JOptionPane pane = new JOptionPane(...);
...
}
Addendum: Where do I get different keys?
UIManager Defaults is an excellent resource for this, as it can examine the default properties of installed Look & Feel implementations.

Related

How to set the style of inputted text to that which immediately follows the cursor position in a JTextPane

I'm working on a database program where the GUI has multiple input areas, some of which are JTextPanes where the user can set Bold, Underline, and Italic styles on their text. When the user places their cursor immediately adjacent to an area that is already bold, for example, I want the next text that they type to likewise be bold. So far, the only thing that is happening is that text typed immediately after bolded text is bold, but I cannot seem to make it so that text typed in immediately before bolded text is likewise bold.
I'm not sure that all was any less than confusing, so here's an example:
Presume the sentence, "Java is fun." is already in one of the JTextPanes.
If the user places the cursor to the left or right of "is", I want whatever they type next to likewise be bold. Like this, "Java fooisbar fun."
So far, I am only getting, "Java fooisbar fun."
What follows is the method I am using to add style-detecting functionality to the caret of a JTextPane and what I thought would work to do this.
I've also tried adding an additional new StyledEditorKit.BoldAction().actionPerformed(null) before or after the boldButton.setSelected(true) but that didn't have any effect. I also attempted tp.getStyledDocument().setCharacterAttributes(caretPosition -1, 1, asPrev, true), and while that did make the next text inputted bold, the results were unpredictable, with random line breaks and missing characters happening. Changing boldButton.setSelected(true) to boldButton.doClick() didn't have any effect, nor did using my ButtonAction class to set the text to bold.
int lastCaretPosition;
public void formatAndAddFunctions(Component c) {
Font normalFont = new Font("Tahoma", Font.PLAIN, 11);
c.setFont(normalFont);
if (c instanceof JTextField) {
((JTextField) c).setAlignmentX(Component.LEFT_ALIGNMENT);
((JTextField) c).addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent evt) {
((JTextField) c).selectAll();
activeComponent = c;
}
});
UndoTool.addUndoFunctionality((JTextField) c);
}
if (c instanceof JScrollPane) {
((JScrollPane) c).setAlignmentX(Component.LEFT_ALIGNMENT);
JViewport vp = ((JScrollPane) c).getViewport();
JTextPane tp = (JTextPane) vp.getView();
tp.setContentType("text/html");
tp.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);
tp.addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent evt) {
activeComponent = tp;
}
});
UndoTool.addUndoFunctionality(tp);
//look at the character attibutes before and after the caret to see if they are
//formatted bold, underline, and/or italic
lastCaretPosition = -1;
tp.addCaretListener((CaretEvent ce) -> {
int caretPosition = tp.getCaretPosition();
if(caretPosition != lastCaretPosition) {
lastCaretPosition = caretPosition;
Element charElementPrev = tp.getStyledDocument().getCharacterElement(caretPosition - 1);
AttributeSet asPrev = charElementPrev.getAttributes();
Element charElementAfter = tp.getStyledDocument().getCharacterElement(caretPosition);
AttributeSet asAfter = charElementAfter.getAttributes();
if ((StyleConstants.isBold(asPrev) || StyleConstants.isBold(asAfter)) && !boldButton.isSelected()) {
boldButton.setSelected(true);
} else if((!StyleConstants.isBold(asPrev) && !StyleConstants.isBold(asAfter)) && boldButton.isSelected()) {
boldButton.setSelected(false);
}
if ((StyleConstants.isUnderline(asPrev) || StyleConstants.isUnderline(asAfter)) && !ulButton.isSelected()) {
ulButton.setSelected(true);
} else if ((!StyleConstants.isUnderline(asPrev) && !StyleConstants.isUnderline(asAfter)) && ulButton.isSelected()) {
ulButton.setSelected(false);
}
if ((StyleConstants.isItalic(asPrev) || StyleConstants.isItalic(asAfter)) && !itButton.isSelected()) {
itButton.setSelected(true);
} else if ((!StyleConstants.isItalic(asPrev) && !StyleConstants.isItalic(asAfter)) && itButton.isSelected()) {
itButton.setSelected(false);
}
}
});
tp.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_DOWN_MASK), "boldKeystroke");
tp.getActionMap().put("boldKeystroke", new ButtonAction("bold"));
tp.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_DOWN_MASK), "underlineKeystroke");
tp.getActionMap().put("underlineKeystroke", new ButtonAction("underline"));
tp.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_DOWN_MASK), "italicKeystroke");
tp.getActionMap().put("italicKeystroke", new ButtonAction("italic"));
}
}
And, for reference, the boldButton's code:
boldButton = new JToggleButton();
boldButton.setIcon(allIcons[39]);
boldButton.setRolloverIcon(allIcons[40]);
boldButton.setSelectedIcon(allIcons[41]);
boldButton.setToolTipText("Bold");
boldButton.setBorderPainted(false);
boldButton.setContentAreaFilled(false);
boldButton.setFocusable(false);
boldButton.setBorder(null);
boldButton.setMargin(noInset);
boldButton.addActionListener((java.awt.event.ActionEvent e) -> {
new StyledEditorKit.BoldAction().actionPerformed(e);
activeComponent.requestFocusInWindow();
});
The odd thing is that if I set the cursor right before bolded text, and then click on the Bold toggle button in the UI, the next text typed does come out bold. But I can't seem to get this to happen programmatically. Any ideas?

how to combine joptionpane with combobox

i want my joptionpane can combine with combobox,and the combobox data is in database, how i managed that.
i've tried change but the red code always show
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String wel = sdf.format(cal1.getDate());
String NamaFile = "/report/harianMasuk.jasper";
HashMap hash = new HashMap();
String tak = JOptionPane.showOptionDialog(null,id.getSelectedIndex()-1,"Laporan Supplier",JOptionPane.QUESTION_MESSAGE);
try {
hash.put("til", wel);
hash.put("rul", tak);
runReportDefault(NamaFile, hash);
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
Read the section from the Swing tutorial on Getting User Input From a Dialog.
It demonstrates how to display a combo box in a JOptionPane.
Not exactly sure what you are trying to accomplish but it appears to be that you want to utilize a JComboBox within a JOptionPane dialog window. This ComboBox would be filled with specific data from your database. The User is to select from this ComboBox and your application continues processing based on that selection. If this is the case then you might want to try something like this:
String selectedItem = "";
int selectedItemIndex = -1;
/* Ensure dialog never hides behind anything (use if
the keyword 'this' can not be used or there is no
object to reference as parent for the dialog). */
JFrame iframe = new JFrame();
iframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iframe.setAlwaysOnTop(true);
// ---------------------------------------------------
int btns = JOptionPane.OK_CANCEL_OPTION;
String dialogMessage = "<html>Select the desired item from the Drop-Down "
+ "list<br>you want to work with:<br><br></html>";
String dialogTitle = "Your Fav Items";
/* Up to you to gather what you want placed into the
JComboBox that will be displayed within the JOptionPane. */
String[] comboBoxItems = {"Your", "DB", "Items", "You", "Want", "To",
"Add", "To", "ComboBox"};
BorderLayout layout = new BorderLayout();
JPanel topPanel = new JPanel(layout);
JLabel label = new JLabel(dialogMessage);
topPanel.add(label, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
JComboBox cb = new JComboBox();
cb.setModel(new DefaultComboBoxModel<>(comboBoxItems));
cb.setSelectedIndex(-1);
centerPanel.add(cb, BorderLayout.CENTER);
topPanel.add(centerPanel);
// Ensure a selection or Cancel (or dialog close)
while (selectedItemIndex < 0) {
int res = JOptionPane.showConfirmDialog(iframe, topPanel, dialogTitle, btns);
if (res == 2) {
selectedItem = "Selection Option Was Canceled!";
break;
}
selectedItemIndex = cb.getSelectedIndex();
if (res == JOptionPane.OK_OPTION) {
if (selectedItemIndex == -1) {
JOptionPane.showMessageDialog(iframe, "<html>You <b>must</b> "
+ "select something or select <font color=red><b>Cancel</b></font>.",
"Invalid Selection...", JOptionPane.WARNING_MESSAGE);
}
else {
selectedItem = cb.getSelectedItem().toString();
}
}
iframe.dispose();
}
JOptionPane.showMessageDialog(iframe, "<html>You selected the ComboBox item:"
+ "<br><br><b><font color=blue><center>" + selectedItem + "</center>"
+ "</font></b><br></html>", "Selected Item", JOptionPane.INFORMATION_MESSAGE);
iframe.dispose();
With the above code, the Input dialog that will be displayed would look something like this:
It is up to you to find the means to fill the comboBoxItems String Array used within the code above.

get values of Jtextfields when click OK in Dialog

My need is to display a tab in a JDialog (confirmDialog or inputDialog). The tab contains 2 JTextField per row. The display works fine :
but I don't know how to get the values of the JTextFields.
Here is the display code :
int size = model.getCheckedApplications().size();
// une ligne par application sélectionnée
layout = new GridLayout(size + 1, 3, 5, 5);
myPanel = new JPanel(layout);
myPanel.add(new JLabel("Application"));
myPanel.add(new JLabel("Version cadre"));
myPanel.add(new JLabel("Nouvelles natures"));
for (Application app : model.getCheckedApplications()) {
myPanel.add(new JLabel(app.getCode88()));
JTextField versionActuelleField = new JTextField(30);
versionActuelleField.setName("versionActuelle"
+ app.getCode88());
versionActuelleField.setText(app
.getVersionCadreActuelle());
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
myPanel.add(versionActuelleField);
myPanel.add(nouvellesNaturesField);
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then I don't know how to get the values when the user clicks on the OK Button :
if (result == 0) { // The user clicks on the ok button
You need to add them to some list that you store, so you can get at them again. Since you are adding them in reference to an application, I would suggest a Map
private Map<Application, JTextField> nouvellesNaturesFields = new ArrayListMultimap<Application, JTextField>(); //Or Hashmap, if the key is unique
private Map<Application, JTextField> versionActuelleFields = new ArrayListMultiMap<Application, JTextField>();
public List<JTextField> getNouvellesNaturesFields() {
return nouvellesNaturesFields ;
}
public List<JTextField> getVersionActuelleFields () {
return versionActuelleFields ;
}
//class code
for (Application app : model.getCheckedApplications()) {
//Other code
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
nouvellesNaturesFields.put(app, nouvellesNaturesField);
//Other code and same for your new nature fields
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then when the user clicks the confirm button, using the property accessor getNouvellesNaturesFields()or getVersionActuelleFields() you can iterate all the fields created, like so:
for (Map.Entry<Application, JTextField> entry: myMap.entries()) {
//Do something here
}
Or you could also get them via:
for (Application app : model.getCheckedApplications()) {
List<JTextField> data = myMap.get(app);
for(JTextField field : data) {
field.getText();
}
}
Since the key value probably won't be unique, I used an ArrayListMultiMap, but if it would be unique, then a HashMap should suffice
You assign the Jtextfield value to a string using the getText() method e.g below
String texfield = JTextField.getText();
Subsequently you use the String textfield wherever you want. And to get the right jtextfield you have to get text from the textfield you want for example you have four Jtexfield. Assuming they are JTextField1, JTextField2, JTextField3 and JTextField4. To get the value of JTextField3 you have
String texfield = JTextField3.getText();
The values should be in the JTextFields you created:
versionActuelleField
nouvellesNaturesField
Also, you might want to look at ParamDialog, which I implemented to be a generic solution to this question.
EDIT
Yes I see now that you are creating these JTextFields in a loop. So you need to create a Collection, I'd suggest a Map<String, JTextField> where you could map all of your application names to the matching JTextField, as well as iterate over the collection to get all application names / JTextFields.

Writing actionListner to display form input on console upon confirmation

I am currently constructing a GUI which allows me to add new cruises to the system. I want to write an actionListner which once the user clicks on "ok" then the form input will be displayed as output on the console.
I currently have the following draft to complete this task:
ok = new JButton("Add Cruise");
ok.setToolTipText("To add the Cruise to the system");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
int selected = typeList2.getSelectedIndex();
String tText = typeList2[selected];
Boolean addtheCruise = false;
addtheCruise = fleet.addCruise();
fleet.printCruise();
if (addtheCruise)
{
frame.setVisible(false);
}
else
{ // Report error, and allow form to be re-used
JOptionPane.showMessageDialog(frame,
"That Cruise already exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
buttonPanel.add(ok);
Here is the rest of the code to the Form input frame:
contentPane2 = new JPanel (new GridLayout(18, 1)); //row, col
nameInput = new JLabel ("Input Cruise Name:");
nameInput.setForeground(normalText);
contentPane2.add(nameInput);
Frame2.add(contentPane2);
Cruisename = new JTextField("",10);
contentPane2.add(Cruisename);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
confirmPanel = new JPanel ();
confirmPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
confirmPanel.setBorder(BorderFactory.createLineBorder(Color.PINK));
addItinerary = new JButton("Add Itinerary");
confirmPanel.add(Add);
confirmPanel.add(addItinerary );
Frame2.add(confirmPanel, BorderLayout.PAGE_END);
Frame2.setVisible(true);
contentPane2.add(Cruisename);
Frame2.add(contentPane2);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
contentPane2.setBorder(BorderFactory.createLineBorder(Color.black));
//Label for start and end location jcombobox
CruiseMessage = new JLabel ("Enter Start and End Location of new Cruise:");
CruiseMessage.setForeground(normalText);
contentPane2.add(CruiseMessage);
Frame2.add(contentPane2);
/**
* creating start location JComboBox
*/
startL = new JComboBox();
final JComboBox typeList2;
final String[] typeStrings2 = {
"Select Start Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
startL = new JComboBox(typeStrings2);
contentPane2.add(startL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
/**
* creating end location JComboBox
*/
endL = new JComboBox();
final JComboBox typeList3;
final String[] typeStrings3 = {
"Select End Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
endL = new JComboBox(typeStrings3);
contentPane2.add(endL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
//Label for select ship jcombobox
selectShipM = new JLabel ("Select Ship to assign Cruise:");
selectShipM.setForeground(normalText);
contentPane2.add(selectShipM);
Frame2.add(contentPane2);
/**
* creating select ship JCombobox
* select ship to assign cruise
*/
selectShip = new JComboBox();
final JComboBox typeList4;
final String[] typeStrings4 = {
"Select Ship", "Dalton Princess", "Stafford Princess" };
selectShip = new JComboBox(typeStrings4);
contentPane2.add(selectShip);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
I need all form inputs from the code above to be displayed on the console upon completion.
Summary:
1. I have two ships in one fleet
2. To add new cruise, all fields (Name, start date, end date, ship) must be selected.
The Problem:
1. I keep coming up with errors when creating " fleet = new Fleet();" in my constructor. Even though I have declared it in my class.
2. In the draft code below, line 5 states "typeList2", however, I have two JComboBox's - two different type Strings for both drop down menu's (Shown in the rest of the code). How do I input both typeLists to the output rather than just one?
Thank you.

how to change the default text of buttons in JOptionPane.showInputDialog

I want to set the text of OK and CANCEL buttons in JOptionPane.showInputDialog
to my own strings.
There is a way to change the buttons' text in JOptionPane.showOptionDialog, but I couldn't find a way to change it in showInputDialog.
if you don't want it for just a single inputDialog, add these lines prior to creating dialog
UIManager.put("OptionPane.cancelButtonText", "nope");
UIManager.put("OptionPane.okButtonText", "yup");
where 'yup' and 'nope' is the text you want displayed
The code below should make a dialog appear and you can specify the button text in the Object[].
Object[] choices = {"One", "Two"};
Object defaultChoice = choices[0];
JOptionPane.showOptionDialog(this,
"Select one of the values",
"Title message",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
choices,
defaultChoice);
Also, make sure to look through the Java tutorials on the Oracle site. I found the solution at this link in the tutorials http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#create
If you want the JOptionPane.showInputDialog with custom button texts, you could extend JOptionPane:
public class JEnhancedOptionPane extends JOptionPane {
public static String showInputDialog(final Object message, final Object[] options)
throws HeadlessException {
final JOptionPane pane = new JOptionPane(message, QUESTION_MESSAGE,
OK_CANCEL_OPTION, null,
options, null);
pane.setWantsInput(true);
pane.setComponentOrientation((getRootFrame()).getComponentOrientation());
pane.setMessageType(QUESTION_MESSAGE);
pane.selectInitialValue();
final String title = UIManager.getString("OptionPane.inputDialogTitle", null);
final JDialog dialog = pane.createDialog(null, title);
dialog.setVisible(true);
dialog.dispose();
final Object value = pane.getInputValue();
return (value == UNINITIALIZED_VALUE) ? null : (String) value;
}
}
You could call it like this:
JEnhancedOptionPane.showInputDialog("Number:", new Object[]{"Yes", "No"});
Please see How to Make Dialogs: Customizing Button Text.

Categories

Resources