how to use mouse click event - java

Hi i have a class where i am using mouseclick event i want to call another class when i click from my mouse
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList theList = (JList) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = theList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object o = theList.getModel().getElementAt(index);
// System.out.println("Double-clicked on: " + o.toString());
String a=o.toString();
LiistSelection.setListIndex(a);
System.out.println(LiistSelection.getListIndex());
new MyGui4();
}
}
}
};
i want to call this class when user click on list then new window should open
here is my class mygui4.java
public class MyGui4 extends JFrame
{
JLabel jLabel1;
Container pane;
private static ResultSet resultSet = null;
public void Gui( )
{
{
getContentPane().setBackground(new java.awt.Color(255,153,51));
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
ImageIcon image = new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\a0.png");
Border border = LineBorder.createGrayLineBorder();
jLabel1 = new JLabel(image);
jLabel1.setBorder(border);
jLabel1.setBackground(Color.red);
c.add(jLabel1);
setLayout(null);
}
public static void main( String[] args )
{
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
}
}

You want to Create a object of another Class and call a function using a object.
class second
{
//.....
public void function()
{
//........
}
public void function(int index)
{
//..........
}
}
second s=new second();
s.function()//calling function
int i=10;
s.function(i)//calling function with parameter
Try This Example :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class m extends JFrame
{
String s="The Value of List is 10";
m()
{
setVisible(true);
pack();
setLayout(null);
JButton b=new JButton("Click to Open another form");
b.setBounds(10,10,200,40);
add(b);
b.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
new s(s);//calling another class contructor
}
});
}
public static void main (String[] args)
{
new m();
}
}
class s extends JFrame
{
s(String s)
{
setVisible(true);
setSize(100,100);
setTitle(s);
}
}
Click The button Another Class and Open The Window

It looks to me like you are tying to invoke the class MyGui4 from the command line when you start the JVM or from another application when you click on the JList, If so then the code needs to be the same in both places.
When invoked from the command line the main() method is invoked which in turn invokes 3 lines of code:
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
When you invoke the code when clicking on the JList you invoke 1 line of code:
new MyGui4();
Can you tell me what the difference is?
Of course I still don't understand the point of this code because none of the methods in your MyGui4 class accept a parameter. So it doesn't matter which item in the JList you click on you will still display the same GUI with the same information. You need to pass the selected object from your JList to your GUI.

Related

How to prevent that closing a JDialog closes the entire application

I have a main(screen) gui window and need to open a few "multi input" windows (jdialog or when not possible jframe), for example to add preferences (4 textfields with 2 filechoosers and 2 radiobuttons).
When pressing OK/Cancel in these JDialogs (or JFrames), my entire application closes.
I don't want that. How can I prevent that?
First try: I tried the intelliJ option "New -> Create Dialog class", which gives me a JDialog with OK/Cancel button. Pressing one of the buttons closes the JDialog and my entire application.
Second try: I wrote a class "by hand" which creates a JDialog (and also tried JFrame). Again: Pressing one of the buttons closes the JDialog and my entire application.
I removed "dispose()" and "setVisible(false)" options from theJDialog (JFrame), but still my entire application is closed.
main class method
public class mainScreen {
// Menu action listener (only relevant options)
class MenuActionListener implements ActionListener {
// menuListener
public void actionPerformed(ActionEvent ev) {
//myVariables myVars = new myVariables();
String[] dummy = null;
System.out.println("Selected: " + ev.getActionCommand());
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
}
// method that opens the external class (see below in following code block)
private void showPreferencesDialog() {
prefJDialog myprefs = new prefJDialog(prefsPanel);
myprefs.showDialog();
boolean okPressed = myprefs.isOkPressed();
if (okPressed) {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"OK pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"Cancel pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
}
}
// This is the class which is mention in the manifest
public mainScreen(JFrame frame) {
boolean preferences = false;
Preferences prefs = Preferences.userRoot();
createmyMenuBar(frame);
groupRadiobuttonsandListen();
fileNamesTableListener();
try {
myUtils.DisplayLogo(mainScreen.this.iconLabel);
} catch(IOException ex) {
System.out.println("Error reading Logo");
}
preferences = check_preferences();
if (!preferences) {
myUtils.checkExifTool(mainScreen.this.rootPanel);
}
programButtonListeners();
}
// main method in my main class for my project
public static void main(String[] args) {
JFrame frame = new JFrame("jExifToolGUI");
frame.setContentPane(new mainScreen(frame).rootPanel);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The JDialog class/method that is called from the main class
package org.hvdw.jexiftoolgui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class prefJDialog extends JDialog {
private JButton okButton;
private JButton cancelButton;
private JPanel prefsPanel;
private boolean okPressed;
public prefJDialog(JPanel prefsPanel) {
super(JOptionPane.getFrameForComponent(prefsPanel), true);
this.prefsPanel = prefsPanel;
setTitle("Preferences");
initDialog();
}
public void showDialog() {
setSize(800, 768);
double x = getParent().getBounds().getCenterX();
double y = getParent().getBounds().getCenterY();
setLocation((int) x - getWidth() / 2, (int) y - getHeight() / 2);
setVisible(true);
}
private void initDialog() {
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
add(pane);
pane.add(Box.createVerticalGlue());
FlowLayout l = new FlowLayout(FlowLayout.RIGHT);
JPanel buttonsPane = new JPanel(l);
okButton = new JButton("Save"); //$NON-NLS-1$
buttonsPane.add(okButton);
pane.getRootPane().setDefaultButton(okButton);
cancelButton = new JButton("CANCEL"); //$NON-NLS-1$
buttonsPane.add(cancelButton);
buttonsPane.setMaximumSize(new Dimension(Short.MAX_VALUE, (int) l.preferredLayoutSize(buttonsPane).getHeight()));
pane.add(buttonsPane);
addListeners();
}
private void addListeners() {
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//saveProperties();
setVisible(false);
okPressed = true;
//close();
// dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
//dispose();
//close();
okPressed = false;
}
});
}
public boolean isOkPressed() {
return okPressed;
}
/*public void close() {
WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}*/
}
So how do I prevent that upon clicking OK or Cancel in the JDialog, the entire application closes. That needs to stay open until the user clicks the "window close" X in the top-right, or from the menu "File -> Exit"
I have searched Google for several days, but can't find a solution (and one same question without answer).
Edit:
After Patrick's answer I changed the close method to
public void close() {
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
And removed the /* and */.
I also activated the close(); in the listeners again, but it doesn't make a difference. My main app is still closed.
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
And the problem is that you don't have a break statement in your switch case so the code falls through to the "Exit" logic and does a System.exit(0)
This is why we need a proper "MCVE" with every question. When you post random pieces of code we can't see the entire logic flow.

Error: java.lang.IllegalArgumentException

Error in following code is: java.lang.IllegalArgumentException: adding container's parent to itself.
This is the code:
public class humev extends JFrame implements ActionListener{
//Dichiarazione variabili e costanti
private static final int larghezza = 1300;
private static final int altezza = 1000;
private static final String nome = "Human Evolution";
private JLabel lab;
private JButton gioca;
private JPanel pang;
public humev(){
try{
pang = new JPanel();
gioca = new JButton("Gioca!");
gioca.addActionListener(this);
lab = new JLabel();
gioca.add(gioca);
lab.add(lab);
pang.setLayout(null);
}
catch(Exception e1){
System.err.println(e1);
System.err.println("Impossibile caricare il frame di gioco!");
}
}
public static void main(String[] args) {
//Finestra
try{
humev h = new humev();
JFrame finestra = new JFrame(nome);
Dimension dim_finestra = new Dimension(larghezza, altezza);
finestra.setPreferredSize(dim_finestra);
finestra.setMaximumSize(dim_finestra);
finestra.setResizable(false);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
finestra.pack();
finestra.setVisible(true);
}
catch(Exception e2){
System.err.println(e2);
System.err.println("Impossibile caricare la finestra. Frame non caricato");
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == gioca){
lab.setText("Gioco avviato con successo!");
}
}
}
You cannot add a labelinto a label :-
lab.add(lab);
Aldo you cannot add a button on a button :-
gioca.add(gioca);
Try adding them to the JPanel or ContentPane instead like
:-
pang.add(gioca);
pang.add(lab);
getContentPane().add(pang);
EDIT:-
For Showing the JFrame you need to do first add your JPanel to JFrame then set the visibility of JFrame to true something like :-
finestra.add(pang); // add panel to frame
finestra.setVisible(true); // show frame visibility to true
Also don't set the layout to null :-
pang.setLayout(null);
Else you will need to set the bounds yourself. So just comment this line.
try to run this example.there is bunch of problems in your code.
you are adding component to itself
gioca.add(gioca); // don't do this
use layouts .don't use null
pang.setLayout(null); // don't do this .use layouts .and even if you use null then
//use bounds to absolutely position .if you use null layout and if you add using `.add()`
//then you will not see those components .
complete code
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class humev extends JFrame implements ActionListener {
private static final int larghezza = 1300;
private static final int altezza = 1000;
private static final String nome = "Human Evolution";
private final JLabel lab;
private final JButton gioca;
private final JPanel pang;
public humev() {
super(nome);
pang = new JPanel();
//pang.setLayout(new FlowLayout()); // use appropriate layout .for example flowlayout.since flowlayout is default layout for jpanel you can avoid it.but don't use null
gioca = new JButton("Gioca!");
gioca.addActionListener(this);
lab = new JLabel("lable");
pang.add(gioca);
pang.add(lab);
add(pang); // add pang panel to frame
Dimension dim_finestra = new Dimension(larghezza, altezza);
setPreferredSize(dim_finestra);
setMaximumSize(dim_finestra);
//setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
}
public static void main(String[] args) {
humev humev = new humev();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == gioca) {
lab.setText("Gioco avviato con successo!");
}
}
}
IllegalArgumentException is an Unchecked Exception.
It rises explicitly by API Developer or Programmer to indicate that a method has invoked with illegal argument.
example:
Thread t = new Thread();
t.setPriority(15);
output:
RuntimeException: IllegalArgumentExcepion
The valid range of Thread priority is 1 to 10, if we are trying to set the priority with any other value, then we will get IllegalArgumentException.

How can I access an Array List's elements inside an ActionListener from another ActionListener?

I have two Action Listener inner-classes inside one main class. Each one corresponds to its own button. One of the Action Listeners is coded to generate an Array List. The other simply writes that Array List to a Text Field.
My question is how can I refer to/access that data from the other Action Listener? The code below compiles but when I check the contents of the Array List from the second Action Listener, it is empty ([]).
I'm guessing this has something to do with the Array List re-instantiating when the other Action Listener's actionPerformed method is called. How can I work around this? (The code here is just the 2 Action Listeners).
// Create a Button Listener Inner Class for Input Route Button.
class InputRouteButtonHandler implements ActionListener {
List<String> routeStopList = new ArrayList<String>();
public void actionPerformed(ActionEvent event) {
String city1 = (String) cityCombo1.getSelectedItem();
String city2 = (String) cityCombo2.getSelectedItem();
if (city1.equals(city2)) {
JOptionPane.showMessageDialog(null, "Invalid route chosen. Please choose two different cities.");
} else {
routeStopList.add(city1); //Add city1 to start of array.
int dialogResult;
do {
String routeStop = JOptionPane.showInputDialog("Enter a stop between the 2 cities:");
routeStopList.add(routeStop);
dialogResult = JOptionPane.showConfirmDialog(null, "Add another stop?");
} while (dialogResult.equals(JOptionPane.YES_OPTION));
routeStopList.add(city2); //Add city2 to end of array.
System.out.println(routeStopList); //Just checking ArrayList contents
}
}
}
// Create a Button Listener Inner Class for Route Button.
class RouteButtonHandler extends InputRouteButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String city1 = (String) cityCombo1.getSelectedItem();
String city2 = (String) cityCombo2.getSelectedItem();
System.out.println(routeStopList); //Just checking ArrayList contents
if (city1.equals(city2)) {
JOptionPane.showMessageDialog(null, "Invalid route chosen. Please choose two different cities.");
} else {
for (int i = 0; i < routeStopList.size(); i++) {
String addedRoute = routeStopList.get(i);
adminPanelTextArea.append(addedRoute + "\n");
}
}
}
}
You are right, your problem is due to your creating two ArrayLists, lists that have absolulely no relationship with each other, other than holding the same type of objects and having the same names. A solution is to create one Model class that is shared by both ActionListener classes, and in this model class, have your ArrayList. Then give your ArrayList classes a setModel(Model model) method or constructor, and pass in a reference to the single Model object into both ActionListeners.
One other consideration is to use a single Control class to handle your listener type code, and then have your Control class hold a Model field.
As an aside, this is dangerous code:
if (city1 == city2) {
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
For example, say you have two buttons that want to manipulate a JList, one wanting to add text, the other wanting to clear it, then you could pass the JList's model into both button handlers. An example program could look like:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ShareList extends JPanel {
private static final String PROTOTYPE_CELL_VALUE = "ABCDEFGHIJKLMNOP";
private static final int VISIBLE_ROW_COUNT = 10;
private JTextField textField = new JTextField(10);
private DefaultListModel<String> listModel = new DefaultListModel<>();
private JList<String> myList = new JList<>(listModel);
public ShareList() {
myList.setPrototypeCellValue(PROTOTYPE_CELL_VALUE);
myList.setVisibleRowCount(VISIBLE_ROW_COUNT);
myList.setFocusable(false);
JPanel buttonPanel = new JPanel();
AddHandler addHandler = new AddHandler(listModel, this);
textField.addActionListener(addHandler);
buttonPanel.add(new JButton(addHandler));
buttonPanel.add(new JButton(new ClearHandler(listModel)));
JPanel rightPanel = new JPanel(new BorderLayout());
rightPanel.add(textField, BorderLayout.NORTH);
rightPanel.add(buttonPanel, BorderLayout.CENTER);
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(new JScrollPane(myList));
add(rightPanel);
}
public String getText() {
textField.selectAll();
return textField.getText();
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ShareList");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ShareList());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class AddHandler extends AbstractAction {
private DefaultListModel<String> listModel;
private ShareList shareList;
public AddHandler(DefaultListModel<String> listModel, ShareList shareList) {
super("Add");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
this.listModel = listModel;
this.shareList = shareList;
}
public void actionPerformed(ActionEvent e) {
String text = shareList.getText();
listModel.addElement(text);
};
}
#SuppressWarnings("serial")
class ClearHandler extends AbstractAction {
private DefaultListModel<String> listModel;
public ClearHandler(DefaultListModel<String> listModel) {
super("Clear");
putValue(MNEMONIC_KEY, KeyEvent.VK_C);
this.listModel = listModel;
}
public void actionPerformed(ActionEvent e) {
listModel.clear();
};
}

Communication between JOptionPane buttons and a custom panel

I have made a multiple input dialog by building a JPanel with the fields I want and adding it to a JOption pane
JMainPanel mainPanel = new JMainPanel(mensaje, parametros, mgr);
int i = JOptionPane.showOptionDialog(null, mainPanel, "Sirena",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
new String[] {"Aceptar", "Cancelar"}, "Aceptar");
However I'm having trouble with the buttons, because some of the fields are required. How can I make the "Ok" button to be enabled once every required field is up, or making the click on the button to make the validations and do not close the pane until every required field is filled?
From the Java API, I found this:
options - an array of objects indicating the possible choices the user
can make; if the objects are components, they are rendered properly;
non-String objects are rendered using their toString methods; if this
parameter is null, the options are determined by the Look and Feel
So, can't I pass custom buttons as parameter?
Looks like I will have to make my own JDialog? for which case, I don't know how to make it return an int just like JOptionPane does, any recommended tutorial?
In the example options is {"Aceptar", "Cancelar"} which are the displayed buttons,
PS. I have full controll over the fields I added to the JPanel.
This is a screenshot of the JOptionPane:
I don't think that you can de-activate a JOptionPane's selections buttons, but one way to still use the JOptionPane is to simply re-display it if the required fields have not been set. You could display an error message JOptionPane first describing the error, and then display a new JOptionPane that holds the same JPanel as its second parameter -- so that the data already entered has not been lost. Otherwise, you may want to create your own JDialog which by the way isn't that hard to do.
Edit
I'm wrong. You can enable and disable the dialog buttons if you use a little recursion.
For example:
import java.awt.Component;
import java.awt.Container;
import java.awt.event.*;
import java.util.HashSet;
import java.util.Set;
import javax.swing.*;
public class Foo extends JPanel {
private static final String[] DIALOG_BUTTON_TITLES = new String[] { "Aceptar", "Cancelar" };
private JCheckBox checkBox = new JCheckBox("Buttons Enabled", true);
private Set<AbstractButton> exemptButtons = new HashSet<AbstractButton>();
public Foo() {
JButton exemptBtn = new JButton("Exempt Button");
JButton nonExemptBtn = new JButton("Non-Exempt Button");
add(checkBox);
add(exemptBtn);
add(nonExemptBtn);
exemptButtons.add(checkBox);
exemptButtons.add(exemptBtn);
checkBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
allBtnsSetEnabled(checkBox.isSelected());
}
});
}
private void allBtnsSetEnabled(boolean enabled) {
JRootPane rootPane = SwingUtilities.getRootPane(checkBox);
if (rootPane != null) {
Container container = rootPane.getContentPane();
recursiveBtnEnable(enabled, container);
}
}
private void recursiveBtnEnable(boolean enabled, Container container) {
Component[] components = container.getComponents();
for (Component component : components) {
if (component instanceof AbstractButton && !exemptButtons.contains(component)) {
((AbstractButton) component).setEnabled(enabled);
} else if (component instanceof Container) {
recursiveBtnEnable(enabled, (Container) component);
}
}
}
public int showDialog() {
return JOptionPane.showOptionDialog(null, this, "Sirena",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
DIALOG_BUTTON_TITLES, "Aceptar");
}
private static void createAndShowGui() {
Foo foo = new Foo();
int result = foo.showDialog();
System.out.println(DIALOG_BUTTON_TITLES[result]);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This code uses listeners to check the state of a JCheckBox, but you can have listeners (DocumentListeners) listening to text field documents if you desire to know if they have data or not. The code then gets the JRootPane that holds the JCheckBox, then the root pane's contentPane, and all components of the dialog are held by this. It then recurses through all the components held by the dialog. If a component is a Container, it recurses through that container. If the component is an AbstractButton (such any JButton or checkbox), it enables or disables -- except for buttons held in the exempt buttons set.
A better example with document listeners
import java.awt.*;
import java.awt.event.*;
import java.util.HashSet;
import java.util.Set;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Foo2 extends JPanel {
private static final String[] DIALOG_BUTTON_TITLES = new String[] {
"Aceptar", "Cancelar" };
private static final int FIELD_COUNT = 10;
private Set<AbstractButton> exemptButtons = new HashSet<AbstractButton>();
private JTextField[] fields = new JTextField[FIELD_COUNT];
public Foo2() {
setLayout(new GridLayout(0, 5, 5, 5));
DocumentListener myDocListener = new MyDocumentListener();
for (int i = 0; i < fields.length; i++) {
fields[i] = new JTextField(10);
add(fields[i]);
fields[i].getDocument().addDocumentListener(myDocListener);
}
// cheating here
int timerDelay = 200;
Timer timer = new Timer(timerDelay , new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
checkDocsForText();
}
});
timer.setRepeats(false);
timer.setInitialDelay(timerDelay);
timer.start();
}
private void checkDocsForText() {
for (JTextField field : fields) {
if (field.getText().trim().isEmpty()) {
allBtnsSetEnabled(false);
return;
}
}
allBtnsSetEnabled(true);
}
private void allBtnsSetEnabled(boolean enabled) {
JRootPane rootPane = SwingUtilities.getRootPane(this);
if (rootPane != null) {
Container container = rootPane.getContentPane();
recursiveBtnEnable(enabled, container);
}
}
private void recursiveBtnEnable(boolean enabled, Container container) {
Component[] components = container.getComponents();
for (Component component : components) {
if (component instanceof AbstractButton && !exemptButtons.contains(component)) {
((AbstractButton) component).setEnabled(enabled);
} else if (component instanceof Container) {
recursiveBtnEnable(enabled, (Container) component);
}
}
}
public int showDialog() {
return JOptionPane.showOptionDialog(null, this, "Sirena",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
DIALOG_BUTTON_TITLES, "Aceptar");
}
private class MyDocumentListener implements DocumentListener {
public void removeUpdate(DocumentEvent arg0) {
checkDocsForText();
}
public void insertUpdate(DocumentEvent arg0) {
checkDocsForText();
}
public void changedUpdate(DocumentEvent arg0) {
checkDocsForText();
}
}
private static void createAndShowGui() {
Foo2 foo = new Foo2();
int result = foo.showDialog();
if (result >= 0) {
System.out.println(DIALOG_BUTTON_TITLES[result]);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I suggest you to define some properties into your JPanel extended class, and use PropertyChangeListener to listen the occured changes and enable/disable relative buttons.
Here's an article.
Another issue maybe finding the ok/cancel buttons in the hierarchy of components, since the JDialog is created through JOptionPane and you haven't a reference to the buttons. Here's a useful thread .
You can add a property to a JComponent using putClientProperty method.
When changes occurs to a given property a PropertyChanged event is raised.
So in your example you can define a boolean property indicating that required that are inserted into the JDialog. Then add a PropertyChangeListener that when is notified enable/disable the ok button.

JDialog repaint after JList modification

I have a JDialog dlg, created by a JFrame frm, that contains a JList list.
When I modify the list (through the ListModel), the list itself is repainted but not the JDialog.
This means that, if I delete a line, the list remains with an empty line while if I add a line, this new line won't be shown (because there is no space in the dialog) until I manually force repainting of dlg (doubleclicking in frm).
Following advices in this post :
How to make repaint for JDialog in Swing?
and in this post:
Force repaint after button click
I tried to call, from my controller class (which is where updates to list are made), the following line:
SwingUtilities.getWindowAncestor(dlg).repaint();
but it didn't work.
I also tried:
dlg.repaint();
No luck either...
Any clue?
Thank you very much.
EDIT:
The organization of my classes is as follows:
a controller class that contains a reference to the main JFrame, frm.
I also extended JDialog into MyDialog, which contains a JList.
When a doubleclick on frm is detected, I show the instance of MyDialog (or create, if it is the first time I show it) and the JList is filled with the data passed to the DefaultListModel. MyDialog is painted so that the list has only the space that it needs.
Now, when a specific event is detected by the controller, I get the specific MyDialog, get the ListModel from JList and update it. Here the JList is indeed updated, but Dialog remains the same.
I use a code like this:
MyDialog dlg = group.getDlg();
if(dlg != null){
DefaultListModel listModel = ((DefaultListModel) dlg.getMyJList().getModel());
listModel.addElement(idStock);
SwingUtilities.getWindowAncestor(dlg).repaint();
}
This doesn't repaint dlg.
I also tried:
SwingUtilities.getWindowAncestor(dlg.getMyJList()).repaint();
but it doesn't work.
I checked with the debugger that the lines are actually executed.
I don't have much more code to show, really.....
I think that you going wrong way, define DefaultListModel that accesible throught all Java methods and Classes, this Model would holds your Objects, then put JList to the JDialog or JOptionPane, for example
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
// based on #trashgod code
/** #see http://stackoverflow.com/questions/5759131 */
// http://stackoverflow.com/questions/8667719/jdialog-repaint-after-jlist-modification
public class ListDialog {
private static final int N = 12;
private JDialog dlg = new JDialog();
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JScrollPane sp = new JScrollPane(list);
private int count;
public ListDialog() {
list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("Add") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
append();
if (count <= N) {
list.setVisibleRowCount(count);
dlg.pack();
}
}
}));
panel.add(new JButton(new AbstractAction("Remove") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
int itemNo = list.getSelectedIndex();
if (itemNo > -1) {
removeActionPerformed(e, itemNo);
}
}
}));
for (int i = 0; i < N - 2; i++) {
this.append();
}
list.setVisibleRowCount(N - 2);
dlg.add(sp, BorderLayout.CENTER);
dlg.add(panel, BorderLayout.SOUTH);
dlg.pack();
dlg.setLocationRelativeTo(null);
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.setVisible(true);
}
private void removeActionPerformed(ActionEvent e, int itemNo) {
System.out.println("made_list's model: " + list.getModel());
System.out.println("Model from a fresh JList: " + new JList().getModel());
model = (DefaultListModel) list.getModel();
if (model.size() > 0) {
if (itemNo > -1) {
model.remove(itemNo);
}
}
}
private void append() {
model.addElement("String " + String.valueOf(++count));
list.ensureIndexIsVisible(count - 1);
}
public static void main(String[] a_args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ListDialog pd = new ListDialog();
}
});
}
}

Categories

Resources