I have jbutton1 which has a text "Connect" when the user clicks the jbutton1 the application runs and the text of jbutton1 changes from "Connect" to "Disconnect". Now again when the user clicks jbutton1 and the text is "Disconnect" so the application should close.
The code i have given here does not checks anything it automatically closes the application which i don't want. I want to check the text of the button if it is connect i should do a different process and if it is disconnect it shouls close my application when the button is clicked.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jComboBox2.getSelectedItem()==null)
{
System.out.println("Select one name");
}
else
{
try {
Runtime r = Runtime.getRuntime();
p = Runtime.getRuntime().exec("C:\\Program Files");
AS a4sObj = new AS(new String[]{jComboBox2.getSelectedItem().toString()});
} catch (IOException ex) {
Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
Just move setText to the end:
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
This is wrong
if(jButton1.getText()== "Disconnect") , take a look at this great answer to check the reason and learn how to compare Strings in java
You should do:
if("Disconnect".equalsIgnoreCase(jButton1.getText()))
instead
Related
I've been working on a background java program for a while and its almost ready to be released so I thought I should probably add a way to exit the program. I have this function:
private static void setupSysTray() {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
try {
final PopupMenu popupMenu = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(ImageIO.read(new File(workingDirectory +
fileSeparator + "tray.png")), "Multi");
final SystemTray tray = SystemTray.getSystemTray();
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(e -> {
System.out.println("Something happened!");
System.exit(0);
});
popupMenu.add(exitItem);
trayIcon.setPopupMenu(popupMenu);
tray.add(trayIcon);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
}
I presumed this would handle it, I pieced it together from various stack overflow posts and the offical documentation. The result is that the tray icon appears, with the correct image and tooltip. When I right click it I see the menu item for "exit" show up. But that's where it breaks, the menu item doesn't have any hover coloring (leading me to believe input at all with it is broken) and clicking on the item turns up no results. Have I made some silly mistake like ordering the adding of items wrong? What's going on here?
As it turns out I was making use of a Global Mouse Hook in an old part of the code that I had all but forgotten about. The hook is from this repository and the fix was changing the hook's raw input setting from true to false.
// True instead of false seems to block JavaFX events
private static GlobalMouseHook mouseHook = new GlobalMouseHook(false);
I am working with Swing right now and I do not get this to work properly.
What I need is the following:
I've got a class "Client" that is able to connect to a TCP server.
If the connection fails (wrong IP for example), then it will show an error dialog that can be closed by clicking on the "OK" Button.
However if the client connected successfully, a window should popup that runs until my client receives a specific message from the server.
My code looks like this:
if(ip != null) {
Client c = new Client();
try{
c.connect(ip, 56556);
JOptionPane msg = new JOptionPane("Connecting...", JOptionPane.INFORMATION_MESSAGE);
JDialog dlg = msg.createDialog("Connecting...");
dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dlg.setVisible(true);
c.addIncomingMessageHandler(new IncomingMessageHandler(){
#Override
public void incomingMessage(Connection<?> cnctn, Object o) {
dlg.setVisible(false);
dlg.dispose();
}
});
}catch(Exception e) {
int n = JOptionPane.showOptionDialog(this, "Oops! Something went wrong!",
"Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
null, new Object[] {"OK"}, JOptionPane.OK_OPTION);
}
}
So the exception is throws if c.connect() fails.
c.addIncomingMessageHandler() is a listener that listens to any incoming messages to the client. If the server sends something, this method will be called. If that's the case, the JDialog will be closed. But this window can be closed right now by clicking on the OK-Button.
I'd like to rename that button and add a function.
The new text should be "Cancel" and if the button is pressed, the client should be closed (c.disconnect) and the window itself should be closed as well.
How could I do that?
From the Documentation:
Stopping Automatic Dialog Closing
By default, when the user clicks a JOptionPane-created button, the dialog closes. But what if you want to check the user's answer before closing the dialog? In this case, you must implement your own property change listener so that when the user clicks a button, the dialog does not automatically close.
DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog, that uses JOptionPane both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yes/No JOptionPane. Though this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs.
Besides setting the property change listener, the following code also calls the JDialog's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. If you do not care to be notified when the user closes the window explicitly, then ignore the bold code.
final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
final JDialog dialog = new JDialog(frame,
"Click a button",
true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setLabel("Thwarted user attempt to close window.");
}
});
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible()
&& (e.getSource() == optionPane)
&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
}
}
});
dialog.pack();
dialog.setVisible(true);
int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
setLabel("Try using the window decorations "
+ "to close the non-auto-closing dialog. "
+ "You can't!");
}
Click here!
Related question.
When I run my application in Linux with Metal look and feel, the user can't be identitied whether the button is pressed or not. it look like button is not pressed though the buttton is in press mode. also the right hand side close button icon is not same as windows.
how can i resolve this two issues?
EDIT
I did following way.
try {
m_FrameBackground = new Color(Integer.parseInt((String)
Client.getClient().getProperty("BackgroundColor"),16));
m_TaskBackground = new Color(Integer.parseInt((String)
Client.getClient().getProperty("TaskBackground"),16));
} catch (Exception e) {
m_FrameBackground = new Color(Integer.parseInt("dfd3be",16));
m_TaskBackground = new Color(Integer.parseInt("dfd3be",16));
}
m_FuelTheme.secondary3 = new ColorUIResource(m_FrameBackground);
m_FuelTheme.secondary2 = new ColorUIResource(m_FrameBackground.darker());
m_FuelTheme.secondary1 = new ColorUIResource(m_FrameBackground.darker().darker());
MetalLookAndFeel.setCurrentTheme(m_FuelTheme);
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
JDialog.setDefaultLookAndFeelDecorated(true);
is there any way to save an image from a java applet
Been asked before:
Java applet - saving an image in a png format
or
Save an Image to a File in a Applet?
Please first search your question or at least check out the related questions as you type your question in. It's very helpful for finding other users with common issues.
Just try this notepad example which helps u to load images and save it also,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
public class Notepad extends JFrame implements ActionListener {
private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
private Menu file = new Menu(); // our File menu
// what's going in File? let's see...
private MenuItem openFile = new MenuItem(); // an open option
private MenuItem saveFile = new MenuItem(); // a save option
private MenuItem close = new MenuItem(); // and a close option!
public Notepad() {
this.setSize(500, 300); // set the initial size of the window
this.setTitle("Java Notepad Tutorial"); // set the title of the window
setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed)
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea
// this is why we didn't have to worry about the size of the TextArea!
this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically
this.getContentPane().add(textArea);
// add our menu bar into the GUI
this.setMenuBar(this.menuBar);
this.menuBar.add(this.file); // we'll configure this later
// first off, the design of the menuBar itself. Pretty simple, all we need to do
// is add a couple of menus, which will be populated later on
this.file.setLabel("File");
// now it's time to work with the menu. I'm only going to add a basic File menu
// but you could add more!
// now we can start working on the content of the menu~ this
gets a little repetitive,
// so please bare with me!
// time for the repetitive stuff. let's add the "Open" option
this.openFile.setLabel("Open"); // set the label of the menu item
this.openFile.addActionListener(this);
// add an action listener (so we know when it's been clicked
this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false));
// set a keyboard shortcut
this.file.add(this.openFile); // add it to the "File" menu
// and the save...
this.saveFile.setLabel("Save");
this.saveFile.addActionListener(this);
this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
this.file.add(this.saveFile);
// and finally, the close option
this.close.setLabel("Close");
// along with our "CTRL+F4" shortcut to close the window, we also have
// the default closer, as stated at the beginning of this tutorial.
// this means that we actually have TWO shortcuts to close:
// 1) the default close operation (example, Alt+F4 on Windows)
// 2) CTRL+F4, which we are about to define now:
(this one will appear in the label)
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
this.close.addActionListener(this);
this.file.add(this.close);
}
public void actionPerformed (ActionEvent e) {
// if the source of the event was our "close" option
if (e.getSource() == this.close)
this.dispose(); // dispose all resources and close the application
// if the source was the "open" option
else if (e.getSource() == this.openFile) {
JFileChooser open = new JFileChooser();
// open up a file chooser (a dialog for the user to browse files to open)
int option = open.showOpenDialog(this);
// get the option that the user selected (approve or cancel)
// NOTE: because we are OPENing a file, we call showOpenDialog~
// if the user clicked OK, we have "APPROVE_OPTION"
// so we want to open the file
if (option == JFileChooser.APPROVE_OPTION) {
this.textArea.setText("");
// clear the TextArea before applying the file contents
try {
// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
while (scan.hasNext()) // while there's still something to read
this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
} catch (Exception ex) { // catch any exceptions, and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
// and lastly, if the source of the event was the "save" option
else if (e.getSource() == this.saveFile) {
JFileChooser save = new JFileChooser(); // again, open a file chooser
int option = save.showSaveDialog(this); // similar to the open file, only this time we call
// showSaveDialog instead of showOpenDialog
// if the user clicked OK (and not cancel)
if (option == JFileChooser.APPROVE_OPTION) {
try {
// create a buffered writer to write to a file
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
out.write(this.textArea.getText()); // write the contents of the TextArea to the file
out.close(); // close the file stream
} catch (Exception ex) { // again, catch any exceptions and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
}
// the main method, for actually creating our notepad and setting it to visible.
public static void main(String args[]) {
Notepad app = new Notepad();
app.setVisible(true);
}
}
in JOption pane I have some JTextArea where user must eneter some text. Then if user click OK code execute. But i want that code will not execute if input text is not enetered.
I am using mouse listener to check OK button but i do not know how to reopen JOption if input text is not enetered and let him go to next step if is text enetered.
my code:
case JOptionPane.YES_OPTION: {
String text= op.getText();
if (text.equals("")) {
// how to prevent closing joptionpane!
} else {
// my code
break;
}
}
JTextArea txt = new JTextArea();
JButton ok = new JButton("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (txt.getText().toString().trim().length() == 0 ) {
}
else {
//your action...
}
}
});
By setting the event property of the listener programmticaly to true, you can "catch" the click and prevent the dialog from closing. Simply check if the TextArea is empty in the click event and if yes, set handled to true.
Further you should provide a information to the user afterwards, which field needs to be filled.