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");
}
}
}
}
Related
So I have 3 separate classes, the settings button on the mainmenu class should switch to main menu, but it simply hides the first panel, same thing when i click return on the other menu, i would like to find a simple soluton without using a layout manager because i don't know how to have card layout communicate to the 2 classes, but thats the solution, it'd be nice if someone could give me some pointers on how to implement that:
public class Game extends JFrame {
MainMenu mainMenu;
Settings settings;
public Game(){
setSize(900,900);
setDefaultCloseOperation(3);
mainMenu = new MainMenu();
settings = new Settings();
mainMenu.setSettings(settings);
settings.setMainMenu(mainMenu);
add(settings,BorderLayout.CENTER);
add(mainMenu, BorderLayout.CENTER);
}
public static void main(String[] args) {
Game game = new Game();
game.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainMenu extends JPanel {
Settings settings;
public void setSettings(Settings settings) {
this.settings = settings;
}
public MainMenu() {
setLayout(new GridLayout(1,3));
JButton Newgame = new JButton("New Game");
JButton Cont = new JButton("Continue");
JButton Sett = new JButton("Settings");
add(Newgame);
add(Cont);
SwitchMenu1 switchMenu1 = new SwitchMenu1();
Sett.addActionListener(switchMenu1);
add(Sett);
}
class SwitchMenu1 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(isVisible()){
settings.setVisible(true);
setVisible(false);
}
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Settings extends JPanel {
MainMenu mainMenu;
public void setMainMenu(MainMenu mainMenu) {
this.mainMenu = mainMenu;
}
public Settings(){
JButton Return = new JButton("Return");
SwitchMenu2 switchMenu2 = new SwitchMenu2();
Return.addActionListener(switchMenu2);
add(Return, BorderLayout.SOUTH);
}
class SwitchMenu2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(isVisible()){
mainMenu.setVisible(true);
setVisible(false);
}
}
}
}
I want to have the other JPanel show up on button click, but it doesn't work, the first one simply disappears. How can i fix this?
Thanks a lot!
This sounds a use case for CardLayout. You have a JPanel, named for example cards, which uses a CardLayout manager. You add all your panels (cards) to that panel, giving them unique names (e.g., "MAIN_MENU", "SETTINGS", etc.). Then, instead of passing every other panel in each of your panels, you only pass the cards panel, which can be used to show the card you wish, e.g., cl.show(cards, "SETTINGS"); on clicking a button, for instance.
Update
As per #c0der's suggestion (see comments section below), the code structure has been updated.
Game.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Game extends JFrame {
JPanel cards;
CardLayout cardLayout;
public Game(){
MainMenu mainMenu = new MainMenu();
Settings settings = new Settings();
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(mainMenu, "MAIN_MENU");
cards.add(settings, "SETTINGS");
mainMenu.setSetBtnActionListener(new BtnController("SETTINGS"));
settings.setReturnBtnActionListener(new BtnController("MAIN_MENU"));
add(cards);
setSize(640,480);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
class BtnController implements ActionListener {
String cardName;
public BtnController(String cardName) {
this.cardName = cardName;
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cards, cardName);
}
}
public static void main(String[] args) {
new Game();
}
}
MainMenu.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class MainMenu extends JPanel {
JButton setBtn;
public MainMenu() {
setLayout(new GridLayout(1, 3));
JButton newGameBtn = new JButton("New Game");
JButton contBtn = new JButton("Continue");
setBtn = new JButton("Settings");
add(newGameBtn);
add(contBtn);
add(setBtn);
}
public void setSetBtnActionListener(ActionListener al) {
setBtn.addActionListener(al);
}
}
Settings.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class Settings extends JPanel {
JButton returnBtn;
public Settings() {
returnBtn = new JButton("Return");
setLayout(new BorderLayout());
add(returnBtn, BorderLayout.SOUTH);
}
public void setReturnBtnActionListener(ActionListener al) {
returnBtn.addActionListener(al);
}
}
This example has Radio Buttons located on a Sub Menu as seen here.
What I would like to do is anytime the "Change Radio Button" button is pressed, it will change which button is selected on the menu. This means it has to first retrieve which is currently set then select the other.
Granted for this simple sample the Radio Buttons could be made instance variables to make things easy but image the JMenu and associated sub-menus and radio buttons are generated is some class further down in the bowels of the program. Direct access is not that direct.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
public class RadioButtonsOnMenu
{
public static void main(final String args[])
{
JFrame frame = new JFrame("MenuSample Example");
JButton jButton = new JButton("Change Radio Button");
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Changing Radion Button");
//How to change the JButton on the menu?
//frame.getMenuBar().......
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel();
jPanel.add(jButton);
frame.add(jPanel);
frame.setJMenuBar(buildMenu());
frame.setSize(350, 250);
frame.setVisible(true);
}
public static JMenuBar buildMenu()
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(newMenuItem);
JMenu findOptionsMenu = new JMenu("Options");
findOptionsMenu.setMnemonic(KeyEvent.VK_O);
fileMenu.add(findOptionsMenu);
ButtonGroup directionGroup = new ButtonGroup();
JRadioButtonMenuItem forwardMenuItem = new JRadioButtonMenuItem("Forward", true);
forwardMenuItem.setMnemonic(KeyEvent.VK_F);
findOptionsMenu.add(forwardMenuItem);
directionGroup.add(forwardMenuItem);
JRadioButtonMenuItem backwardMenuItem = new JRadioButtonMenuItem("Backward");
backwardMenuItem.setMnemonic(KeyEvent.VK_B);
findOptionsMenu.add(backwardMenuItem);
directionGroup.add(backwardMenuItem);
return menuBar;
}
}
It is not clear how best to access the sub-menu and associated radio button settings within the JButton action.
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Changing Radion Button");
//How to change the JButton on the menu?
//frame.getMenuBar().......
}
});
I could probably get the Menu Bar from the Frame and drill down figure the code can get messy if there Menu Bar has numerous items, sub items and even multiple radio button groups.
Is there a more direct way to find out which Radio Buttons on the menu are selected as well as a more direct way to change their value?
The "trick" is to create an application model to hold the value of the menu radio buttons.
Here's the GUI I created.
I started the Swing application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I created a JFrame and a JButton JPanel. I separated the creation of the JFrame and JPanel.
I created an application model class to hold a boolean which determines whether forward or backward is selected. The JButton ActionListener switches the state of the boolean. The updateRadioButtonMenu method updates the selected state of the radio button menu items.
Here's the complete runnable code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
public class RadioButtonsOnMenu implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new RadioButtonsOnMenu());
}
private ApplicationModel model;
private JRadioButtonMenuItem backwardMenuItem;
private JRadioButtonMenuItem forwardMenuItem;
public RadioButtonsOnMenu() {
this.model = new ApplicationModel();
}
#Override
public void run() {
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
frame.add(createButtonPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(newMenuItem);
JMenu findOptionsMenu = new JMenu("Options");
findOptionsMenu.setMnemonic(KeyEvent.VK_O);
fileMenu.add(findOptionsMenu);
ButtonGroup directionGroup = new ButtonGroup();
forwardMenuItem = new JRadioButtonMenuItem("Forward", model.isForward());
forwardMenuItem.setMnemonic(KeyEvent.VK_F);
findOptionsMenu.add(forwardMenuItem);
directionGroup.add(forwardMenuItem);
backwardMenuItem = new JRadioButtonMenuItem("Backward", !model.isForward());
backwardMenuItem.setMnemonic(KeyEvent.VK_B);
findOptionsMenu.add(backwardMenuItem);
directionGroup.add(backwardMenuItem);
return menuBar;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
JButton button = new JButton("Change Radio Button");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
model.setForward(!model.isForward());
updateRadioButtonMenu();
}
});
panel.add(button);
return panel;
}
public void updateRadioButtonMenu() {
forwardMenuItem.setSelected(model.isForward());
backwardMenuItem.setSelected(!model.isForward());
}
public class ApplicationModel {
private boolean isForward;
public ApplicationModel() {
this.isForward = true;
}
public boolean isForward() {
return isForward;
}
public void setForward(boolean isForward) {
this.isForward = isForward;
}
}
}
What you could do is to save the state in a boolean. You could add listener to the radio buttons and change the boolean everytime one of them is selected
boolean isForward = true;
so when changed to backward you set the value to false. This way you don't need to get The state of the radiobuttons everytime.
In your button actionlistener you could then do:
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Changing Radion Button");
forwardRadioButton.setState(!isForward);
backwardRadioButton.setState(isForward);
iSForward = !isForward;
}
});
I would say you need to do these two things:
Since you seem to have a lot of items it is best to store them somewhere else
1 Create a class to store all the items and then just pass the class
public class myItemHolder{
//declare all the items here instead of at the main
JButton jButton = new JButton("Change Radio Button");
ButtonGroup directionGroup = new ButtonGroup();
JRadioButtonMenuItem forwardMenuItem = new JRadioButtonMenuItem("Forward", true);
JRadioButtonMenuItem backwardMenuItem = new JRadioButtonMenuItem("Backward");
myListener(myItemHolder items){
directionGroup.add(forwardMenuItem);
}
public ButtonGroup getButtons() {
return directionGroup;
}
public JButton getClick() {
return jButton;
}
}
2 Create your own action listener class like so
public class myListener implements ActionListener{
myItemHolders items;
myListener(myItemHolder items){
this.items=items;
}
#Override
public void actionPerformed(ActionEvent e) {
//get the radiobutton like so and do what you want with it
items.getButtons()
}
}
Now you just need to do this in the main:
public class RadioButtonsOnMenu
{
public static void main(final String args[])
{
myItemHolder items = new myItemHolder();
items.getClick.addActionListener(new myListener(items));
}
}
And there you can access everything easily :)
It is all a matter of where you declare your stuff.
Or if you only want to send the ButtonGroup you can just do so by changing the structure a little so the actionlistener only requests the ButtonGroup and give it items.getButtons() instead of items.
Here's another possible way to go about it using Enum state tracking. I make use of a Enum and a Map to track the Radio Button that should be activated. This lets it scale as large as you want for associated Radio Button items within the same JMenu.
RadioMenu
package tools;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;
public class RadioMenu<E extends Enum<E>> extends JMenu {
private static final long serialVersionUID = 1L;
private E currentState;
private JRadioButtonMenuItem selectedRadioButton;
private HashMap<E, JRadioButtonMenuItem> stateMap;
public RadioMenu() {
stateMap = new HashMap<E, JRadioButtonMenuItem>();
}
public RadioMenu(String name) {
super(name);
stateMap = new HashMap<E, JRadioButtonMenuItem>();
}
public void addRadioButton(E associatedState, JRadioButtonMenuItem radioButton) {
//Set default to first added button
if(stateMap.isEmpty()) {
currentState = associatedState;
radioButton.setSelected(true);
selectedRadioButton = radioButton;
}
add(radioButton);
stateMap.put(associatedState, radioButton);
radioButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setState(associatedState);
}
});
}
public void generateButtonsFromEnum(Class<E> enumType) {
for(E enumValue : enumType.getEnumConstants()) {
addRadioButton(enumValue, new JRadioButtonMenuItem(enumValue.toString()));
}
}
public E getState() {
return currentState;
}
public void setState(E newState) {
currentState = newState;
selectedRadioButton.setSelected(false);
selectedRadioButton = stateMap.get(newState);
selectedRadioButton.setSelected(true);
}
}
RadioMenuTest
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import tools.RadioMenu;
public class RadioMenuTest implements Runnable {
public enum RadioOptions {
Forward, Backward, Left, Right
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new RadioMenuTest());
}
private RadioMenu<RadioOptions> optionsMenu;
#Override
public void run() {
JFrame frame = new JFrame("RadioMenu Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
frame.getContentPane().add(createButtonPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
optionsMenu = new RadioMenu<RadioOptions>("Options");
optionsMenu.generateButtonsFromEnum(RadioOptions.class);
fileMenu.add(optionsMenu);
return menuBar;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
JButton setBackwardButton = new JButton("Set To Backward");
setBackwardButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
optionsMenu.setState(RadioOptions.Backward);
}
});
panel.add(setBackwardButton);
JButton setRightButton = new JButton("Set To Right");
setRightButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
optionsMenu.setState(RadioOptions.Right);
}
});
panel.add(setRightButton);
return panel;
}
}
I have a simple JButton linked to an actionPerformed method. Now I want to bind a key to the button so that when i press this key on the keyboard it performs the same action it would perform by pressing the button with the mouse.
I found out this code is working but as you can see I have to write twice the code to perform when key is pressed or button is pressed.
Is there a way to avoid this?
import java.io.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.*;
public class provakey implements ActionListener{
private JButton bStart;
//Costruttore
public provakey() throws IOException{
initGUI();
}
private void initGUI(){
JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel();
bStart = new JButton("Avvia");
bStart.addActionListener(this);
bStart.setActionCommand("start");
bStart.setBounds(140,10,150,40);
AbstractAction buttonPressed = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if (bStart.isEnabled()){
System.out.println("pressed");
}
}
};
bStart.getActionMap().put("start", buttonPressed);
bStart.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,0), "start");
buttonPanel.setLayout(null);
buttonPanel.setBounds(0,240,600,60);
buttonPanel.add(bStart);
frame.setLayout(null);
frame.add(buttonPanel);
frame.setTitle("Prova");
frame.setSize(600, 350);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if ("start".equals(e.getActionCommand())) {
buttonPressed();
}
}
public void buttonPressed(){
System.out.println("pressed");
}
public static void main (String args[]) throws IOException {
provakey p = new provakey();
}
}
I have to write twice the code to perform when key is pressed or button is pressed.
An Action is an ActionListener.
So, you can add an Action to the button, so the same Action will be executed whether you click on the button or use the key binding:
//bStart.addActionListener(this);
bStart.addActionListener( buttonPressed );
There is no need to set the action command since you now have a unique class for your "Start" processing that is not shared by other buttons in your class.
See: https://stackoverflow.com/a/33739732/131872 for a working example.
This question already has answers here:
this: Cannot use this in static context
(5 answers)
Closed 5 years ago.
hi my Problem was i cant add Buttons to the Action listener
i will made a menu
i dont know why i become a error
here the code
package lvl;
import java.awt.Label;
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;
public class Main extends JFrame implements ActionListener{
private JButton button;
private JButton eintellungen;
private JButton credits;
private JButton schliessen;
public static void main(String[] args) {
JFrame meinJFrame = new JFrame();
meinJFrame.setTitle("menu");
JPanel panel = new JPanel();
JButton button = new JButton("play");
JButton schliessen = new JButton("schließen");
JButton eintellungen = new JButton("einstellungen");
JButton credits = new JButton("credits");
panel.add(button);
panel.add(schliessen);
panel.add(credits);
panel.add(eintellungen);
credits.addActionListener(this);
meinJFrame.add(panel);
meinJFrame.setSize(500, 500);
meinJFrame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
}
oh i become a error the error says Cannot use this in a static context and it was by credits.addActionListener(this);
please help me
You are in a static context of public static main. There is no this in static context. Use anonomous class insteed.
credits.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//// handle action here
}
});
obviously,your class Main and it's method Main(String[] args) is static,and although your Main implements ActionListener,it cant use cause the method addActionListener need a Object ,static method Main has not 'this' context.
you can
credits.addActionListener(new YourActionListener());
meinJFrame.add(panel);
meinJFrame.setSize(500, 500);
meinJFrame.setVisible(true);
}
}
class YourActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
}
}
or
credits.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
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());
}
}