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());
}
}
Related
Say I have a separate class that has a void method called sampleVoidMethod that asks and prints user input.
I have assigned a JButton in another class to initiate sampleVoidMethod(). What I don't understand is how to make the sampleVoidMethod display its output inside the JFrame.
Right now, it's displaying sampleVoidMethod body on my IDE's console with the JFrame open. Below is the jframe class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class someGUIClass {
public void createWindow() {
JFrame battleFrame = new JFrame("Welcome");
battleFrame.setVisible(true);
battleFrame.setResizable(true);
battleFrame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
battleFrame.setSize(600,500);
battleFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
battleFrame.add(panel);
JButton buttonOne = new JButton("Press Me");
buttonOne.addActionListener((new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sampleVoidMethod();
}
}));
buttonOne.setVisible(true);
buttonOne.setBounds(400,300,100,100);
panel.add(buttonOne);
}
}
Below is the sampleVoidMethod of SomeClass:
public void sampleVoidMethod() {
System.out.println("I am a sample method!");
}
Actually i'm writing code. I want to display message dialogue (without pressing any button) when I left my JTextField but don't know how to do this. Please Help. Im using NetBeans.
You can use Focus Listener API to achieve that.
On focusLost event, you can show your dialog box.
Example from the documentation:
public void focusLost( FocusEvent e )
{
displayMessage( "Focus lost", e );
}
You can use FocusListener class focusLost() method.
Simple Example:
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ExampleClass {
JFrame MainFrame;
JTextField textField1;
JTextField textField2;
public ExampleClass(){
MainFrame = new JFrame("Example");
MainFrame.setLayout(new FlowLayout());
textField1 = new JTextField(10);
textFieldFocus();
textField2 = new JTextField("Dummy text");
MainFrame.add(textField1);
MainFrame.add(textField2);
MainFrame.pack();
MainFrame.setVisible(true);
}
private void textFieldFocus() {
textField1.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
JOptionPane.showMessageDialog(null, "Done!");
}
#Override
public void focusGained(FocusEvent e) {}
});
}
public static void main(String[] args) {
new ExampleClass();
}
}
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");
}
}
How can I assign two buttons to share the same class for handling events in Java/swing?
For example, I have this:
private class BtnEvtHandler implements ActionListener {
private int counter=10;
public void actionPerformed(ActionEvent e) {
gs.setX(counter);
gs.repaint();
counter=counter+10;
}
public void actionPerformed(ActionEvent e) {
//action for move button
}
}
JButton jumpBtn= new JButton("JUMP");
BtnEvtHandler okButtonHandler= new BtnEvtHandler();
(jumpBtn).addActionListener(okButtonHandler);
menuPanel.add(jumpBtn);
Now I want to add another button as below which can have the same class as event handler but dispatches to different actionPerformed as mentioned in above code.
JButton moveBtn= new JButton("MOVE");
menuPanel.add(moveBtn);
(moveBtn).addActionListener(okButtonHandler);
You can't reuse one ActionListener and expect it to call a different method depending on the button you attach it to. The contract of ActionListener has one method that gets called. But you can check the source of the event and have flow control based on that. Here's an example:
package com.sandbox;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class SwingSandbox {
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
JPanel pane = new JPanel();
MyActionListener myActionListener = new MyActionListener();
JButton button1 = new JButton("Button1");
button1.addActionListener(myActionListener);
pane.add(button1);
JButton button2 = new JButton("Button2");
button2.addActionListener(myActionListener);
pane.add(button2);
frame.add(pane);
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
private static class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if ("Button1".equals(source.getText())) {
System.out.println("You clicked button 1");
} else {
System.out.println("You clicked button 2");
}
}
}
}
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.