I am trying to get the buttons to at least execute something when they are pressed and BlueJ doesn't show any errors, but when I execute the Program and I try to press the buttons, nothing happens. I am really unsure why that is the case. I would appreciate any help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MainMenu
{
JFrame frame= new JFrame();
JButton button = new JButton("Singleplayer");
JButton button2 = new JButton("Multiplayer");
MainMenu(){
prepareGUI();
}
public void prepareGUI(){
frame.setTitle("Game");
frame.getContentPane().setLayout(null);
frame.add(button);
frame.add(button2);
button.setBounds(100,200,100,40);
button2.setBounds(200,200,100,40);
frame.setVisible(true);
frame.setBounds(200,200,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setUpButtonListeners(){
ActionListener buttonlistener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.green);
System.out.println("Singleplayer Selected");
}
};
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame.getContentPane().setBackground(Color.red);
System.out.println("Multiplayer Selected");
}
};
button.addActionListener(buttonlistener);
button2.addActionListener(buttonlistener2);
}
public class MainClass {
public void main(String args[] )
{
new MainMenu();
}
}
}
setUpButtonListeners() are not executed in the program. So action listeners are not available. you can include setUpButtonListeners() in prepareGUI method.
Related
I want to make a window that when you press the buttons it will show the phrase "I Love You" in different language in the text area. I Just don't know how to connect the text area in the buttons. I have three classes. I tried many ways I could think and I also search the things related to this but I can't find any useful
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainClass {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
private ToolBar Tulbar = new ToolBar();
private JTextArea textArea = new JTextArea();
public MainFrame() {
super("This window loves you");
setLayout(new BorderLayout());
add(Tulbar, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ToolBar extends JPanel{
private JButton Button1 = new JButton("Korean");
private JButton Button2 = new JButton("Japanese");
private JButton Button3 = new JButton("French");
private JButton Button4 = new JButton("Italian");
private JButton Button5 = new JButton("English");
private JButton Button6 = new JButton("Tagalog");
public ToolBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
//added buttons
add(Button1);
add(Button2);
add(Button3);
add(Button4);
add(Button5);
add(Button6);
}
public ToolBar(JTextArea frame) {
Button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Saranghae");
}
});
Button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Aishiteru");
}
});
Button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Je t\'aime");
}
});
Button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Ti\'amo");
}
});
Button5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("I Love You");
}
});
Button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Mahal Kita");
}
});
}
}
Since you are calling Button1.addActionListener in public ToolBar(JTextArea frame) constructor, you should invoke this constructor to invoke the code in it. But instead you are invoking public ToolBar() constructor.
To fix this instead of:
private ToolBar Tulbar = new ToolBar();
private JTextArea textArea = new JTextArea();
you should write:
private JTextArea textArea = new JTextArea();
private ToolBar Tulbar = new ToolBar(textArea);
and in ToolBar fix the constructors, instead of:
public ToolBar() {
// ... STUFF 1 ...
}
public ToolBar(JTextArea frame) {
// ... STUFF 2 ...
}
you should write:
public ToolBar(JTextArea frame) {
// ... STUFF 1 ...
// ... STUFF 2 ...
}
or
public ToolBar() {
// ... STUFF 1 ...
}
public ToolBar(JTextArea frame) {
this();
// ... STUFF 2 ...
}
Please learn Java Naming Conventions and use it all the time. You probably don't think it's important, but I promise it will save you from making stupid mistakes, and will save your time fixing them.
So I am trying to make a menu in swing of 8 functions. This code i have right now.
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Menu extends JFrame {
public Menu(){
init();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
Menu menu = new Menu();
menu.setVisible(true);
}
});
}
private void init() {
setTitle("Group 2");
setSize(300, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton quitButton = new JButton("E(X)it");
quitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
createLayout(quitButton);
JButton nameAsk = new JButton("What is your name?");
nameAsk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
}
});
createLayout(nameAsk);
}
private void createLayout(JComponent... arg){
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(arg[0]));
gl.setVerticalGroup(gl.createSequentialGroup().addComponent(arg[0]));
}
}
The problem is when i add one more button the other one goes away. I think its on top of other button but i am confused now.
There are two buttons in my ui which re-directs to two JFrames. I am trying to make that if user press button one, button two becomes disabled, and if the user presses button two, button one becomes disabled, so that the user cannot open both the JFrames at the same time.
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class Main extends JFrame {
public Main() {
JPanel panel = new JPanel();
getContentPane().add (panel,BorderLayout.NORTH);
JButton button1 = new JButton("One");
panel.add(button1);
JButton button2 = new JButton("Two");
panel.add(button2);
button1.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
button2.setEnabled(false);
One f = new One();
f.setSize(350,100);
f.setVisible(true);
}
});
button2.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
button1.setEnabled(false);
Two fr = new Two();
fr.setSize(350,100);
fr.setVisible(true);
}
});
public void enableButtons()
{
button1.setEnabled(true);
button2.setEnabled(true);
}
}
public static void main(String[] args) {
Main frame = new Main();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
enableButtons();
System.exit(0);
}
});
frame.setSize(300,200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
In your ActionListener for Button One, add
ButtonTwo.setEnabled(false);
and in the ActionListenerfor Button Two add
ButtonOne.setEnabled(false);
Don't forget to add the corresponding enables (button.setEnable(true)) otherwise you will be left with two disabled buttons. Maybe in an event for closing the JFrames.
EDIT:
You can write a method like this
public void enableButtons()
{
button1.setEnabled(true);
button2.setEnabled(true);
}
Call this method in an event of JFrame closing.
This tutorial explains the JFrame closing event.
Check out the ButtonGroup for a more elegant solution.
http://docs.oracle.com/javase/tutorial/uiswing/components/buttongroup.html
I've got a Frame (named here "MainApplication"), which mainly has a JPanel to show informations, depending on the context.
On startup, the MainApplication has an empty JPanel.
It then creates a "LoginRequest" class, which creates a simple login/password form, and send it back to the MainApplication, which displays it in its JPanel.
The "LoginRequest" class implements ActionListener, so when the user clicks on the "Login" button, it checks wheter or not the login/password is correct, and, if the user is granted, I want to unload that form, and display the main screen on the MainApplication Frame.
So, to do it, I came up with this :
public class LoginRequest implements ActionListener {
protected MainApplication owner_m = null;
public LoginRequest(MainApplication owner_p) {
owner_m = owner_p;
}
#Override
public void actionPerformed(ActionEvent event_p) {
// the user just clicked the "Login" button
if (event_p.getActionCommand().equals("RequestLogin")) {
// check if login/password are correct
if (getParameters().isUserGranted(login_l, password_l)) {
// send an ActionEvent to the "MainApplication", so as it will
// be notified to display the next screen
this.owner_m.actionPerformed(
new java.awt.event.ActionEvent(this, 0, "ShowSummary")
);
} else {
messageLabel_m.setForeground(Color.RED);
messageLabel_m.setText("Incorrect user or password");
}
}
}
}
Then, the "MainApplication" class (which extends JFrame) :
public class MainApplication extends JFrame implements ActionListener {
protected void load() {
// create the panel to display information
mainPanel_m = new JPanel();
// on startup, populate the panel with a login/password form
mainPanel_m.add(new LoginRequest(this).getLoginForm());
this.add(mainPanel_m);
}
#Override
public void actionPerformed(ActionEvent event_p) {
// show summary on request
if (event_p.getActionCommand().equals("ShowSummary")) {
// remove the previous information on the panel
// (which displayed the login form on this example)
mainPanel_m.removeAll();
// and populate the panel with other informations, from another class
mainPanel_m.add(...);
...
...
}
// and then refresh GUI
this.validate();
this.repaint();
this.pack();
}
}
When the ActionEvent is sent from the "LoginRequest" class to the "MainApplication" class, it executes the code, but at the end, nothing happens, as if the JFrame wasn't repainted.
Any ideas ?
Thanks,
The best way would be to use JDialog (main frame JFrame would be a parent component) for login form and CardLayout to switch between panels (so there is no need for removing, repainting and revalidating):
Your main form should look something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel welcomePanel = new JPanel();
JPanel workspacePanel = new JPanel();
JPanel cardPanel = new JPanel();
JButton btnLogin = new JButton("Login");
JLabel lblWelcome = new JLabel("Welcome to workspace");
CardLayout cl = new CardLayout();
LoginRequest lr = new LoginRequest(this);
public MainFrame() {
welcomePanel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lr.setVisible(true);
}
});
workspacePanel.add(lblWelcome);
cardPanel.setLayout(cl);
cardPanel.add(welcomePanel, "1");
cardPanel.add(workspacePanel, "2");
cl.show(cardPanel,"1");
frame.getContentPane().add(cardPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Your login form should look something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginRequest extends JDialog{
/**You can add, JTextFields, JLabel, JPasswordField..**/
JPanel panel = new JPanel();
JButton btnLogin = new JButton("Login");
public LoginRequest(final MainFrame mf) {
setTitle("Login");
panel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Put some login logic here
mf.cl.show(mf.cardPanel,"2");
dispose();
}
});
add(panel, BorderLayout.CENTER);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
}
EDIT:
Your way:
MainFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel welcomePanel = new JPanel();
JPanel workspacePanel = new JPanel();
JPanel cardPanel = new JPanel();
JButton btnLogin = new JButton("Login");
JLabel lblWelcome = new JLabel("Welcome");
LoginRequest lr = new LoginRequest(this);
public MainFrame() {
welcomePanel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lr.setVisible(true);
}
});
workspacePanel.add(lblWelcome);
frame.getContentPane().add(welcomePanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
LoginRequest class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginRequest extends JDialog{
/**You can add, JTextFields, JLabel, JPasswordField..**/
JPanel panel = new JPanel();
JButton btnLogin = new JButton("Login");
public LoginRequest(final MainFrame mf) {
setTitle("Login");
panel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Put some login logic here
mf.frame.getContentPane().removeAll();
mf.frame.add(mf.workspacePanel);
mf.frame.repaint();
mf.frame.revalidate();
dispose();
}
});
add(panel, BorderLayout.CENTER);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
}
I'm learning Swing class now and everything about it. I've got this toy program I've been putting together that prompts for a name and then presents a JOptionPane with the message "You've entered (Your Name)".
The submit button I use can only be clicked on, but I'd like to get it to work with the Enter button too. I've tried adding a KeyListener, as is recommended in the Java book I'm using (Eventful Java, Bruce Danyluk and Murtagh).
This is my code:
import java.awt.BorderLayout;
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;
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName));
submit.addKeyListener(new SubmitButton(textBoxToEnterName));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
And this is the actionListener, keyListener class:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SubmitButton implements ActionListener, KeyListener {
JTextField nameInput;
public SubmitButton(JTextField textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
}
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
There is a simple trick for this. After you constructed the frame with all it buttons do this:
frame.getRootPane().setDefaultButton(submitButton);
For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.
And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
}
}
UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:
SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);
You can use the top level containers root pane to set a default button, which will allow it to respond to the enter.
SwingUtilities.getRootPane(submitButton).setDefaultButton(submitButton);
This, of course, assumes you've added the button to a valid container ;)
UPDATED
This is a basic example using the JRootPane#setDefaultButton and key bindings API
public class DefaultButton {
public static void main(String[] args) {
new DefaultButton();
}
public DefaultButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton button;
private JLabel label;
private int count;
public TestPane() {
label = new JLabel("Press the button");
button = new JButton("Press me");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
gbc.gridy++;
add(new JButton("No Action Here"), gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
InputMap im = button.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = button.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "spaced");
am.put("spaced", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
}
#Override
public void addNotify() {
super.addNotify();
SwingUtilities.getRootPane(button).setDefaultButton(button);
}
protected void doButtonPressed(ActionEvent evt) {
count++;
label.setText("Pressed " + count + " times");
}
}
}
This of course, assumes that the component with focus does not consume the key event in question (like the second button consuming the space or enter keys
In the ActionListener Class you can simply add
public void actionPerformed(ActionEvent event) {
if (event.getSource()==textField){
textButton.doClick();
}
else if (event.getSource()==textButton) {
//do something
}
}
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
Without a frame this works for me:
JTextField tf = new JTextField(20);
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
String[] options = {"Ok", "Cancel"};
int result = JOptionPane.showOptionDialog(
null, tf, "Enter your message",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,0);
message = tf.getText();
I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key
textField_in = new JTextField();
textField_in.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getExtendedKeyCode());
if (arg0.getKeyCode()==10) {
String name = textField_in.getText();
textField_out.setText(name);
}
}
});
textField_in.setBounds(173, 40, 86, 20);
frame.getContentPane().add(textField_in);
textField_in.setColumns(10);