I have a main application frame (MainFrame class). On actionperformed event of a JButton, a JPanel (MyJPanel class) is opened by placing it in JDialog. I am not extending JDialog to create MyJPanel class because I might need MyJPanel at other purposes too.
My Problem is I cannot programmatically close the MyJPanel which is displayed in JDialog. Is there anything that I missing? Could you please figure it out?
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class MainFrame extends JPanel {
public MainFrame() {
JButton btnOpenJdialog = new JButton("Open JDialog");
add(btnOpenJdialog);
btnOpenJdialog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog jd = new JDialog();
MyJPanel mjp = new MyJPanel(true);//showing in JDialog
jd.setTitle("JDialog");
jd.add(mjp);
jd.pack();
jd.setVisible(true);
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Test-JFrame");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainFrame());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
MyJPanel Class :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JButton;
public class MyJPanel extends JPanel {
private boolean isShownInJDialog = false;
public MyJPanel() {
JButton btnCloseMe = new JButton("Finish Action");
add(btnCloseMe);
btnCloseMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShownInJDialog) {
MyJPanel.this.setVisible(false);
//how to close the JDialog too.
}
else {
//just hide the content,
MyJPanel.this.setVisible(false);
}
}
});
}
public MyJPanel(boolean isShownInJDialog) {
this();
this.isShownInJDialog = isShownInJDialog;
}
}
UPDATE
I was able to solve this using Howard's answer as :
...
if (isShownInJDialog) {
Window w = SwingUtilities.getWindowAncestor(MyJPanel.this);
w.setVisible(false);
}
...
If I understand your question correctly, you want to close the JDialog which your MyJPanel is contained in but do not have a reference to it?
You may either provide such a reference using the constructor of MyJPanel or change the code inside your ActionListener to
Window w = SwingUtilities.getWindowAncestor(MyJPanel.this);
w.setVisible(false);
which looks up the parent window of your panel without direct reference.
Related
I didn't really know how else to phrase that but essentially:
-I have a few separate "pieces" that I am trying to add onto a master frame; to keep the code from getting unwieldy I have each "piece" be its own class.
-I'm getting stuck on adding the panells onto the master frame, because the classes themselves aren't panels, rather the method of the class creates the panel, which creates issues that I don't know how to solve.
PIECE (works on its own when I have it make a dialog instead of be a panel):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PieceThing3 extends JPanel //<switched from JDialog
{
//set up variables here
private ActionListener pieceAction = new ActionListener()
{
public void actionPerformed (ActionEvent ae)
{
// Action Listener (this also works)
}
};
private void createPiece()
{
//setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//setLocationByPlatform(true);
// the above are commented out when I switch from dialog to panel
JPanel contentPane = new JPanel();
//something that uses pieceAction is here
//two buttons, b and s, with action listeners are here
contentPane.add(b);
contentPane.add(s);
add(contentPane);
//pack();
//again, commented out to switch from dialog
setVisible(true);
System.out.println("hi I'm done");
//just to check and make sure it's done
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PieceThing3().createPiece();
}
});
}
}
Sorry that is very vague, but the intricacies are not as important as the general idea - it works perfectly when I have it create its own dialog box, but now I am trying to get it to make a panel within a master code, below:
MASTER:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CollectGUI extends JFrame{
private void createDialog(){
this.setSize(2000,1000);
this.setLocation(0,0);
this.setTitle("TITLE");
PieceThing3 pt = new PieceThing3();
//HERE, if I do pt.main(null); while it is in "dialog mode" (rather than panel) it pops up a dialog box and everything is hunky dory. But I don't know how to get it to add the method as a panel.
this.add(pt.main(null));
//this gives an error
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new CollectGUI().createDialog();
}
}
As I said in the comments, if I just do pt.main(null) when pt is set to make a dialog, it does it, but if I try to add pt.main(null) as a panel it throws an error. Can anybody give me some insight on how to add a method of a class rather than a class? I'm pretty stumped.
THANK YOU!!
You are definitely on the right track working to maintain separation of concerns and implement your gui in a number of distinct components. Try something like this:
Panel1
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel1 extends JPanel {
public Panel1() {
this.add(new JLabel("This is panel 1"));
}
}
Panel2
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel2 extends JPanel {
public Panel2() {
this.add(new JLabel("This is panel 2"));
}
}
JFrame
import java.awt.BorderLayout;
import javax.swing.JFrame;
import org.yaorma.example.jframe.panel.panel1.Panel1;
import org.yaorma.example.jframe.panel.panel2.Panel2;
public class ExampleJFrame extends JFrame {
public ExampleJFrame() {
super("Example JFrame Application");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setLayout(new BorderLayout());
Panel1 pan1 = new Panel1();
Panel2 pan2 = new Panel2();
this.add(pan1, BorderLayout.NORTH);
this.add(pan2, BorderLayout.SOUTH);
this.setVisible(true);
}
}
main:
public class ExampleApplication {
public static void main(String[] args) throws Exception {
new ExampleJFrame();
}
}
EDIT:
Here's a Panel1 with a little more content.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.yaorma.example.action.sayhello.SayHelloAction;
public class Panel1 extends JPanel {
//
// instance variables
//
private JButton pressMeButton;
//
// constructor
//
public Panel1() {
this.setLayout(new BorderLayout());
this.add(new JLabel("This is panel 1"), BorderLayout.NORTH);
this.initPressMeButton();
}
//
// button
//
private void initPressMeButton() {
this.pressMeButton = new JButton("Press Me");
this.pressMeButton.addActionListener(new PressMeButtonActionListener());
this.add(pressMeButton, BorderLayout.SOUTH);
}
//
// method to get the parent jframe
//
private JFrame getParentJFrame() {
Container con = this;
while(con != null) {
con = con.getParent();
if(con instanceof JFrame) {
return (JFrame)con;
}
}
return null;
}
//
// action listener for Press Me button
//
private class PressMeButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFrame jFrame = getParentJFrame();
SayHelloAction action = new SayHelloAction(jFrame);
action.execute();
}
}
}
Action called by button:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SayHelloAction {
private JFrame owner;
public SayHelloAction(JFrame owner) {
this.owner = owner;
}
public void execute() {
JOptionPane.showMessageDialog(owner, "Hello World");
}
}
I wanted to create a fairly simple GUI program that switches between panels depending on buttons the user clicked. I searched around and came up with CardLayout being the best suggestion.
Basically in the examples of CardLayout, you create a "card" (a JPanel) and then add each component, like buttons, etc... and switch between the cards.
What I want to create is an object that is a "card" with all the components set up already, in a separate class, and just create an instance of that in the main program. I am a beginner and do not know the best design practices, so I didn't want to create my own class that extended JPanel, which I am pretty sure is terrible design.
You do it just like you would if you had create an instance of JPanel and add the components directly to it.
You need to ensure that the custom class extends from something JComponent or JPanel (preferably) and add them to the container like any other component, for example...
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestCard {
public static void main(String[] args) {
new TestCard();
}
public TestCard() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final CardLayout cardLayout = new CardLayout();
final JPanel cardPane = new JPanel(cardLayout);
cardPane.add(new Card01(), "Card01");
cardPane.add(new Card02(), "Card02");
JToggleButton btnCard01 = new JToggleButton("#1");
JToggleButton btnCard02 = new JToggleButton("#2");
ButtonGroup bg = new ButtonGroup();
bg.add(btnCard01);
bg.add(btnCard02);
JPanel buttons = new JPanel();
buttons.add(btnCard01);
buttons.add(btnCard02);
btnCard01.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPane, "Card01");
}
});
btnCard02.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPane, "Card02");
}
});
btnCard01.setSelected(true);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(cardPane);
frame.add(buttons, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Card01 extends JPanel {
public Card01() {
setLayout(new GridBagLayout());
add(new JLabel("#1"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class Card02 extends JPanel {
public Card02() {
setLayout(new GridBagLayout());
add(new JLabel("#2"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Text in transparent windows ( AWTUtilities.setWindowOpaque(window, false) ) is not antialiased correctly, and looks different then in opaque windows.
I'm using JDK 7.40.
Any idea how to workaround it?
In the program below the button text is not antialiased (correctly). Removing the setWindowOpaque() fixes the antialiasing.
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import com.sun.awt.AWTUtilities;
public class TransparentFrame extends JFrame
{
public TransparentFrame()
{
setUndecorated(true);
AWTUtilities.setWindowOpaque(this, false);
add(new JButton(new ExitAction()));
}
public static void main(String[] args)
{
JFrame frame = new TransparentFrame();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class ExitAction extends AbstractAction
{
public ExitAction()
{
super("Exit");
}
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
I minimized my program to include only the problem and I tried to code exactly as I understood from many examples. When I used the ActionListener, I get problem solved. But I wonder why using ItemListener, checkbox does not operate correctly.
If I run my program without ItemListener, it works correctly. With this ItemListener, checkBox doesn't change state.
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class omaJFrame extends JFrame{
private JCheckBox checkBox1;
public omaJFrame() {
super("Window Title");
TheHandler handler = new TheHandler();
setLayout(new FlowLayout());
checkBox1 = new JCheckBox("Checkbox 1");
add(checkBox1);
checkBox1.addItemListener(handler);
}
private class TheHandler implements ItemListener {
String output = "";
public void itemStateChanged(ItemEvent event) {
if (event.getItem()==checkBox1)
output = String.format("%s", checkBox1.isSelected());
JOptionPane.showMessageDialog(null, output);
}
}
}
import javax.swing.JFrame;
public class EventHandlerMain {
public static void main(String[] args) {
omaJFrame window = new omaJFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(350,200);
window.setVisible(true);
}
}
Works for me. Note also that Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class OmaJFrame extends JFrame {
private JCheckBox checkBox1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
OmaJFrame f = new OmaJFrame();
}
});
}
public OmaJFrame() {
super("Window Title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
TheHandler handler = new TheHandler();
setLayout(new FlowLayout());
checkBox1 = new JCheckBox("Checkbox 1");
add(checkBox1);
checkBox1.addItemListener(handler);
pack();
setLocationByPlatform(true);
setVisible(true);
}
private class TheHandler implements ItemListener {
String output = "";
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getItem() == checkBox1) {
output = String.format("%s", checkBox1.isSelected());
}
JOptionPane.showMessageDialog(null, output);
}
}
}
i am developing an Virtual keyboard module.
KeyBoardModule.java
KeyBoardModule kbm = new KeyBoardModule("small", false, null);
is called when in Other jForm(MainFrame.java) is clickevent on textbox
then I get new JFrame with keyboard(its like popup window),
When JButton enter is pressed it saves data to variable textFieldValue from textarea of KeyBoardModule.
than frame.disponse()
the main class calls MainFrame and mainframe call on click the keyboard, and i need to return value from keyboard to mainframe..
without using actionlistener(for enter button) in mainframe
To return a value directly from GUI1 to another GUI2 , GUI1 must have a reference to the object of GUI2. So that whenever you want to pass any message from GUI1 to GUI2 , you could do it by calling the appropriate method of GUI2. For example consider the code given below. While creating the object of InputBoard in MainFrame we pass the current object of MainFrame to InputBoard's constructor so that InputBoard could pass its input to MainFrame GUI using appropriate public method of MainFrame. Here MainFrame opens the InputBoard frame on click of button. And whenever some input is passed to the JTextField in InputBoard it is reflected within the JTextArea of MainFrame.
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
class MainFrame extends JFrame implements ActionListener
{
private JButton button;
private JTextArea tArea;
private InputBoard inBoard;
public void prepareAndShowGUI()
{
setTitle("Main Frame");
tArea = new JTextArea(10,30);
button = new JButton("Click Me");
inBoard = new InputBoard(this);
inBoard.prepareGUI();
JScrollPane tFieldPane = new JScrollPane(tArea);
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true);
tArea.setEditable(false);
button.addActionListener(this);
getContentPane().add(tFieldPane);
getContentPane().add(button,BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.requestFocus();
}
#Override
public void actionPerformed(ActionEvent evt)
{
if (!inBoard.isVisible())
{
inBoard.setVisible(true);
}
inBoard.toFront();
}
public void setText(final String s)
{
tArea.setText(s);
}
public static void main(String[] st)
{
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
MainFrame mf = new MainFrame();
mf.prepareAndShowGUI();
}
});
}
}
class InputBoard extends JFrame implements DocumentListener
{
MainFrame mainFrame ;
JTextField inField;
public InputBoard(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
}
public void prepareGUI()
{
setTitle("Input Board");
inField = new JTextField(40);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(inField);
inField.getDocument().addDocumentListener(this);
setLocationRelativeTo(mainFrame);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
}
#Override
public void changedUpdate(DocumentEvent evt)
{
mainFrame.setText(inField.getText());
}
#Override
public void insertUpdate(DocumentEvent evt)
{
mainFrame.setText(inField.getText());
}
#Override
public void removeUpdate(DocumentEvent evt)
{
mainFrame.setText(inField.getText());
}
}