JFrame quase modal

0 respostas
M

Usando o fundamento "Java sempre passa por valor". Consegui um JFrame quase modal sem usar o JDialog.

JFrame normal
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class JFrameNormal {
	private JFrame jf;

	public JFrameNormal() {
		JButton jb = new JButton("abrir um JFrame quase modal");

		jf = new JFrame("JFrame normal");
		jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		jf.setSize(400, 400);
		jf.setLocationRelativeTo(null);
		jf.add(jb);
		jf.setVisible(true);

		jb.addActionListener(new AbreModalFrame());
	}

	public void setModal() {
		jf.setEnabled(!jf.isEnabled());
	}

	private JFrameNormal getThis() {
		return this;
	}

	private class AbreModalFrame implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			setModal();
			new JFrameQuaseModal(getThis());
		}
	}
}
JFrame quase modal
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class JFrameQuaseModal {
	private JFrame jf;
	private JFrameNormal jfn;

	public JFrameQuaseModal(JFrameNormal jfn) {
		this.jfn = jfn;
		JButton jb = new JButton("Fechar");

		jf = new JFrame("JFrame quase modal");
		jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		jf.setResizable(false);
		jf.setSize(300, 300);
		jf.setAlwaysOnTop(true);
		jf.setLocationRelativeTo(null);
		jf.add(jb);
		jf.setVisible(true);

		jb.addActionListener(new Fecha());
	}

	private class Fecha implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			jfn.setModal();
			jf.dispose();
		}
	}

}
Teste
public class TesteFramequaseModal {

	public static void main(String[] args) {
		JFrameNormal p = new JFrameNormal();
	}
}
Tente usar o JFrame.setVisible(), no lugar do JFrame.setEnabled()
Criado 11 de novembro de 2011
Respostas 0
Participantes 1