Java Calculator is producing the right output - java

I worked on a simple project on my own, which was to develop a calculator using Java, but I am getting the wrong output:
When I press button 1--> 1
When I press button 2-->2
When I press button 1-->11 (This is wrong) It should display 121 not 11
When I press button 2-->22
I asked everyone, I looked over my code and I could not find the solution. Most people say my code's logic is code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JTextField;
public class ButtonListener implements ActionListener {
JTextField text;
String display = "";
String button[];
JButton buttons[];
public ButtonListener(JTextField text, String[] button, JButton[] buttons) {
this.text = text;
this.button = button;
this.buttons = buttons;
}
public void Display(String button) {
display = display + button;
// return display;
}
public void actionPerformed(ActionEvent Buttonpress) {
/******************** Constants ********************/
// Planks Constant
if (Buttonpress.getSource() == buttons[0]) {
// display+=button[0];
Display(button[0]);
}
// Elementary Charge
if (Buttonpress.getSource() == buttons[8]) {
// display+=Buttonpress.getSource();
Display(button[8]);
}
text.setText(display);
}
}

First of all method names should NOT start with an upper case character. "Display" should be "display".
Don't keep arrays of buttons and strings to determine which button was clicked and which text should be appended.
You can get all the information you need to update your display text field from the ActionEvent itself.
Here is an example for you to look at:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
// UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Related

How can I move focused button?

I have some issues with my Java Swing code.
I want to move between buttons using the keyboard (UP, DOWN key) and press the button using the ENTER key. But I think there is no way to use the keyboard.
Can anyone teach me how to move buttons with the keyboard UP and DOWN keys?
I also have used JRadioButton, but it was difficult...
The below code is my code!
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class StartScreen extends JFrame {
JButton[] buttons;
private KeyListener playerKeyListener;
public StartScreen() {
setTitle("테트리스 시작 화면");
setSize(400, 500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setBackground(Color.PINK);
JPanel jPanel = new JPanel();
jPanel.setBackground(Color.PINK);
jPanel.setBounds(0,0,400,500);
jPanel.setLayout(null);
String[] btnText = {"일반 모드 게임 시작", "아이템 모드 게임 시작", "게임 설정", "스코어 보드", "게임 종료"};
buttons = new JButton[5];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(btnText[i]);
buttons[i].setBackground(new Color(0,0,0,0));
buttons[i].setVisible(true);
buttons[i].setBorderPainted(true);
jPanel.add(buttons[i]);
}
int y = 150;
for (int i = 0; i < buttons.length; i++) {
buttons[i].setBounds(125, y, 150, 50);
y += 60;
}
JLabel jLabel = new JLabel("Tetris");
Font font = new Font("Arial", Font.BOLD, 40);
jLabel.setFont(font);
jLabel.setLayout(null);
jLabel.setBounds(145,80,150,40);
jPanel.add(jLabel, BorderLayout.CENTER);
getContentPane().add(jPanel);
setVisible(true);
playerKeyListener = new PlayerKeyListener();
addKeyListener(playerKeyListener);
setFocusable(true);
requestFocus();
}
public class PlayerKeyListener implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_UP:
break;
default:
System.out.println("");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
public static void main(String[] args) {
new StartScreen();
}
}
Following shows two different approaches:
add a KeyStroke to the set of focus traversal keys which allows you change the behaviour for a specific component.
add a Key Binding to the panel which will then allow you to use the arrow keys for all components on the panel
Choose the approach that best meets your requirment.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FocusTraversalKeys extends JPanel
{
public FocusTraversalKeys()
{
for (int i = 0; i < 5; i++)
{
JButton button = new JButton( String.valueOf(i) );
add( button );
// Add left arrow key as a focus traversal key.
// Applies only to this specific component.
Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>( button.getFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS ) );
set.add( KeyStroke.getKeyStroke( "LEFT" ) );
button.setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set );
}
// Add right arrow key as a focus traversal key.
// Applies to all components on the panel
InputMap im = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
String rightText = "RIGHT";
im.put(KeyStroke.getKeyStroke(rightText), rightText);
getActionMap().put(rightText, new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("FocusTraversalKeys");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new FocusTraversalKeys() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Swing window doesn't return value after x time

I'm trying to do a call simulator in Swing and for some reason the window won't budge.
My goal is to open a seperate window that returns true or false if a button is pressed or another has been pressed. The user should have 15 seconds to do something, otherwise it returns false and performs an action.
When it returns, it should finish it's execution. This function is called by another function part of main.
However, due to my lack of experience and idiocy, it doesn't work. Instead, it opens a window (blank) that never closes by itself when it should...
Here's the code:
public static boolean callWindow(Telephone src, Telephone dst) {
Timer t1 = new Timer(15000, e-> {
DateTime date = new DateTime();
Call c = new Call(date, src.getTelephone(), dst.getTelephone(), 0);
dst.addLostCall(c);
});
//Janela para atender
JFrame window = new JFrame();
window.setTitle("Incoming Call");
JLabel telephones = new JLabel();
telephones.setText("From: " + src.getTelephone() + " To: " + dst.getTelephone() );
JButton answerCall = new JButton("Answer");
JButton denyCall = new JButton("Decline");
JLabel status = new JLabel();
answerCall.addActionListener( e -> status.setText("answer") );
denyCall.addActionListener( e -> status.setText("no answer") );
answerCall.setBackground(Color.GREEN);
denyCall.setBackground(Color.RED);
JPanel callInfo = new JPanel();
callInfo.add(telephones);
JPanel callOptions = new JPanel();
callOptions.add(answerCall);
callOptions.add(denyCall);
Container container = window.getContentPane();
container.add(callInfo, BorderLayout.NORTH);
container.add(callOptions);
window.setSize(350,120);
window.setVisible(true);
t1.start();
while (t1.isRunning()) {
if (status.getText().equals("answer")) return true;
if (status.getText().equals("no answer")) return false;
}
return false;
}
I would appreciate to know how this could work and how to despaghettify this horrible code.
I used a JDialog to demonstrate how to close a window after 15 seconds.
Here's the GUI JFrame I created.
Here's the JDialog I created
The JDialog will dispose after 15 seconds. The isAnswered method will return true if the call was answered or false if the call was declined, the JDialog was closed by left-clicking on the X, or when the 15 seconds runs out.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class JDialogTimedGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTimedGUI());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Timed GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
75, 100, 75, 100));
panel.setPreferredSize(new Dimension(400, 200));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
IncomingCall ic = new IncomingCall(frame, "Incoming Call",
"555-1212", "555-2323");
System.out.println("Incoming call: " + ic.isAnswered());
}
}
public class IncomingCall extends JDialog {
private static final long serialVersionUID = 1L;
private boolean answered;
private Timer timer;
public IncomingCall(JFrame frame, String title,
String sourcePhone, String destinationPhone) {
super(frame, true);
this.answered = false;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
add(createMainPanel(frame, sourcePhone, destinationPhone));
pack();
setLocationRelativeTo(frame);
timer = new Timer(15000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
timer.stop();
}
});
timer.start();
setVisible(true);
}
private JPanel createMainPanel(JFrame frame,
String sourcePhone, String destinationPhone) {
JPanel panel = new JPanel(new BorderLayout(5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
String s = "From: " + sourcePhone + " To: " + destinationPhone;
JLabel telephones = new JLabel(s);
panel.add(telephones, BorderLayout.BEFORE_FIRST_LINE);
JPanel callOptions = new JPanel();
CallButtonListener listener = new CallButtonListener(this);
JButton answerCall = new JButton("Answer");
answerCall.addActionListener(listener);
answerCall.setBackground(Color.GREEN);
callOptions.add(answerCall);
JButton denyCall = new JButton("Decline");
denyCall.addActionListener(listener);
denyCall.setBackground(Color.RED);
callOptions.add(denyCall);
panel.add(callOptions, BorderLayout.CENTER);
return panel;
}
public void setAnswered(boolean answered) {
this.answered = answered;
}
public boolean isAnswered() {
return answered;
}
}
public class CallButtonListener implements ActionListener {
private IncomingCall incomingCall;
public CallButtonListener(IncomingCall incomingCall) {
this.incomingCall = incomingCall;
}
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
if (button.getText().equals("Answer")) {
incomingCall.setAnswered(true);
} else {
incomingCall.setAnswered(false);
}
incomingCall.dispose();
}
}
}

Replace ImageIcon with JButton pressed

I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.

Java: Right Click Copy Cut Paste On TextField

I've made a program which prints a value in a text field. The problem is that when a user right clicks in the text field, a menu like this won't open:
Is there a way the user can have this menu open upon right click?
This is my code:
public class A extends JFrame{
private JTextField txt1;
private JTextField txt2;
private JLabel val;
private JLabel prt;
private JButton bt1;
public A() {
getContentPane().setLayout(null);
txt1 = new JTextField();
txt1.setBounds(178, 93, 87, 28);
getContentPane().add(txt1);
txt2 = new JTextField();
txt2.setBounds(178, 148, 87, 28);
getContentPane().add(txt2);
val = new JLabel("Enter Value");
val.setBounds(84, 93, 69, 28);
getContentPane().add(val);
prt = new JLabel("Printed Value");
prt.setBounds(80, 148, 87, 28);
getContentPane().add(prt);
bt1 = new JButton("Click This");
bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int n=Integer.parseInt(txt1.getText());
txt2.setText(n+"");
}
});
bt1.setBounds(178, 188, 105, 28);
getContentPane().add(bt1);
setSize(400, 399);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main Method:
public class Main {
public static void main(String[] args) {
A object = new A();
}
}
Read the Swing tutorial on How to Use Menus for the basics of creating a popup menu.
Then you can use the Actions provided by the DefaultEditorKit to create your popup menu.
For the "Delete" action you will need to create your own custom Action. Read the Swing tutorial on How to Use Actions for the basics. Except you would extend TextAction since it has methods that allow you to access the text component with focus so you can create reusable code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextFieldPopup extends JPanel
{
public TextFieldPopup()
{
JTextField textField = new JTextField(10);
add( textField );
JPopupMenu menu = new JPopupMenu();
Action cut = new DefaultEditorKit.CutAction();
cut.putValue(Action.NAME, "Cut");
cut.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control X"));
menu.add( cut );
Action copy = new DefaultEditorKit.CopyAction();
copy.putValue(Action.NAME, "Copy");
copy.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control C"));
menu.add( copy );
Action paste = new DefaultEditorKit.PasteAction();
paste.putValue(Action.NAME, "Paste");
paste.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control V"));
menu.add( paste );
Action selectAll = new SelectAll();
menu.add( selectAll );
textField.setComponentPopupMenu( menu );
}
static class SelectAll extends TextAction
{
public SelectAll()
{
super("Select All");
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.selectAll();
component.requestFocusInWindow();
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("TextFieldPopup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TextFieldPopup() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Static class to instantly add regular popup menu to a textfield.
import javax.swing.*;
import java.awt.event.ActionEvent;
import javax.swing.undo.*;
public class JTextFieldRegularPopupMenu {
public static void addTo(JTextField txtField)
{
JPopupMenu popup = new JPopupMenu();
UndoManager undoManager = new UndoManager();
txtField.getDocument().addUndoableEditListener(undoManager);
Action undoAction = new AbstractAction("Undo") {
#Override
public void actionPerformed(ActionEvent ae) {
if (undoManager.canUndo()) {
undoManager.undo();
}
else {
System.out.println("No Undo Buffer.");
}
}
};
Action copyAction = new AbstractAction("Copy") {
#Override
public void actionPerformed(ActionEvent ae) {
txtField.copy();
}
};
Action cutAction = new AbstractAction("Cut") {
#Override
public void actionPerformed(ActionEvent ae) {
txtField.cut();
}
};
Action pasteAction = new AbstractAction("Paste") {
#Override
public void actionPerformed(ActionEvent ae) {
txtField.paste();
}
};
Action selectAllAction = new AbstractAction("Select All") {
#Override
public void actionPerformed(ActionEvent ae) {
txtField.selectAll();
}
};
cutAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control X"));
copyAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control C"));
pasteAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control V"));
selectAllAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control A"));
popup.add (undoAction);
popup.addSeparator();
popup.add (cutAction);
popup.add (copyAction);
popup.add (pasteAction);
popup.addSeparator();
popup.add (selectAllAction);
txtField.setComponentPopupMenu(popup);
}
}
Usage:
JTextFieldRegularPopupMenu.addTo(jTxtMsg);
Instantly adds popup menu to the chosen JTextFIeld.
I'd start with How to use menus and Bringing Up a Popup Menu (although I'd personally use JComponent#setComponentPopupMenu instead of a MouseListener)
Then I'd have a look at JTextField#copy, JTextField#cut and JTextField#paste

GUI multiple frames switch

I am writing a program for a black jack game. It is an assignment we are not to use gui's but I am doing it for extra credit I have created two frames ant they are working. On the second frame I want to be able to switch back to the first when a button is pressed. How do I do this?
first window.............
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow1 extends JFrame implements ActionListener
{
private JButton play = new JButton("Play");
private JButton exit = new JButton("Exit");
private JPanel pane=new JPanel();
private JLabel lbl ;
public BlackJackWindow1()
{
super();
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
play = new JButton("Start");
exit = new JButton("exit");
lbl = new JLabel ("Welcome to Theodores Black Jack!!!!!");
add (lbl) ;
add(play, BorderLayout.CENTER);
play.addActionListener (this);
add(exit,BorderLayout.CENTER);
exit.addActionListener (this);
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow2 bl = new BlackJackWindow2();
if (event.getSource() == play)
{
bl.BlackJackWindow2();
}
else if(event.getSource() == exit){
System.exit(0);
}
}
second window....
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow2 extends JFrame implements ActionListener
{
private JButton hit ;
private JButton stay ;
private JButton back;
//private JLabel lbl;
public void BlackJackWindow2()
{
// TODO Auto-generated method stub
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
hit = new JButton("Hit");
stay = new JButton("stay");
back = new JButton("return to main menu");
// add (lbl) ;
add(hit, BorderLayout.CENTER);
hit.addActionListener (this) ;
add(stay,BorderLayout.CENTER);
stay.addActionListener (this) ;
add(back,BorderLayout.CENTER);
back.addActionListener (this) ;
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow1 bl = new BlackJackWindow1();
if (event.getSource() == hit)
{
//code for the game goes here i will complete later
}
else if(event.getSource() == stay){
//code for game goes here i will comeplete later.
}
else
{
//this is where i want the frame to close and go back to the original.
}
}
}
The second frame needs a reference to the first frame so that it can set the focus back to the first frame.
Also your classes extend JFrame but they are also creating other frames in their constructors.
A couple of suggestions:
You're adding components to a JPanel that uses FlowLayout but are using BorderLayout constants when doing this which you shouldn't do as it doesn't make sense:
add(play, BorderLayout.CENTER);
Rather, if using FlowLayout, just add the components without those constants.
Also, rather than swap JFrames, you might want to consider using a CardLayout and swapping veiws in a single JFrame. For instance:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooBarBazDriver {
private static final String INTRO = "intro";
private static final String GAME = "game";
private CardLayout cardlayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardlayout);
private IntroPanel introPanel = new IntroPanel();
private GamePanel gamePanel = new GamePanel();
public FooBarBazDriver() {
mainPanel.add(introPanel.getMainComponent(), INTRO);
mainPanel.add(gamePanel.getMainComponent(), GAME);
introPanel.addBazBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, GAME);
}
});
gamePanel.addBackBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, INTRO);
}
});
}
private JComponent getMainComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Foo Bar Baz");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FooBarBazDriver().getMainComponent());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class IntroPanel {
private JPanel mainPanel = new JPanel();
private JButton baz = new JButton("Baz");
private JButton exit = new JButton("Exit");
public IntroPanel() {
mainPanel.setLayout(new FlowLayout());
baz = new JButton("Start");
exit = new JButton("exit");
mainPanel.add(new JLabel("Hello World"));
mainPanel.add(baz);
mainPanel.add(exit);
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
});
}
public void addBazBtnActionListener(ActionListener listener) {
baz.addActionListener(listener);
}
public JComponent getMainComponent() {
return mainPanel;
}
}
class GamePanel {
private static final Dimension MAIN_SIZE = new Dimension(400, 200);
private JPanel mainPanel = new JPanel();
private JButton foo;
private JButton bar;
private JButton back;
public GamePanel() {
foo = new JButton("Foo");
bar = new JButton("Bar");
back = new JButton("return to main menu");
mainPanel.add(foo);
mainPanel.add(bar);
mainPanel.add(back);
mainPanel.setPreferredSize(MAIN_SIZE);
}
public JComponent getMainComponent() {
return mainPanel;
}
public void addBackBtnActionListener(ActionListener listener) {
back.addActionListener(listener);
}
}
Since I had to test it myself if it is in fact so easy to implement, I built this simple example. It demonstrates a solution to your problem. Slightly inspired by #jzd's answer (+1 for that).
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class FocusChangeTwoFrames
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createGUI();
}
});
}
private static void createGUI() throws HeadlessException
{
final JFrame f2 = new JFrame();
f2.getContentPane().setBackground(Color.GREEN);
final JFrame f1 = new JFrame();
f1.getContentPane().setBackground(Color.RED);
f1.setSize(400, 300);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
if(f1.hasFocus())
f2.requestFocus();
else
f1.requestFocus();
}
};
f1.addMouseListener(ml);
f2.setSize(400, 300);
f2.setLocation(200, 150);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setVisible(true);
f2.addMouseListener(ml);
}
}
Enjoy, Boro.

Categories