I create a jPanel and I open a new jDialog when I click on button (dlgSegments is a JDialog that opened):
JButton btnAddSegment = new JButton("Add GeoSegment");
btnAddSegment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlgSegments.setVisible(true);
}
});
Then in the opened jDialog I want to return the "selected" back to the jPanel which called this jDialog.
How can I implement it?
This is the button listener in the opened jDialog and seleced is the variable that I want to pass to the jPanel:
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GeoSegment selected = lstSegments.getSelectedValue();
// i want to send back the selected value
}
});
One possible solution: If you create your Dialog send an DataObject to the Dialog via his constructor. The DataObject conatins the value you are interested in.
MyDataObject dataObject = new MyDataObject();
MyDialog dialog = new MyDialog(dataObject);
fill the DataObject with the selected value in the dialog.
If you're still working on this problem, your Add button can call getSelectedIndex() or getSelectedIndices() to find out what's selected. Then fire a PropertyChangeEvent like #Hovercraft Full Of Eels shows here. Have you main panel do addPropertyChangeListener() to listen to the dialog.
Related
I have a JFrame (called FTask) with public void method. Example code:
public void clear() {
jTable1.clearSelection();
jButton1.setEnabled(false);
jButton3.setEnabled(false);
jButton2.setEnabled(false);
jTextArea1.setText(null);
}
Then, I have JDialog with a button. I want when I click the button, frame do the 'clear' method to the frame.
I've tried:
FTask ft = new FTask();
ft.clear();
But it didn't work.
I've tried:
FTask ft = new FTask();
ft.clear();
But it didn't work.
No, it wouldn't. This code is creating a new (2nd instance) of the frame that is not set visible. What you need is a reference to the original frame.
This can be fixed in a number of ways, too broad to go into here, and is Object Oriented Programming 101 that should be mastered before trying to write GUI'd apps. - which add their own complications.
You have to use actionlistener in order to run the code when the button is clicked.
JButton button = new JButton("Click me");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
if(e.getSource() == button){
System.out.println("You clicked the button");
//In your case:
ft.clear();
}
}
});
As #Menno said, you have to use ActionListener in order to detect Button Clicks
Here is the Java 8 Style:
JButton button = new JButton("Click me");
//Add action listener to button
button.addActionListener(
ae -> ft.clear();
);
// Add button to frame
add(button);
I have a panel that contains a File Section button. The Button itself should load FileDialog() upon click. Upon calling FileDialog() constructor I figured out that it asks parent either Frame or Dialog while I was passing JPanel. The Panel itself is called in JOptionPane.showMessageDialog() method. How to make it possible? Code is given below:
JPanel pnlMain;
JButton btnPath;
pnlPath.add(btnPath);
//Click Event
btnPath.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("File Section Clicked..");
java.awt.FileDialog fd = new java.awt.FileDialog();
}
});
JOptionPane.showMessageDialog(null, pnlMain, "Settings", JOptionPane.PLAIN_MESSAGE);
I created a new Instance of JFrame and it worked:
FileDialog fd = new FileDialog(new Frame(),"My Settings",FileDialog.LOAD);
I am creating an application that has 1 JFrame java file and 1 JDialog java file.
In the JFrame, I have a button and when pressed I want it to display what I have designed in the JDialog.
So for example, my JFrame java file is called MMainView.java and my JDialog is called OptionView.java. So when the button in MMainView.java is pressed I want to display the JDialog I have designed in OptionView.java.
So in my MMainView.java file, I have a function that is called when that button is pressed. How do I display the dialog in OptionView.java?
SOLVED
For those wondering. This is what I did:
private JDialog optionView; ~~> JDialog Declaration
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (optionView == null) {
JFrame mainFrame = myApp.getApplication().getMainFrame();
optionView = new OptionView(mainFrame, true);
optionView.setLocationRelativeTo(mainFrame);
}
myApp.getApplication().show(optionView);
}
Sounds like you want to create an ActionListener for your button, and set the visibility of the JDialog to true when you press the button.
Something on these lines:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionevent)
{
//set the visibility of the JDialog to true in here
}
});
Let's say your button is called myBtn.
The class should look like this.
public class MMainView extends JFrame
implements ActionListener
You should use a listener for the button.
JButton myBtn = new JButton();
myBtn.addActionListener(this);
And finally:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myBtn) {
new OptionView();
You don't really need the if, it's just in case you want to add more buttons for the actionPerformed.
First register the button in "MainView.java", like below.
b1.addActionListener(this);
b1.setName("OpenJDialog");
//this is to read in actionperformed method incase you have more than one button
// in action performed method call the dialogue class
public void actionPerformed(ActionEvent ae){
JButton jb = (JButton)ae.getSource();
String str = jb.getName();
if(str.equals("OpenJDialog"){
new OptionView();
//I am assuming u are configuring jdialog content in OptionView constructor
}
}
In my program I have a main JFrame that holds a button. When this button is clicked a new JFrame appears in which I can change some information. Whenever I finish editing I press a save button on the new JFrame which saves the changes and disposes the JFrame. Now when this is done, I'd like to perform an action in the main JFrame as well, but only if something changed. If I open the new JFrame and just close it again without using the save button, I don't want to do anything in the main frame.
I've tried searching the web for a solution, but just don't seem to be anything useful out there..
An example of the code I've got so far:
Main Frame...
public class MainFrame extends JFrame
{
public MainFrame()
{
super("Main Frame");
JButton details = new JButton("Add Detail");
add(details);
details.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
new DetailFrame().setVisible(true);
}
});
}
}
Detail Frame...
public class DetailFrame extends JFrame
{
public DetailFrame()
{
super("Detail Frame");
JButton save = new JButton("Save");
add(save);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Save whatever content
dispose();
}
});
}
}
So when I click the "Save" button on the Detail Frame, I want to do something in the Main Frame, whereas when the "x" is clicked on the Detail Frame, I don't want to do anything..
Hope someone is able to help me, and sorry for my english..
You can pass a MainFrame handle to the DetailFrame constructor. Then, on clicking the Save button, the DetailFrame would call a function in MainFrame and pass the changes to it.
Another way is to create a public boolean variable in DetailFrame and set it to true when the Save button is clicked. This way MainFrame will know whether the DetailFrame was closed or Save'd.
EDIT: Some more ideas:
Use JDialog instead of JFrame. JDialog.setVisible is modal, i.e. it will block the calling function until the dialog is closed; this way you can process the results of the dialog in the same "Details" button listener.
To access the dialog after it is called, store the dialog in a separate variable. First construct the dialog, then show it, and then process the result by analyzing its variables.
Store the results of editing in other public variables of DetailFrame (or let's call it DetailDialog). This should happen only when the "Save" button is clicked. This may even allow to go without the boolean variable (depends on the types of values you are editing).
DetailDialog dlg = new DetailDialog();
dlg.setVisible(true);
if(dlg.approvedResult != null) {
// process the result...
}
EDIT: Sorry, JDialog is not modal by default. Need to call a special super constructor to make it modal.
Also, here you will have to pass the reference to MainFrame to the dialog constructor, but you still can declare it as a simple JFrame and avoid unnecessary dependencies.
To get the reference to the enclosing MainFrame from within the anonymous ActionListener, use MainFrame.this.
To be able to change the button text after it was created, you will have to store the button in a member variable.
Main Frame...
public class MainFrame extends JFrame
{
private JButton details = new JButton("Add Detail");
public MainFrame()
{
super("Main Frame");
getContentPane().add(details);
details.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
DetailDialog dlg = new DetailDialog(MainFrame.this);
dlg.setVisible(true);
if(dlg.approved){
details.setText("Edit Detail");
}
}
});
}
}
Detail Dialog... (not Frame)
public class DetailDialog extends JDialog
{
public boolean approved = false;
public DetailDialog(JFrame parent)
{
super(parent,"Detail Dialog",true); // modal dialog parented to the calling frame
JButton save = new JButton("Save");
getContentPane().add(save);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Save whatever content
approved = true;
dispose();
}
});
}
}
Create the detail frame in the main frame, and add a windowlistener to it, using the windowadapter class. Implement the windowclosing event by checking for changes, handle those, and then dispose the detail frame. This is all done in the mainframe.
The detail frame should have do nothing on close set to prevent the detail frame being disposed before you recorded the changes.
You may wish to implement checking for changes in the detailframe as a method returning a class holding the interesting data. That way your windowlistener can be small an to the point.
Forget the 2nd JFrame. use a modal dialog instead. It will block input until dismissed. Once dismissed, the only thing to do is decide whether to update the original data. JOptionPane has some inbuilt functionality that makes that easy. If the user presses Cancel or the esc key, the showInputDialog() method will return null as the result.
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class EditInfo {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame("Uneditable");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout(10,10));
final JTextField tf = new JTextField("Hello World!", 20);
tf.setEnabled(false);
p.add(tf, BorderLayout.CENTER);
JButton edit = new JButton("Edit");
edit.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
String result = JOptionPane.showInputDialog(
f,
"Edit text",
tf.getText());
if (result!=null) {
tf.setText(result);
}
}
} );
p.add(edit, BorderLayout.EAST);
p.setBorder(new EmptyBorder(10,10,10,10));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
If it is necessary to edit a number of fields all at once in the JOptionPane, use a JPanel to contain them all, and put them in a showMessageDialog() call. Check the integer based return result to determine if the user OK'd the changes.
I have created a modal JDialog box with a custom drawing on it and a JButton. When I click the JButton, the JDialog box should close and a value should be returned.
I have created a function in the parent JFrame called setModalPiece, which receives a value and sets it to a local JFrame variable.
The problem is that this function is not visible from the JDialog box (even though the JDialog box has a reference to the parent JFrame).
Two questions:
1) Is there a better way to return a value from a JDialog box to its parent JFrame?
2) Why can't the reference to the JFrame passed to the JDialog be used to access my JFrame function setModalPiece?
I generally do it like this:
Dialog dlg = new Dialog(this, ...);
Value result = dlg.showDialog();
The Dialog.showDialog() function looks like this:
ReturnValue showDialog() {
setVisible(true);
return result;
}
Since setting visibility to true on a JDialog is a modal operation, the OK button can set an instance variable (result) to the chosen result of the dialog (or null if canceled). After processing in the OK/Cancel button method, do this:
setVisible(false);
dispose();
to return control to the showDialog() function.
You should do the opposite by adding a custom method getValue() to your custom JDialog.
In this way you can ask the value of the dialog from the JFrame instead that setting it by invoking something on the JFrame itself.
If you take a look at Oracle tutorial about dialogs here it states
If you're designing a custom dialog, you need to design your dialog's API so that you can query the dialog about what the user chose. For example, CustomDialog has a getValidatedText method that returns the text the user entered.
(you can find source of CustomDialog to see how they suppose that you will design your custom dialog)
I don't know if I can explain my method in a cool way...
Let's say I need productPrice and amount from a JDialog whos going to get that info from user, I need to call that from the JFrame.
declare productPrice and ammount as public non-static global variables inside the JDialog.
public float productPrice;
public int amount;
* this goes inside the dialog's class global scope.
add these lines in the JDialog constructor to ensure modality
super((java.awt.Frame) null, true);
setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
* this goes within the dialog's class constructor
let's say your JDialog's class name is 'MyJDialog' when calling do something like this
MyJDialog question = new MyJDialog();
MyJDialog.setVisible(true);
// Application thread will stop here until MyJDialog calls dispose();
// this is an effect of modality
//
// When question calls for dispose(), it will leave the screen,
// but its global values will still be accessible.
float myTotalCostVar = question.productPrice * question.ammount;
// this is acceptable.
// You can also create public getter function inside the JDialog class,
// its safer and its a good practice.
* this goes in any function within your JFrame and will call JDialog to get infos.
When you pass any value to JFrame to JDialog then create parametrized constructor of jdialog and in jframe whenever you want to call.
e.g. The parametrized constructor like :
public EditProduct(java.awt.Frame parent, boolean modal, int no) {
//int no is number of product want to edit.
//Now we can use this pid in JDialog and perform whatever you want.
}
When you want to pass values from JDialog to JFrame create a bean class with set and get method the the values using vector and get these values in jframe.
More info
Here is how I usually do it. I wasn't sure, that's why I've created that post:
Returning value from JDialog; dispose(), setVisible(false) - example
Add an interface to your constructor?
public class UploadConfimation extends JDialog {
private final JPanel contentPanel = new JPanel();
public interface GetDialogResponse{
void GetResponse(boolean response);
}
/**
* Create the dialog.
*/
public UploadConfimation(String title, String message, GetDialogResponse result) {
setBounds(100, 100, 450, 300);
setTitle(title);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JLabel lblMessage = new JLabel(message);
contentPanel.add(lblMessage);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("YES");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
result.GetResponse(true);
dispose();
}
});
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("NO");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
result.GetResponse(false);
dispose();
}
});
buttonPane.add(cancelButton);
}
}
}
}