Can I make anonymous event handler method to act conditional like
JButton activeDataBtn = new JButton("Active");
activeDataBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (activeDataPanel.setVisible(false)) { //Erroneous code
readDataFromFile(); //a method reads data from .csv
//file and shows it on activeDataPanel
activeDataPanel.setVisible(true);
}
else
activeDataPanel.setVisible(false);
}
}
});
how can i make this conditional?
Sure you can, but that code is not valid:
if (activeDataPanel.setVisible(false))
maybe you want to check if your panel is visible try it this way:
if (activeDataPanel.isVisible())
or maybe activeDataPanel.getVisible() I'm not sure about the getter name for it right now :)
Related
I'm having a problem with my Java code.
I need to execute my doSomething() method, which includes code that manage also global variables. The problem is that the method is invoked twice (both mouseEvent and focusEvent of my JTable are fired at the same time).
How can I execute the doSomething() method only once at a time, in a sort of mutual exclusion ?
Thanks.
addMouseListener (new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
doSomething();
}
});
addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e){
doSomething();
}
});
JTable cells contains String with length 1 or 2.
I need to apply a setValue method (or delete the String), in the exact moment the user stops the cell editing or he writes a 2 character String.
With those listeners I know the exact time to do the setValue or to inform the user that the first character he wrote doesn't exist. So in that way I wanted to block the user's action.
In other words, I need to control the user input in order to do a setValue or delete it. FocusLost tells me when the user clicks outside the JTable Component.
MouseClicked tells me when the user clicks in the JTable Component.
When mouseClicked is invoked and the JOptionPane appears, the cell automatically lose the focus, and so also the focusLost is invoked.
public void doSomething () {
// inEdit and tableCellEdited are the global variables
if ( inEdit && tableCellEdited != null ) {
String temp = "" + tableCellEdited.getDay();
String s = tableCellEdited.getValRenderer().trim();
if (s.length() > 2) s = s.substring(4);
if ( !s.trim().isEmpty() ) {
JOptionPane.showMessageDialog(getParent(),
"Code doesn't exist" , "Error: Code doesn't exist",JOptionPane.WARNING_MESSAGE);
tableCellEdited.setRendererValue(getUltimaGG(), false);
}
else {
tableCellEdited.setRendererValue(s, false);
setValueAt(tableCellEdited, getRowFromMat(tableCellEdited.getMat()), Integer.parseInt(temp.substring(6, 8)) );
}
clearProgrammazioneDueCaratteri();
}
}
repaint();
}
For school, I'm attempting to recreate Microsoft's Notepad program using Java's Swing. I'm working on the saving and opening of .txt files, and I'm trying to figure out a way for the program to detect when a change has been made to the document. If a change has been detected and the user chooses to open or create a new file, I want the program to prompt the user if they would like to save their changes before continuing.
My thought for this was to create a flag, called documentChanged, that would initially be false, and which would be set to true whenever a change was made to the JTextArea. To detect this change, I thought of using a TextListener as follows:
public class JNotepad implements ActionListener
{
boolean documentChanged;
JTextArea notepad;
JNotepad()
{
documentChanged = false;
notepad = new JTextArea();
notepad.addTextListener(new TextListener() {
public void textValueChanged(TextEvent te) {
documentChanged = true;
}
});
}
}
However, I learned that Java classes are unable to implement multiple interfaces at once, and I'm already using ActionListeners to implement the items of my notepad's menu bar.
My question is, is there any way to use both TextListener and ActionListener (or any other listener) simultaneously in the same class? If not, what would be my best plan of action for detecting a change in the document?
It was answer in another post. See Text Changed event in JTextArea? How to?
And also see How to Write a Document Listener (DocumentListener) in Oracle, you will see an applet example.
How does your this even compile
notepad = new JTextArea();
notepad.addTextListener(new TextListener() {
// ....
}
since TextListeners are not defined to work with JTextAreas but rather with TextAreas, a completely different beast.
You should add a DocumentListener to your JTextArea's Document.
notepad.getDocument().addDocumentListener(new DocumentListener() {
void insertUpdate(DocumentEvent e) {
documentChanged = true;
}
void removeUpdate(DocumentEvent e) {
documentChanged = true;
}
void changedUpdate(DocumentEvent e) {
documentChanged = true;
}
});
Regarding
My question is, is there any way to use both TextListeners and ActionListeners (or any other listener) simultaneously in the same class?
Use of a DocumentListener has nothing to do with ActionListeners used elsewhere in your program since their domains are orthogonal to each other, i.e., the one has absolutely nothing to do with the other.
I'm making a program that adds and formats files. I actually have many classes, but for the purpose of this question let's say I have two, guidialog and guimain.
In guidialog I have a JTextField and an actionlistener for it. Here is the actionlistner:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain();
blockAddWrite.addNewBlockFile();
}
});
public String blockName;
Now in guimain I have a formatter which writes a file based on the name given in the text field:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
try {
newBlock = new Formatter("Block" + blockName.blockName + ".java");
System.out.println("Created File: Block" + blockName.blockName);
} catch (Exception e) {
System.out.println("ERROR: Could Not Output Block File");
}
}
I do edit and close the file, but it wasn't necessary. But when I try this, all of the stuff in guimain that refers to blockName outputs as "null". I can't figure it out.
That's because in guimain, you're not using the blockName field of the dialog where the user entered something: you're using the blockName field of another, newly constructed dialog:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
^--- the dialog is not the one where the user entered something. It's a new one.
You should pass the blockName from the dialog to the guimain:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain(blockName); // we construct a guimain instance with the entered text
blockAddWrite.addNewBlockFile();
}
});
Side notes:
you should not use public fields. Use getter methods.
classes should be start with an upper-case and be spelt in CamelCase: GuiMain.
hi i have a full screen program which i dont want people to close unless they have a password i have this code at the moment
public void windowClosing(WindowEvent arg0)
{
System.out.println("HERE");
String inputValue = JOptionPane.showInputDialog("Please input the closeword");
if (inputValue != "closeplz")
{
}
}
in the if statement i want it to stop the method so that the program doesent close. any help would be greatly aprecheated thanks ste
You have to call
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
on (or within) the JFrame instance. Then the frame will not close unless you do it manually, though windowClosing() will still be called. Inside it, you can then conditionally call
System.exit(1);
which will end the application. Be sure to do any necessary cleanup first.
Check out Closing an Applicaton for a simple class to help you with this. You would need to provide the custom close action that prompts the user for the password.
Using your simple example the code would be:
Action ca = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
JFrame frame = (JFrame)e.getSource();
String inputValue = JOptionPane.showInputDialog("Please input the closeword");
if (! inputValue.equals("closeplz"))
{
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
};
CloseListener cl = new CloseListener(ca);
i write a method to create a form(3 buttons and a textBox), then i call it in main.
but when i run program, before i enter information in the form (method form6 ),
Other commands that are executed! "s4 and ontname chenged in the form".
this is a part of my code:::::::::::
//////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
System.out.println("*begin main*"); // call form method
String s4= form6(); // s4 is returned by method.
System.out.println("s3333*"+s4);
System.out.println("ont:"+ontname);//it's global }
//////////////////////////////////////////////////////////////////////////
i have 2 questions:::
1--- While the form is running, other commands are executed!
What is their order execution?
2. --- i want to define a button to when i click it,it closes the form.
thanks all.
If I get your code correctly, ontname is either (1) a class member (declared outside a method) or (2) a local variable, which is declared in the method that contains this code snippet.
In both cases there is no need to "return" ontname just because it is not declared inside the anonymous ActionListener instance.
The following example illustrates a typical pattern for this problem:
public void someMethod() {
// ...
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
setOntName(selFile.getPath()); // <-- here we call another method
}
});
// ...
}
void setOntName(String ontName) {
// do something with ontName
}
Alternativly: declare ontName as a static class member (only):
private static String ontName = ""; // <-- accessible from main method
public static void main(String[] args) {
// ...
}
// more methods.
You can't return a value in this Method because the ActionListenerInterface does not allow this. But you can call another method from within the actionPerformed() method and pass the ontname to it.
You can also close the third button in the new method. Or define the third button as final and use it in the actionPerformed() method.
E.g.
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
anotherMethod(ontname);
}
});
private void anotherMethod(String path) {
//doSomething with the path
//close third button here
}
You could probably define your variable ontname as global, outside of your function:
var ontname = null;
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// ...
ontname=selFile.getPath();
}
});
// ...
System.out.println("filepath: "+ontname);
If you want to remember the values, then they should be class level variables.
But, generally, you would want to pass these to some other method to do some processing on them (or, say, persist them in a file). You can pass these as parameters to the other method.
(The second one is better in most cases, I don't know much about your app, so I am unable to give one answer)
There are other problems with your code:
You need to check whether the use has clicked the "Ok" or "Cancel" button in the open dialog to decide whether to get the file or not.
String filename = File.separator+"c:"; does not really make sense. Perhaps you meant String filename = "c:"+File.separator; But even this is not very useful. File.separator is for getting the platform specific file separator char (\ in Windows, / on linux) but since you are hard coding c:, you are anyway constrainting your app to Windows. You might want to have a better platform independent way (start at the "default" path, new JFileChooser() without arguments, and then remember the path the user last used, and proceed from there)
If the argument to the showOpenDialog method is your parent frame, then the dialog would be centered on the parent frame, and would, in most cases, look nicer.
You might also want to relook your variable names.
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
int option = fc.showOpenDialog(null);
if(option = JFileChooser.APROVE_OPTION)
{
File selFile = fc.getSelectedFile();
String ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
doSomeOperation(ontname); //Or, declare ontname as a class level variable.
}
}
});