Custom created button on JOptionPane does not work? - java

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

Related

How to adapt the text to a label? [duplicate]

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
}

How can I set the backgorund color for a JFrame using a JComboBox from another JFrame?

Actually, I'm trying to do a "Setting" window for a game and I want to set the background color of another window. I have no idea what to do. Some ideas pls?
You can implement it in different places. One of the ways is constructor, for example:
public YourClassPanel() {
// to set Look&Feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.updateComponentTreeUI(this);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
ControlPanel.tgp = null;
}
});
this.setBounds(0, 0, 710, 580);
this.setTitle("Buffer Allocation Panel");
this.setPreferredSize(null);
this.setResizable(false);
this.setBackground(Color.yellow); //to set Background
this.setForeground(Color.magenta); // to set Foreground
this.setOpaque(a!=255); // to set Opaque
}
Set a different color for JPanel background from Properties.

displayMessage instead of showMessageDialog

I'm creating my first program in java (in Netbeans), it is basically a SystemTray Icon with a popup menu with different functions for every item. In the following Item I want to use "displayMessage" instead of "showMessageDialog" after that the image was saved. I've tried with trayIcon.displayMessage("Message", "message", TrayIcon.MessageType.INFO); but it doesn't work and I don't know why, do you have any idea?
item5.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e) {
BufferedImage image = null;
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(SupTray.class.getName()).log(Level.SEVERE, null, ex);
}
try {
image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (AWTException ex) {
Logger.getLogger(SupTray.class.getName()).log(Level.SEVERE, null, ex);
}
try {
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HH.mm.ss");
Calendar now = Calendar.getInstance();
ImageIO.write(image, "png", new File(System.getProperty("user.home")+"\\Desktop\\"+formatter.format(now.getTime())+".png"));
} catch (IOException ex) {
Logger.getLogger(SupTray.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "L'immagine รจ stata salvata nel desktop.", "Cattura schermata", JOptionPane.INFORMATION_MESSAGE);
}
});
Im not sure if it makes any difference in this case, but in general you should specify the component the dialog should be displayed on (null in JOptionPane.showMessageDialog).
I had some unnecessary issues not doing this some time ago.

Icons on JOptionPane

Sorry, this is really basic. My first experience with Java Swing using Eclipse. I'm trying to write a very simple JOptionPane. I want the question mark icon to appear, but all I am getting is the Java coffee cup icon. What am I doing wrong? Thanks!
Object[] options = {"Encrypt", "Decrypt"};
int n = JOptionPane.showOptionDialog(new JFrame(),
"What Do You Want to Do?",
"Crypto",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
Please have a look at How to Set the Look and Feel
Try with different themes
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
// Set Motif L&F on any platform
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
// Set cross-platform Java L&F (also called "Metal")
// UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
// Set System L&F
//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
Object[] options = { "Encrypt", "Decrypt" };
JOptionPane.showOptionDialog(new JFrame(), "What Do You Want to Do?", "Crypto",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a
// custom Icon
options, // the titles of buttons
options[0]); // default button title
}
});
With different themes:

Add object to panel on every click

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();
}

Categories

Resources