I've created a simple terminal app using lanterna that simply displays a custom button. But even though in the custom button's class I extend the Button class and override the Button class' createDefaultRenderer method to return an instance of the Button class' FlatButtonRenderer class, it is displaying the button using the DefaultButtonRenderer class.
Can you help me understand how to create a custom button in lanterna that displays the button using the FlatButtonRenderer?
import java.io.IOException;
import java.util.ArrayList;
import com.googlecode.lanterna.terminal.*;
import com.googlecode.lanterna.screen.*;
import com.googlecode.lanterna.gui2.*;
class Test {
public static void main(String[] args) {
DefaultTerminalFactory terminalFactory = new DefaultTerminalFactory();
Screen screen = null;
try {
screen = terminalFactory.createScreen();
screen.startScreen();
final WindowBasedTextGUI textGUI = new MultiWindowTextGUI(screen);
final Window window = new GUIAppWindow();
textGUI.addWindowAndWait(window);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if(screen != null) {
try {
screen.stopScreen();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
}
private static class GUIAppWindow extends BasicWindow {
GUIAppWindow() {
ArrayList<Window.Hint> hints = new ArrayList<>();
hints.add(Window.Hint.CENTERED);
setHints(hints);
Panel mainPanel = new Panel(new LinearLayout(Direction.VERTICAL));
XButton b = new XButton(new String("."));
b.addListener(new ButtonHandler("data"));
mainPanel.addComponent(b);
this.setComponent(mainPanel);
}
private class XButton extends Button {
public XButton(String label) {
super(label);
}
#Override
protected ButtonRenderer createDefaultRenderer() {
return new Button.FlatButtonRenderer();
}
}
private class ButtonHandler implements Button.Listener {
final String loc;
ButtonHandler(String loc) {
this.loc = loc;
}
public void onTriggered(Button button) {
button.setLabel(button.getLabel().equals(".") ? "x" : new String("."));
}
}
}
}
I believe the correct way to use FlatButtonRenderer is to call setRenderer().
private class XButton extends Button {
public XButton(String label) {
super(label);
setRenderer(new Button.FlatButtonRenderer());
}
}
Im trying to understand why this program does not work. Am i using the actionlistener properly why does it not show the time elapsed from when the thread is running but the thread is not running and i see nothing on the screen.
what am i doing wrong or this is the wrong way of using the ActionListener class
or am i not using it properly, here is the code for all the files.
import java.awt.event.*;
import java.util.TooManyListenersException;
public class Timer extends Thread {
private int iTime = 0;
private ActionListener itsListener = null;
public Timer() {
super(); // allocates a new thread object
iTime = 0; // on creation of this object set the time to zero
itsListener = null; // on creation of this object set the actionlistener
// object to null reference
}
public synchronized void resetTime() {
iTime = 0;
}
public void addActionListener(ActionListener event) throws TooManyListenersException {
if (event == null)
itsListener = event;
else
throw new TooManyListenersException();
}
public void removeActionListener(ActionListener event) {
if (itsListener == event)
itsListener = null;
}
public void run() {
while (true) {
try {
this.sleep(100);
}
catch (InterruptedException exception) {
// do nothing
}
iTime++;
if (itsListener != null) {
String timeString = new String(new Integer(iTime).toString());
ActionEvent theEvent = new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, timeString);
itsListener.actionPerformed(theEvent);
}
}
}
}
next file
import java.awt.event.*;
import java.util.TooManyListenersException;
public class TextTimeDemonStration extends Object implements ActionListener {
private Timer aTimer = null; // null reference for this object
public TextTimeDemonStration() {
super();
aTimer = new Timer();
try {
aTimer.addActionListener(this);
}
catch (TooManyListenersException exception) {
// do nothing
}
aTimer.start();
}
public void actionPerformed(ActionEvent e) {
String theCommand = e.getActionCommand();
int timeElapsed = Integer.parseInt(theCommand, 10);
if (timeElapsed < 10) {
System.out.println(timeElapsed);
}
else
System.exit(0);
}
}
the last file the main class running the program from
public class MainTest {
public static void main(String[] args) {
TextTimeDemonStration test = new TextTimeDemonStration();
}
}
In TextTimeDemonStration class, you called aTimer.addActionListener(this); to assign an action listener
But in your Timer.addActionListener() method, in the if else block, you wrote
if (event == null)
itsListener = event;
else
throw new TooManyListenersException();
Since this is not null, it will throw TooManyListenersException exception which will be caught.
After which you start the timer. But, since itsListener is null after the initialisation, in your Timer.run() method, the if block will never be executed. Therefore, nothing is done.
Fix up the logic at Timer.addActionListener() method and it should work just fine.
Hope this helps.
Normal JCheckbox react directly on user input and sets or unsets the tick. After this the MouseListener is called. What I want to achieve is that the state of the JCheckbox can only be changed by the controller. What are decent way to achieve this?
I tried to add a mouse listener which immediatly add/removes the tick again but this results in flickering.
The only way I found was to overwrite the processMouseEvent method but this is really bad...
EDIT (my current version):
This does now work now. Missed to adjust the model before.
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.EventListener;
import javax.swing.JCheckBox;
public class MyJCheckBox extends JCheckBox {
public MyJCheckBox() {
MouseListener[] ml = (MouseListener[]) this.getListeners(MouseListener.class);
for (int i = 0; i < ml.length; i++) {
this.removeMouseListener(ml[i]);
this.addMouseListener(new MouseListenerWrapper(ml[i]));
}
}
public void addClickListener(ClickListener listener) {
listenerList.add(ClickListener.class, listener);
}
private class MouseListenerWrapper implements MouseListener {
MouseListener listener;
public MouseListenerWrapper(MouseListener listener) {
this.listener = listener;
}
#Override
public void mouseClicked(MouseEvent e) {
listener.mouseClicked(e);
}
#Override
public void mousePressed(MouseEvent e) {
listener.mousePressed(e);
}
#Override
public void mouseReleased(MouseEvent e) {
for(ClickListener listener : listenerList.getListeners(ClickListener.class)) {
listener.onClick();
//Adjust model
MyJCheckBox.this.getModel().setArmed(false);
MyJCheckBox.this.getModel().setPressed(false);
}
}
#Override
public void mouseEntered(MouseEvent e) {
listener.mouseEntered(e);
}
#Override
public void mouseExited(MouseEvent e) {
listener.mouseExited(e);
}
}
}
interface ClickListener extends EventListener {
public void onClick();
}
I don't like it when people play with the UI. This will confuse the user and they will think the application is broken if they can't click on the check box.
Anyway, remove the MouseListener from the check box.
MouseListener[] ml = (MouseListener[])checkBox.getListeners(MouseListener.class);
for (int i = 0; i < ml.length; i++)
checkBox.removeMouseListener( ml[i] );
There is another way to implement the behaviour I would like to have if you overwrite the paint method and change the model according to your needs before you paint it.
import java.awt.Graphics;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
public class MyJCheckBox extends JCheckBox {
private boolean change = false;
private boolean previousState = false;
#Override
public void setSelected(boolean selected) {
if(this.isSelected() != selected) {
change = true;
}
super.setSelected(selected);
}
#Override
public void paint(Graphics g) {
AbstractButton b = this;
ButtonModel model = b.getModel();
boolean changeRequest = false;
//adjust model state to our needs. A state change
//is only possible if it was requested by
//setSelected()
if(previousState != model.isSelected()) {
//Revert change if it was not requested by
//by setSelected()
if(! change) {
changeRequest = true;
model.setSelected(previousState);
}
//Reset change to false so it can only be changed once
//To change it again you have to call setSelected() again.
change = false;
}
//Set current state as previous state
previousState = model.isSelected();
//paint with adjusted model
super.paint(g);
//Inform listener that a change was requested
if(changeRequest) {
for(ClickListener listener : listenerList.getListeners(ClickListener.class)) {
listener.onClick();
}
}
}
}
interface ClickListener extends EventListener {
public void onClick();
}
How should I detect that column moved action is finished in JTable? I've added columnModeListener to my column model but the problem is columnMoved method is called every time a column moves (by certain pixels). I don't want this behavior. I just want to detect when the column dragging is finished.
columnModel.addColumnModelListener(new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
}
public void columnRemoved(TableColumnModelEvent e) {
}
public void columnMoved(TableColumnModelEvent e) {
//this is called so many times
//I don't want this, but something like column moved finished event
System.out.println("Moved "+e.getFromIndex()+", "+e.getToIndex());
}
public void columnMarginChanged(ChangeEvent e) {
}
public void columnSelectionChanged(ListSelectionEvent e) {
}
});
I hope it is clear what I'm looking for. Thanks.
This is what I ended up doing. I know it is dirty, but it fits for what I'm looking:
boolean dragComplete = false;
apTable.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
if (dragComplete) {
System.out.println("Drag completed");
}
dragComplete = false;
}
});
columnModel.addColumnModelListener(new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
}
public void columnRemoved(TableColumnModelEvent e) {
}
public void columnMoved(TableColumnModelEvent e) {
dragComplete = true;
}
public void columnMarginChanged(ChangeEvent e) {
}
public void columnSelectionChanged(ListSelectionEvent e) {
}
});
Here's an inner class I use to determine when the column ordering has changed. Note that the user may not have let go of the mouse at this point, so the dragging may continue further.
private class ColumnUpdateListener implements TableColumnModelListener {
int lastFrom = 0;
int lastTo = 0;
private void verifyChange(int from, int to) {
if (from != lastFrom || to != lastTo) {
lastFrom = from;
lastTo = to;
///////////////////////////////////////
// Column order has changed! Do something here
///////////////////////////////////////
}
}
public void columnMoved(TableColumnModelEvent e) {
verifyChange(e.getFromIndex(), e.getToIndex());
}
public void columnAdded(TableColumnModelEvent e) {
verifyChange(e.getFromIndex(), e.getToIndex());
}
public void columnRemoved(TableColumnModelEvent e) {
verifyChange(e.getFromIndex(), e.getToIndex());
}
public void columnMarginChanged(ChangeEvent e) {}
public void columnSelectionChanged(ListSelectionEvent e) {}
}
It's worked well for me.
This might be a better approach:
table.setTableHeader(new JTableHeader(table.getColumnModel()) {
#Override
public void setDraggedColumn(TableColumn column) {
boolean finished = draggedColumn != null && column == null;
super.setDraggedColumn(column);
if (finished) {
onColumnChange(table); // Handle the event here...
}
}
});
This is what works for me (both column movements and margin resizes):
I extend the table and override the columnMoved and columnMarginChanged
methods in the following way:
... first add some variables for state keeping
private int lastMovementDistance = 0;
private boolean bigMove = false;
private boolean resizeBegan = false;
...
#Override
public void columnMarginChanged(ChangeEvent e) {
super.columnMarginChanged(e);
if (isShowing()){
resizeBegan = true;
}
}
#Override
public void columnMoved(TableColumnModelEvent e) {
super.columnMoved(e);
//this will be set to 0 when the column is dragged
//to where it should begin if released
lastMovementDistance = Math.abs(getTableHeader().getDraggedDistance());
if (e.getFromIndex() != e.getToIndex()){
//note, this does not guarantee that the columns will be eventually
//swapped - the user may move the column back.
//but it prevents us from reacting to movements where
//the user hasn't even moved the column further then its nearby region.
//Works for me, because I don't care if the columns stay the same
//I only need the updates to be infrequent and don't want to miss
//changes to the column order
bigMove = true;
}
}
... then in the constructor of my table i do this:
public MyTable(){
...
getTableHeader().addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent evt) {
if (bigMove && lastMovementDistance == 0 ){
//react! the tables have possibly switched!
}
else if (resizeBegan){
//react! columns resized
}
resizeBegan = false;
bigMove = false;
}
});
...
}
It is kinda like a hack, but it works for me.
Nice answer on your own question ashokgelal. Just a little improvement I think. Your code also trigger on single click on the header. Using one more flag you can prevent the 'dragComplete' trigger when the column haven't really changed.
Modified code:
boolean mDraggingColumn = false;
boolean mColumnCHangedIndex = false;
tblObjects.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
if (mDraggingColumn && mColumnCHangedIndex) {
System.out.println("Column changed");
}
mDraggingColumn = false;
mColumnCHangedIndex = false;
}
});
tblObjects.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
#Override
public void columnAdded(TableColumnModelEvent e) {}
#Override
public void columnRemoved(TableColumnModelEvent e) {}
#Override
public void columnMoved(TableColumnModelEvent e) {
mDraggingColumn = true;
if (e.getFromIndex() != e.getToIndex()) {
mColumnCHangedIndex = true;
}
}
#Override
public void columnMarginChanged(ChangeEvent e) {}
#Override
public void columnSelectionChanged(ListSelectionEvent e) {}
});
If I understand you correctly, maybe you want to look at the mouse listeners. Maybe the MOUSE_RELEASED event?
All answers fail at one use-case: if the table is in a layout filling up the entire window, then resizing the window will resize the table and thus its columns. By watching for mouse events on the column headers, we fail to receive the event when the user resize the window.
I looked at the JTable&friends source-code, and the columnMarginChanged() method is always called in a sub-sub-sub...-function called by JTable.doLayout().
Then, my solution is to watch for doLayout() calls that trigger at least one columnMarginChanged().
In fact, columnMarginChanged() is called for every columns.
Here is my solution:
private class ResizableJTable extends JTable {
private TableColumnModelListener columnModelListener;
private boolean columnsWereResized;
#Override
public void setColumnModel(TableColumnModel columnModel) {
if (getColumnModel() != null) {
getColumnModel().removeColumnModelListener(columnModelListener);
columnModelListener = null;
}
if (columnModel != null) {
columnModelListener = new TableColumnModelListener() {
public void columnSelectionChanged(ListSelectionEvent e) {
// Nothing to do
}
public void columnRemoved(TableColumnModelEvent e) {
// Nothing to do
}
public void columnMoved(TableColumnModelEvent e) {
// Nothing to do
}
public void columnMarginChanged(ChangeEvent e) {
columnsWereResized = true;
}
public void columnAdded(TableColumnModelEvent e) {
// Nothing to do
}
};
columnModel.addColumnModelListener(columnModelListener);
}
super.setColumnModel(columnModel);
}
#Override
public void doLayout() {
columnsWereResized = false;
super.doLayout();
if (columnsWereResized) {
onColumnsResized();
}
}
/**
* Sub-classes can override this method to
* get the columns-were-resized event.
* By default this method must be empty,
* but here we added debug code.
*/
protected void onColumnsResized() {
int[] columnSizes = getColumnSizes();
String sizes = "";
for (int i : columnSizes) {
sizes += i + " ";
}
System.out.println("COLUMNS RESIZED: [ " + sizes + "]");
}
protected int[] getColumnSizes() {
TableColumnModel columnModel = getTableHeader().getColumnModel();
int columnCount = columnModel.getColumnCount();
int[] columnSizes = new int[columnCount];
for(int i = 0; i < columnCount; i++) {
TableColumn column = columnModel.getColumn(i);
columnSizes[i] = column.getWidth();
}
return columnSizes;
}
}
I followed approach 2 of this guide, so now I have a ModalInternalFrame that blocks input to all other frames, just as I wanted. However, I made one change from the example, and now I have two problems.
The Change
I removed the JOptionPane, because the whole point is to show my own pane. In order to make it close, I set closeable to true, and added an InternalFrameListener with the same code as the example's listener for the JOptionPane. That doesn't work, so I also added code at the end of doDefaultCloseAction.
The Problems
The ModalInternal frame never goes away. I think some exception is being thrown but...
I can't see any thrown exceptions, and I don't know where they're going. Usually when in debug mode, Eclipse will stop right before the exception is given to the UncaughtExceptionHandler, but that isn't happening in this case.
The Code
If my description of the problem doesn't help, here's my version of the ModalInternalFrame. If you want more code, I can post that as well. Sorry it's so long, but I tried to make it as concise as possible.
public class ModalInternalFrame extends JInternalFrame {
public ModalInternalFrame(String title, JRootPane rootPane,
Component desktop) {
super(title, false, true, false, false);
// create opaque glass pane
final JPanel glass = new JPanel();
glass.setOpaque(false);
// Attach mouse listeners
MouseInputAdapter adapter = new MouseInputAdapter() { };
glass.addMouseListener(adapter);
glass.addMouseMotionListener(adapter);
this.addInternalFrameListener(new InternalFrameListenerAdapter() {
public void internalFrameClosed(InternalFrameEvent e) { close(); }
public void internalFrameClosing(InternalFrameEvent e){ close(); }
});
// Change frame border
putClientProperty("JInternalFrame.frameType", "optionDialog");
// Size frame
Dimension size = getPreferredSize();
Dimension rootSize = desktop.getSize();
setBounds((rootSize.width - size.width) / 2,
(rootSize.height - size.height) / 2, size.width, size.height);
desktop.validate();
try { setSelected(true); }
catch (PropertyVetoException ignored) { }
glass.add(this); // Add modal internal frame to glass pane
rootPane.setGlassPane(glass); // Change glass pane to our panel
glass.setVisible(true); // Show glass pane, then modal dialog
}
private void close(){
if (isVisible()) {
try { setClosed(true); }
catch (PropertyVetoException ignored) { }
setVisible(false);
rootPane.getGlassPane().setVisible(false);
}
}
#Override public void doDefaultCloseAction() {
super.doDefaultCloseAction();
close();
}
#Override public void setVisible(boolean flag) {
super.setVisible(flag);
if (flag) startModal();
else stopModal();
}
private synchronized void startModal() {
try {
if (SwingUtilities.isEventDispatchThread()) {
EventQueue theQueue = getToolkit().getSystemEventQueue();
while (isVisible()) {
AWTEvent event = theQueue.getNextEvent();
Object source = event.getSource();
if (event instanceof ActiveEvent) {
((ActiveEvent) event).dispatch();
} else if (source instanceof Component) {
((Component) source).dispatchEvent(event);
} else if (source instanceof MenuComponent) {
((MenuComponent) source).dispatchEvent(event);
} else {
System.err.println("Unable to dispatch: " + event);
}
}
} else { while (isVisible()) { wait(); } }
} catch (InterruptedException ignored) {
}
}
private synchronized void stopModal() { notifyAll(); }
}
Update: I've discovered that modal dialog boxes suit my needs fine, but if anyone does have an idea, I'd be glad to hear it. One thing I haven't tried is wrapping every method in a try {} catch (Exception e){} which would probably help a lot.
I can't quite get your code to run, but here's a simpler version, based on the Sun example, that does work -- the main frame has a button in it (taking up all the available space), but clicking the button is blocked until the internal frame has been closed.
You can see, pretty much all I did was replace the new JOptionPane().createInternalFrame() business with my own frame. My guess is that you're overcomplicating things when you try to do your own event dispatching.
Or am I missing something?
public class Foo {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLocationByPlatform(true);
JButton desktop = new JButton(new AbstractAction("Click me if you can") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("I have been clicked");
}
});
frame.getContentPane().add(desktop);
frame.setVisible(true);
JInternalFrame modal =
new JInternalFrame("Modal Popup", false, true, false, false);
JLabel popupContent = new JLabel("I am the popup");
popupContent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
modal.add(popupContent);
modal.pack();
JPanel glass = new JPanel();
glass.setOpaque(false);
glass.add(modal);
frame.setGlassPane(glass);
glass.setVisible(true);
modal.setVisible(true);
modal.addInternalFrameListener(new ModalAdapter(glass));
}
}
class ModalAdapter extends InternalFrameAdapter {
Component glass;
public ModalAdapter(Component glass) {
this.glass = glass;
// Associate dummy mouse listeners
// Otherwise mouse events pass through
MouseInputAdapter adapter = new MouseInputAdapter() {
};
glass.addMouseListener(adapter);
glass.addMouseMotionListener(adapter);
}
public void internalFrameClosed(InternalFrameEvent e) {
glass.setVisible(false);
}
}
Try this. I got it from the Webby IT blog post on JInternal Frames: http://webbyit.blogspot.com/2011/03/managing-jinternalframes-within.html
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
/**
* An extended <code>JInternalFrame</code> that provides modality in a child/parent hierarchy.
* source: webby it internal frames blog post
*
* #author webbyit
*/
public class ModalityInternalFrame extends JInternalFrame {
protected JDesktopPane desktopPane;
protected JComponent parent;
protected ModalityInternalFrame childFrame;
protected JComponent focusOwner;
private boolean wasCloseable;
public ModalityInternalFrame() {
init(); // here to allow netbeans to use class in gui builder
}
public ModalityInternalFrame(JComponent parent) {
this(parent, null);
}
public ModalityInternalFrame(JComponent parent, String title) {
this(parent, title, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable) {
this(parent, title, resizable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable) {
this(parent, title, resizable, closeable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable,
boolean maximizable) {
this(parent, title, resizable, closeable, maximizable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable,
boolean maximizable,
boolean iconifiable) {
super(title, resizable, closeable, maximizable, iconifiable);
setParentFrame(parent);
//setFocusTraversalKeysEnabled(false);
if (parent != null && parent instanceof ModalityInternalFrame) {
((ModalityInternalFrame) parent).setChildFrame(ModalityInternalFrame.this);
/*
* set focus to the new frame and show the frame Code added by Jasir
*/
try {
((ModalityInternalFrame) parent).setSelected(false);
setSelected(true);
setVisible(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(ModalityInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Add glass pane
ModalityInternalGlassPane glassPane = new ModalityInternalGlassPane(this);
setGlassPane(glassPane);
// Add frame listeners
addFrameListener();
// Add frame veto listenr
addFrameVetoListener();
init();
// calculate size and position
}
private void setParentFrame(JComponent parent) {
desktopPane = JOptionPane.getDesktopPaneForComponent(parent);
this.parent = parent == null ? JOptionPane.getDesktopPaneForComponent(parent) : parent; // default to desktop if no parent given
}
public JComponent getParentFrame() {
return parent;
}
public void setChildFrame(ModalityInternalFrame childFrame) {
this.childFrame = childFrame;
}
public ModalityInternalFrame getChildFrame() {
return childFrame;
}
public boolean hasChildFrame() {
return (childFrame != null);
}
protected void addFrameVetoListener() {
addVetoableChangeListener(new VetoableChangeListener() {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (evt.getPropertyName().equals(JInternalFrame.IS_SELECTED_PROPERTY)
&& evt.getNewValue().equals(Boolean.TRUE)) {
if (hasChildFrame()) {
//childFrame.setSelected(true);
if (childFrame.isIcon()) {
childFrame.setIcon(false);
}
throw new PropertyVetoException("no!", evt);
}
}
}
});
}
/**
* Method to control the display of the glass pane, dependant on the frame
* being active or not
*/
protected synchronized void addFrameListener() {
addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameActivated(InternalFrameEvent e) {
if (hasChildFrame() == true) {
getGlassPane().setVisible(true);
grabFocus();
} else {
getGlassPane().setVisible(false);
}
}
#Override
public void internalFrameOpened(InternalFrameEvent e) {
getGlassPane().setVisible(false);
try {
setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(ModalityInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
if (parent != null && parent instanceof ModalityInternalFrame) {
((ModalityInternalFrame) parent).childClosing();
}
}
});
}
/**
* Method to handle child frame closing and make this frame available for
* user input again with no glass pane visible
*/
protected void childClosing() {
setClosable(wasCloseable);
getGlassPane().setVisible(false);
if (focusOwner != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
moveToFront();
setSelected(true);
focusOwner.grabFocus();
} catch (PropertyVetoException ex) {
}
}
});
focusOwner.grabFocus();
}
getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
setChildFrame(null);
getDesktopPane().setSelectedFrame(this);
System.out.println(getDesktopPane().getSelectedFrame());
}
/*
* Method to handle child opening and becoming visible.
*/
protected void childOpening() {
// record the present focused component
wasCloseable = isClosable();
setClosable(false);
focusOwner = (JComponent) getMostRecentFocusOwner();
grabFocus();
getGlassPane().setVisible(true);
getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
#Override
public void show() {
if (parent != null && parent instanceof ModalityInternalFrame) {
// Need to inform parent its about to lose its focus due
// to child opening
((ModalityInternalFrame) parent).childOpening();
}
calculateBounds();
super.show();
}
protected void init() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 394, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 274, Short.MAX_VALUE));
pack();
}
public void calculateBounds() {
Dimension frameSize = getPreferredSize();
Dimension parentSize = new Dimension();
Dimension rootSize = new Dimension(); // size of desktop
Point frameCoord = new Point();
if (desktopPane != null) {
rootSize = desktopPane.getSize(); // size of desktop
frameCoord = SwingUtilities.convertPoint(parent, 0, 0, desktopPane);
parentSize = parent.getSize();
}
//setBounds((rootSize.width - frameSize.width) / 2, (rootSize.height - frameSize.height) / 2, frameSize.width, frameSize.height);
// We want dialog centered relative to its parent component
int x = (parentSize.width - frameSize.width) / 2 + frameCoord.x;
int y = (parentSize.height - frameSize.height) / 2 + frameCoord.y;
// If possible, dialog should be fully visible
int ovrx = x + frameSize.width - rootSize.width;
int ovry = y + frameSize.height - rootSize.height;
x = Math.max((ovrx > 0 ? x - ovrx : x), 0);
y = Math.max((ovry > 0 ? y - ovry : y), 0);
setBounds(x, y, frameSize.width, frameSize.height);
}
/**
* Glass pane to overlay. Listens for mouse clicks and sets selected on
* associated modal frame. Also if modal frame has no children make class
* pane invisible
*/
class ModalityInternalGlassPane extends JComponent {
private ModalityInternalFrame modalFrame;
public ModalityInternalGlassPane(ModalityInternalFrame frame) {
modalFrame = frame;
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (modalFrame.isSelected() == false) {
try {
modalFrame.setSelected(true);
if (modalFrame.hasChildFrame() == false) {
setVisible(false);
}
} catch (PropertyVetoException e1) {
//e1.printStackTrace();
}
}
}
});
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(new Color(255, 255, 255, 100));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
I just had to do this thing for a project. All I did was passed the main window object to Jinternalframe. The main object has a semaphore that tracks whether modal is locked or not. Upon closing the Jinternalframe (extension) calls the main object's semaphore. Very simple.
This is not the main code but you get the idea :
//called frame
public CallingFrame parent;
public void setParent(CallingFrame parent_){
this.parent=parent_;
}
private void frameClosed(javax.swing.event.InternalFrameEvent evt) {
parent.modalLocked=false;
}
In my case the application uses a label with image-parts to call internalframes, so the code starts with
//calling frame
CalledFrame cf=new CalledFrame();
cf.setParent(this);
cf.setVisible(true);
modalLoacked=true;
private void jLabel1MouseReleased(java.awt.event.MouseEvent evt) {
if (modalLocked)
return;
else// (do your things)
}
I followed the tutorials but most of them are overcomplicating things when a single semaphore will do the tricks of not letting you click on any area while one Called Frame is not closed.
public void internalFrameClosing(InternalFrameEvent e){ close(); }
calling close() will cause internalFrameClosing() to be called again, until the stack overflows.
Try removing that listener altogether.
You can just add setClosable(true); in the constructor