I wanted to create dynamic list of buttons using ArrayList. If I copy the method which is written AddButton in constructor , it works. However, If I run this method in ActionListener, it won't work. How do I resolve this ?
Code:
package HelloJFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField text1;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main().setVisible(true);
}
public Main() {
super("Hello JFrame");// Set Title from JFrame constructor
setSize(600, 600);
setResizable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
text1 = new JTextField(20);
// text.setSize(200, 20);
add(text1);
JButton submit = new JButton("Add Button");
submit.addActionListener(this);
submit.setActionCommand("ekle");
add(submit);
}
#Override
public void actionPerformed(ActionEvent e) {
AddButton(2);
}
public void AddButton(int number) {
ArrayList<JButton> buttons = new ArrayList<JButton>();
for (int i = 0; i < number; i++) {
buttons.add(new JButton("Button #" + i));
}
/*
* JButton button = new JButton("Click!");
* button.addActionListener(this); add(button);
*/
for (int i = 0; i < buttons.size(); i++) {
this.add(buttons.get(i));
}
}
}
After adding all the buttons to the frame you need to add
revalidate();
repaint();
to make sure the layout manager is invoked.
Also, method names should NOT start with an upper case character. "AddButton" should be "addButton".
Related
I started codig Java last weekend and I've read most of the basic stuff. I'm trying to separate my frame from main method, and panels from the frame so they are all in separate class files. I have trouble calling ActionLister in "Frame1" class with a button (buttonBack) in the "TheGame" class. The button should trigger the Listener which in turn should remove theGame panel and add mainMenu panel to frame1. I know that CardLayout is better suited for swapping panels but i want to learn the limits and workarounds before i go do it the "easy" way, i feel that you learn much more that way.
Here is some of my code:
Main:
public class Main {
public static void main(String[] args){
Frame1 frame1 = new Frame1();
frame1.frame1();
}
}
Frame1:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
class Frame1 {
private JFrame frame1 = new JFrame("Name");
public void frame1() {
TheGame theGame = new TheGame();
MainMenu mainMenu = new MainMenu();
// Frame options
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLocationRelativeTo(null);
// Creating a top menu
JMenuBar menubar = new JMenuBar();
frame1.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenuItem about = new JMenuItem("About");
help.add(about);
// Creating action for the menuitem "exit".
class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
exit.addActionListener(new exitaction());
// Creating listener for the menuitem "about".
class aboutaction implements ActionListener{
public void actionPerformed (ActionEvent e){
JDialog dialogabout = new JDialog();
JOptionPane.showMessageDialog(dialogabout, "Made by: ");
}
}
about.addActionListener(new aboutaction());
// Add the panels, pack and setVisible
theGame.theGame();
mainMenu.mainMenu();
frame1.add(theGame.getGUI());
// This is the ActionListener i have trouble connecting with the buttonBack in the "theGame" class
class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
frame1.remove(theGame.getGUI());
frame1.add(MainMenu.getGUI());
}
}
frame1.pack();
frame1.setVisible(true);
}
public JFrame getGUI() {
return frame1;
}
}
MainMenu:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class MainMenu {
private JPanel mainMenu = new JPanel (new GridBagLayout());
public void mainMenu() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating Label
JLabel introduction = new JLabel("Name");
grid.gridx = 1;
grid.gridy = 3;
mainMenu.add(introduction, grid);
// Creating buttons Start Game, Highscore and Exit Game
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 5;
mainMenu.add(buttonNewGame, grid);
JButton buttonHighscore = new JButton("Highscore");
buttonHighscore.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 6;
mainMenu.add(buttonHighscore, grid);
JButton buttonExit = new JButton("Exit Game");
buttonExit.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 7;
mainMenu.add(buttonExit, grid);
}
public JComponent getGUI() {
return mainMenu;
}
}
TheGame:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class TheGame {
private JPanel theGame = new JPanel (new GridBagLayout());
public void theGame() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating a label
JLabel label1 = new JLabel("Press the BACK button to go back to Main Menu");
label1.setVisible(true);
grid.gridx = 1;
grid.gridy = 0;
theGame.add(label1,grid);
// Creating BACK button
JButton buttonBack = new JButton("BACK");
buttonBack.setVisible(true);
grid.gridx = 1;
grid.gridy = 1;
buttonBack.addActionListener(new --); // This is the button i want to connect with the ActionListener on Frame1 class
theGame.add(buttonBack, grid);
}
public JComponent getGUI() {
return theGame;
}
}
I've tried moving the ActionListener outside of methods, inside the Main, declaring it static, but haven't been able to call it anyways. I've also looked at other posts like this: Add an actionListener to a JButton from another class but have not been able to implement it in to my code.
Any help is appreciated.
The best answer -- use MVC (model-view-controller) structure (and CardLayout) for the swapping of your views. If you don't want to do that, then your listener should have a reference to the container that does the swapping, and so that the listener can notify this container that a swap should occur. The container will then call its own code to do the swapping. To do this you need to pass references around including a reference to the main GUI to wherever it is needed. This can get messy, which is why MVC, which is more work, is usually better -- fewer connections/complexity in the long term.
Side note -- don't pass a JDialog into a JOptionPane as a JOptionPane is a specialized JDialog, and you shouldn't have a top level window displaying a top level window. Instead pass in a JPanel.
For example:
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PassRef {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
MyMain mainPanel = new MyMain();
JFrame frame = new JFrame("Pass Reference");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class MyMain extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
private CardLayout cardLayout = new CardLayout();
private MenuView menuView = new MenuView(this);
private ActionView1 actionView1 = new ActionView1(this);
public MyMain() {
setLayout(cardLayout);
add(menuView, MenuView.NAME);
add(actionView1, ActionView1.NAME);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public void showCard(String key) {
cardLayout.show(this, key);
// or swap by hand if you don't want to use CardLayout
// but remember to revalidate and repaint whenever doing it by hand
}
}
class MenuView extends JPanel {
public static final String NAME = "Menu View";
public MenuView(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder("Menu"));
add(new JButton(new GoToAction("Action 1", ActionView1.NAME, myMain)));
}
}
class ActionView1 extends JPanel {
public static final String NAME = "Action View 1";
public ActionView1(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder(NAME));
add(new JButton(new GoToAction("Main Menu", MenuView.NAME, myMain)));
}
}
class GoToAction extends AbstractAction {
private String key;
private MyMain myMain;
public GoToAction(String name, String key, MyMain myMain) {
super(name);
this.key = key;
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
myMain.showCard(key);
}
}
What I want to design is with this code is when I enter any text into the Textfield, then hit the button to save it. So I've been trying few ways, but I could not solve that command prompt shows me an empty space...
When I tried the source code into the "main" method, it was working well like what I expected..
Here is my source code:
package test;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
class testListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = new TxtField().savedTxt();
System.out.println("ActionPerformed :" + s);
}
}
public class TxtField {
static JTextField jtf;
JFrame jf;
JButton jbtn;
static String temp;
public TxtField() {
jtf = new JTextField(10);
jf = new JFrame("JFrame");
jbtn = new JButton("OK");
jf.add(jtf);
jf.add(jbtn);
jf.setVisible(true);
jf.setSize(300, 300);
jf.setLayout(new GridLayout(2, 0));
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.addActionListener(new testListener());
jbtn.addActionListener(new testListener());
}
public String savedTxt() {
temp = jtf.getText();
System.out.println("Temp is :" + temp);
return temp;
}
public static void main(String[] args) {
new TxtField();
}
}
You are creating a new TxtField when the action is called, instead of referencing the one that invoked the action:
String s = new TxtField().savedTxt();
Try making TxtField itself the ActionListener:
public class TxtField implements ActionListener
Then reference the current instance:
jtf.addActionListener(this);
jbtn.addActionListener(this);
Then reference the JTextField in the current instance:
String s = savedTxt();
You are close...You can do something like this:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Test {
Test t;
static JTextField jtf;
JFrame jf;
JButton jbtn;
static String temp;
public Test() {
t = this;
class testListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = jtf.getText();
t.savedTxt();
System.out.println("ActionPerformed :" + s);
}
}
jtf = new JTextField(10);
jf = new JFrame("JFrame");
jbtn = new JButton("OK");
jf.add(jtf);
jf.add(jbtn);
jf.setVisible(true);
jf.setSize(300, 300);
jf.setLayout(new GridLayout(2, 0));
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.addActionListener(new testListener());
jbtn.addActionListener(new testListener());
}
public String savedTxt() {
temp = jtf.getText();
System.out.println("Temp is :" + temp);
return temp;
}
public static void main(String[] args) {
Test t1 = new Test();
}
}
The problem is you are creating a new Instance of your class in the actionPerformed event instead of using the one you already have...
String s = new TxtField().savedTxt();
This is calling savedTxt() on the new instance instead of the one you already have which has the text you typed.
Questions I am pulling my hair out over.
How do I get the array to add data to current index, then increment to the next index to add changed JTextField data for the next button press. currently I'm overwriting the same index.
I have tried to figure out actionlisteners for the button "Submit" that uses a counter with nesting of the loop. played with ideas from question 23331198 and 3010840 and 17829577 many others as a reference but didn't really get it to far. Most searches pull up info on managing buttons with arrays and creating button arrays so I assume I'm not using the correct wording to search with. I have read a few places that an MD array is not the best option to use.
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 javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
int arrayIndex = 0;
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < tutArray.length; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
textArea.append("\n");
textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
This is what I was looking for thanks for the help!
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 javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
int arrayIndex = 0;
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
textArea.setText("");
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < arrayIndex; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
// textArea.append("\n");
//textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
You can add the index as a field in your main object:
protected int index;
in your actionPerformed you increase index:
index++;
NOTE:
But why do you extend from JFrame AND use the field mainFrame?
you can use
this.setSize(800,800);
this.add(mainPanel);
Please declare (because of extends JFrame):
private static final long serialVersionUID = 1L;
Please start the name of an object with a lower case letter:
JButton exit = new JButton("Quit");
I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.
I'm working on a school project where we have to create a virtual smartphone, to run on a computer.
My problem is that I need to create a keyboard on the screen (like on an smartphone), which you can then use by clicking with your mouse. I could just create every single JButton, but that will take a really long time. So I was hopping that someone knew some sort of algorithm that creates all the buttons and places them correctly on the screen.
Thank you in advance :)
You could construct the buttons through the use of for loops. One loop for every keyboard row is a plausible approach.
String row1 = "1234567890";
String row2 = "qwertyuiop";
// and so forth
String[] rows = { row1, row2, .. };
for (int i = 0; i < rows.length; i++) {
char[] keys = rows[i].toCharArray();
for (int j = 0; i < keys.length; j++) {
JButton button = new JButton(Character.toString(keys[j]));
// add button
}
}
// add special buttons like space bar
This could be done more elegantly through a more OOP approach, but this basic loop system will work.
This simple example might help you:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame
{
private JTextField txt;
private PopUpKeyboard keyboard;
public MainFrame()
{
super("pop-up keyboard");
setDefaultCloseOperation(EXIT_ON_CLOSE);
txt = new JTextField(20);
keyboard = new PopUpKeyboard(txt);
txt.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
Point p = txt.getLocationOnScreen();
p.y += 30;
keyboard.setLocation(p);
keyboard.setVisible(true);
}
});
setLayout(new FlowLayout());
add(txt);
pack();
setLocationByPlatform(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new MainFrame().setVisible(true);
}
});
}
private class PopUpKeyboard extends JDialog implements ActionListener
{
private JTextField txt;
public PopUpKeyboard(JTextField txt)
{
this.txt = txt;
setLayout(new GridLayout(3, 3));
for(int i = 1; i <= 9; i++) createButton(Integer.toString(i));
pack();
}
private void createButton(String label)
{
JButton btn = new JButton(label);
btn.addActionListener(this);
btn.setFocusPainted(false);
btn.setPreferredSize(new Dimension(100, 100));
Font font = btn.getFont();
float size = font.getSize() + 15.0f;
btn.setFont(font.deriveFont(size));
add(btn);
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
txt.setText(txt.getText() + actionCommand);
}
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String alphabet = "abcdefghijklmnopqrstuvwxyz";
JFrame myFrame = new JFrame();
JPanel myPanel = new JPanel();
for (int i = 0; i < alphabet.length(); i++) {
myPanel.add(new JButton(alphabet.substring(i, i + 1)));
}
myFrame.add(myPanel);
myFrame.pack();
myFrame.setVisible(true);
}
This is a fast example of how to do it :).