I'm using following code to display error message in my swing application
try {
...
} catch (Exception exp) {
JOptionPane.showMessageDialog(this, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
The width of the error dialog goes lengthy depending on the message. Is there any way to wrap the error message?
A JOptionPane will use a JLabel to display text by default. A label will format HTML. Set the maximum width in CSS.
JOptionPane.showMessageDialog(
this,
"<html><body><p style='width: 200px;'>"+exp.getMessage()+"</p></body></html>",
"Error",
JOptionPane.ERROR_MESSAGE);
More generally, see How to Use HTML in Swing Components, as well as this simple example of using HTML in JLabel.
Add your message to a text component that can wrap, such as JEditorPane, then specify the editor pane as the message to your JOptionPane. See How to Use Editor Panes and Text Panes and How to Make Dialogs for examples.
Addendum: As an alternative to wrapping, consider a line-oriented-approach in a scroll pane, as shown below.
f.add(new JButton(new AbstractAction("Oh noes!") {
#Override
public void actionPerformed(ActionEvent action) {
try {
throw new UnsupportedOperationException("Not supported yet.");
} catch (Exception e) {
StringBuilder sb = new StringBuilder("Error: ");
sb.append(e.getMessage());
sb.append("\n");
for (StackTraceElement ste : e.getStackTrace()) {
sb.append(ste.toString());
sb.append("\n");
}
JTextArea jta = new JTextArea(sb.toString());
JScrollPane jsp = new JScrollPane(jta){
#Override
public Dimension getPreferredSize() {
return new Dimension(480, 320);
}
};
JOptionPane.showMessageDialog(
null, jsp, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}));
catch (Exception e) {
e.printStackTrace();
StringBuilder sb = new StringBuilder(e.toString());
for (StackTraceElement ste : e.getStackTrace()) {
sb.append("\n\tat ");
sb.append(ste);
}
JTextArea jta = new JTextArea(sb.toString());
JScrollPane jsp = new JScrollPane(jta) {
#Override
public Dimension getPreferredSize() {
return new Dimension(750, 320);
}
};
JOptionPane.showMessageDialog(
null, jsp, "Error", JOptionPane.ERROR_MESSAGE);
break; /// to show just one time
}
Related
I've been working on this program for the last week or so and have had this particular block of code running smoothly up until a little while ago. I haven't changed it at all, and all of a sudden it started throwing an exception for every option picked once the button was pushed. I've tested it for each option by putting a "System.out.println(activityMultiplier);" statement in each block, and it prints the correct value, so the item listener seems to be working. And when I select "Choose an Activity Level" (the optin which is supposed to throw an exception) the exception is thrown properly: the JOptionPane goes away once I click okay, and the JComboBox is still there so I can make another selection. However, I get the JOptionPane error message for EVERY option now, I've included the noActivity() method at the bottom so you can see what I'm calling.
public void setActivity() //JComboBox
{
final JFrame activityWindow = new JFrame();
activityWindow.setTitle("Question No 6 of 6");
activityWindow.setLocationRelativeTo(null);
JPanel activityPanel = new JPanel();
activityPanel.setLayout(new BorderLayout(10, 10));
activityPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel activityLabel = new JLabel("Please select your activity level:");
final JComboBox activityList = new JComboBox(activityString);
activityList.setSelectedIndex(5);
activityList.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
activityLevel = (String) activityList.getSelectedItem();
}
});
JButton submitBtn = new JButton("Submit");
submitBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
if (activityLevel.equals("Choose an activity level"))
throw new Exception();
else if (activityLevel.equals("Sedentary (little or no exercise)"))
{
activityMultiplier = 1.2;
activityWindow.dispose();
setBMR();
}
else if (activityLevel.equals("Lightly active (light exercise/sports 1-3 days/week)"))
{
activityMultiplier = 1.375;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
else if (activityLevel.equals("Moderatetely active (moderate exercise/sports 3-5 days/week)"))
{
activityMultiplier = 1.55;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
else if (activityLevel.equals("Very active (hard exercise/sports 6-7 days a week"))
{
activityMultiplier = 1.725;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
else if (activityLevel.equals("Extra active (very hard exercise/sports & physical job or 2x/day training)"))
{ activityMultiplier = 1.9;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
}
catch(Exception e1)
{
noActivity();
}
}
});
private void noActivity()
{
JOptionPane.showMessageDialog(null, "Please select an activity level.", "No Selection Made", JOptionPane.ERROR_MESSAGE);
JOptionPane.getRootFrame().dispose();
}
why not simply change it to:
if (activityLevel.equals("Choose an activity level"))
noActivity();
the rest of the options are in else if blocks anyway
i don't think that is a proper use for an Exception
I added JLabel on JFrame and displayed frame on YES button click of JOptionPane, it displays frame but didn't display label text.
int yes = JOptionPane.showConfirmDialog(null,"Do you want to reactivate previous
schedule(s)","Reactivate Schedule",JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if(yes == JOptionPane.OK_OPTION) {
setVisible(false);
disp_wait.setVisible(true);
for(int i=0 ; i<options.taskList.size(); i++) {
dataList = Options.getInstance().getTaskList();
Task task=dataList.get(i);
boolean active = task.getActive();
if(active) {
task.setActive(true);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.getMessage();
}
}
}
}
All your code is performing some processing during an event handling. In Java this is a problem, the GUI only gets drawn once all the event handling is processed. Besides that, it would be great to see the code for your JFrame, it probably does not add the Label before calling pack()
This is my actionListener for a popup menu button i want to add this picture on the panel after every its clicked
mntmNewMenuItem.addActionListener(new ActionListener() {
//This method will be called whenever you click the button.
int i;
public void actionPerformed(ActionEvent e) {
try {
label.setIcon(new ImageIcon
(new URL("file:/C:/Users/Ashad/JunoWorkspace/FYP1/table.png")));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
panel.add(label);
//redraw panel after addition
panel.validate();
panel.repaint();
handleDrag(label);
}
});
you can only add a UI object once.
if you want just a single instance to be added, you need to remove that element 1st then add. (but it doesn't seem logical removing then adding).
instead you can create a Label() object inside actionperformed
public void actionPerformed(ActionEvent e) {
label = new Label();//Added
try {
label.setIcon(new ImageIcon
(new URL("file:/C:/Users/Ashad/JunoWorkspace/FYP1/table.png")));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
I have added my own JPanel and JButton to JOptionPane as below.
When I click on the "OK" Button nothing shows up. Is there any alternative to it? i want to just get user's Username and Password but with my button not default from JOptionpane.
Can any body see what is wrong with this code?
final WebTextField user = new WebTextField();
final WebPasswordField password = new WebPasswordField();
WebButton ok = new WebButton("OK");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Zip file exist, continuing with extraction of zip file");
}
});
}
});
WebButton cancel = new WebButton("Cancel");
WebPanel panel = new WebPanel(new GridLayout(2, 2));
panel.setOpaque(false);
panel.add(new WebLabel("User:"));
panel.add(user);
panel.add(new WebLabel("Password:"));
panel.add(password);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
UIManager.put("OptionPane.background", Color.WHITE);
UIManager.put("Panel.background", Color.WHITE);
int o =JOptionPane.showOptionDialog(bcfiDownloadPanel,
new Object[]{panel},
"Authorization Required",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new WebButton[]{new WebButton("OK"), new WebButton("Cancel")}, // this is the array
"default"
);
It's quite unusual JOptionPane though... I do hope that WebButton is something that extends JButton;
int o =JOptionPane.showOptionDialog(bcfiDownloadPanel,
new Object[]{panel},
"Authorization Required",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new WebButton[]{new WebButton("OK"), new WebButton("Cancel")}, // this is the array
"default"
... so, as for any JButton, you should add action listener to it to make it listent to click event etc;
modify your code in something like this way:
int o =JOptionPane.showOptionDialog(bcfiDownloadPanel,
new Object[]{panel},
"Authorization Required",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new WebButton[]{this.ok, this.cancel}, // this is the array
"default"
Report that helps
Good luck
I am making a network application that has a chat function. On the chat I have one JTextPane
for displaying messages and one more for input. Then I have some buttons that allow to add style on the input text(bold,italic,font size,colour). The text is formatted correctly on input pane , although when moved to the display pane(once the correct JButton is pressed) it only has the format of last character. How can I move the text while keeping its original format?For example if I write "Hello Worl d" on the input , display shows "Hello Worl d"
textPane is the input pane
Where set :
final SimpleAttributeSet set = new SimpleAttributeSet();
Code for making input text bold(same of adding other styles) :
bold.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
StyledDocument doc = textPane.getStyledDocument();
if (StyleConstants.isBold(set)) {
StyleConstants.setBold(set, false);
bold.setSelected(false);
} else {
StyleConstants.setBold(set, true);
bold.setSelected(true);
}
textPane.setCharacterAttributes(set, true);
}
});
code for moving text from the input pane to the display pane :
getInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String input = textPane.getText();
textPane.setText("");
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Use the example to merge both Documents
http://java-sl.com/tip_merge_documents.html