JPanel How to make button work? - java

As you read this code, you will realize I got one action event to work, it opens up a new JPanel that displays the button that will run the ballBounce, but for now im stuck trying to get a working button within that frame because that frame is already within a actionEvent, any help?
public class MainJPanelOperation
{
public static void main(String[] a)
{
JPanel panel1 = new JPanel(new GridLayout(5, 10, 1, 1));
JButton t1 = new JButton();
JButton t2 = new JButton();
JButton letsStart = new JButton("Start The Program!");
JButton t3 = new JButton();
JButton t4 = new JButton();
//letsStart.setBounds(200,250,12,12);
panel1.add(t1);
panel1.add(t2);
panel1.add(letsStart);
panel1.add(t3);
panel1.add(t4);
final JFrame frame1 = new JFrame("Game");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(panel1);
frame1.setSize(1000,1000);
frame1.setVisible(true);
t1.setVisible(false);
t2.setVisible(false);
t3.setVisible(false);
t4.setVisible(false);
letsStart.setBackground(Color.yellow);
panel1.setBackground(Color.black);
letsStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("panel 2 main menu intro online");
JPanel panelMM = new JPanel(new GridLayout(5, 10, 1, 0));
JButton MM1 = new JButton("BallBounce");
panelMM.add(MM1);
JFrame frameMM = new JFrame("Game/Main Menu");
frameMM.add(panelMM);
frameMM.setSize(1000,1000);
frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameMM.setVisible(true);
frame1.setVisible(false);
}
});//end of start sequence
}
}

JPanel panelMM = new JPanel(new GridLayout(5, 10, 1, 0));
JButton MM1 = new JButton("BallBounce");
panelMM.add(MM1);
final JFrame frameMM = new JFrame("Game/Main Menu");
frameMM.add(panelMM);
frameMM.setSize(1000,1000);
frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
letsStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("panel 2 main menu intro
frameMM.setVisible(true);
frame1.setVisible(false);
}
});
You can make frameMM final and there is no need to have all of your code inside the ActionListener.

Try This :it is working inside a Action Listener.
JButton MM1 = new JButton("BallBoe");
MM1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("panel 2");
}
});
or class MainJPanelOperation implements ActionListener
You can use class MainJPanelOperation
{
static JButton MM1;
//your code
}
MM1=new JButton("Button");
MM1.addActionListener(this);
write a Method outside Main()
public void ActionPerformed(ActionEvent e)
{
if(e.getSource()==MM1)
{
System.out.print("");
}
if(e.getSource()==Buttonobject)
{
//your code for button Pressing Event
}
}

Related

Java - Blank window

I am newbie to Java. My following code give me a blank window.
Anyone can help me with what is going on ?
I am thinking that the error is at the ActionListeners.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Listeners");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
JTextArea txtArea = new JTextArea();
HelloActionListener hlisten = new HelloActionListener(txtArea);
JButton bl = new JButton("TOP");
bl.addActionListener((ActionListener) hlisten);
JButton b2 = new JButton("LEFT");
ActionListener rightListener = (ActionEvent e) -> {
txtArea.setText("Yes,let's go Left");
};
b2.addActionListener(rightListener);
JButton b3 = new JButton("RIGHT");
b3.addActionListener((ActionEvent e) -> {
txtArea.setText("Sorry, we cant go Right");
});
JButton b4 = new JButton("Bottom");
b4.addActionListener((ActionListener) hlisten);
frame.add(bl, BorderLayout.PAGE_START);
frame.add(b2, BorderLayout.LINE_START);
frame.add(b3, BorderLayout.LINE_END);
frame.add(b4, BorderLayout.PAGE_END);
frame.add(txtArea, BorderLayout.CENTER);
frame.setVisible(true);
}
Say you want to put "Hello" in your text area when the top button is pressed. Then you need to define your HelloActionListener as below:
private static class HelloActionListener implements ActionListener {
private JTextArea textArea;
public HelloActionListener(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void actionPerformed(ActionEvent e) {
textArea.setText("Hello");
}
}
The rest of your code is kind of messy but should work, however, you don't need to make the frame to be visible twice.
UPDATE
But I do think your code should be something like this:
public class MyApplication extends JFrame {
public MyApplication() {
setTitle("Listeners");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextArea txtArea = new JTextArea();
HelloActionListener hlisten = new HelloActionListener(txtArea);
JButton bl = new JButton("TOP");
bl.addActionListener(hlisten);
JButton b2 = new JButton("LEFT");
ActionListener rightListener = e -> {
txtArea.setText("Yes,let's go Left");
};
b2.addActionListener(rightListener);
JButton b3 = new JButton("RIGHT");
b3.addActionListener(e -> {
txtArea.setText("Sorry, we cant go Right");
});
JButton b4 = new JButton("Bottom");
b4.addActionListener(hlisten);
add(bl, BorderLayout.PAGE_START);
add(b2, BorderLayout.LINE_START);
add(b3, BorderLayout.LINE_END);
add(b4, BorderLayout.PAGE_END);
add(txtArea, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new MyApplication();
frame.pack();
frame.setVisible(true);
});
}
private class HelloActionListener implements ActionListener {
private JTextArea textArea;
public HelloActionListener(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
textArea.setText("Hello from " + button.getText());
}
}
}
There is no need for the first frame.setVisible(true); in your code - you are calling that again right at the end. But your panels are all zero size. You need to call frame.pack(); before you set it visible. Note also that all of that (the GUI stuff) should be done from the Event Dispatch Thread, not from your main thread.

Why aren't the JButtons displayed on the JFrame?

When I run the program the window and all it's properties are right, but the buttons won't show up, any idea of what I've done wrong?
I have two classes window and TimeTable0:
Here's window:
package timetable0;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class window extends JFrame {
JButton bt1,bt2,bt3,bt4 = new JButton();
JPanel panel = new JPanel();
public void ventana() {
setResizable(false);
setTitle("Time Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,550);
setVisible(true);
bt1.setText("Show Grades");
bt2.setText("Show Time Table");
bt3.setText("");
bt4.setText("");
panel.add(bt1);
panel.add(bt2);
panel.add(bt3);
panel.add(bt4);
}
public void actions (){
bt1.addActionListener((ActionEvent e) -> {
System.out.println("");
});
bt2.addActionListener((ActionEvent e) -> {
System.out.println("");
});
bt3.addActionListener((ActionEvent e) -> {
System.out.println("");
});
bt4.addActionListener((ActionEvent e) -> {
System.out.println("");
});
}
}
And here's TimeTable0:
package timetable0;
public class TimeTable0 {
public static void main(String[] args) {
window menu = new window();
menu.ventana();
menu.actions();
}
}
You aren't adding the JPanel to the frame.
panel.add(bt1);
panel.add(bt2);
panel.add(bt3);
panel.add(bt4);
setContentPane(panel);
You aren't running the program on the Event Dispatch Thread:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
window menu = new window();
menu.ventana();
menu.actions();
}
});
}
You aren't creating all four buttons:
JButton bt1 = new JButton();
JButton bt2 = new JButton();
JButton bt3 = new JButton();
JButton bt4 = new JButton();
I would have done it this way if you really want to extends your class to a JFrame.
public class Window extends JFrame {
JButton bt1,bt2,bt3,bt4; //Do initialization in the constructor, not here
JPanel panel;
public Window() {
createComponents();
addComponents();
initFrame();
}
private void createComponents(){
panel = new JPanel();
panel.setPreferredSize(new Dimension(800, 600));
bt1 = new JButton("Show Grades");
bt2 = new JButton("Show Time Table");
bt3 = new JButton("btn 3");
bt4 = new JButton("btn 4");
}
private void addComponents(){
panel.add(bt1);
panel.add(bt2);
panel.add(bt3);
panel.add(bt4);
add(panel);
}
private void initFrame(){
setResizable(false);
setTitle("Time Table");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
}
Usually I would prefer to extends a class to JPanel instead of extending it to JFrame. After that create a JFrame in the main() and add your customized JPanel into it.
You will need to initialize the buttons and add panel to the JFrame. Also, try moving the setVisible(true) statement to the end of the ventana() method so that it is displayed after the components are added.
public void Ventana() {
bt1 = new JButton("Show Grades");
bt2 = new JButton("Show Time Table");
bt3 = new JButton();
bt4 = new JButton();
...
panel.add(bt4);
add(panel);
setVisible(true); //moved from top
}
You didn't show much codes there, but you should at least try to do this instead:
Note that JButton bt1,bt2,bt3,bt4 = new JButton(); is different from writing it as below:
JButton bt1 = new JButton();
JButton bt2 = new JButton();
JButton bt3 = new JButton();
JButton bt4 = new JButton();
Doing JButton bt1,bt2,bt3,bt4 = new JButton();, you are only creating a JButton object for bt4 and not the rest.
You have also forgotten to add your JPanel into your JFrame.
add(panel); //Add panel to frame
Initialize buttons one by one:
JButton bt1 = new JButton();
JButton bt2 = new JButton();
JButton bt3 = new JButton();
JButton bt4 = new JButton();
Add panel to your frame after you add buttons to your panel:
panel.add(bt1);
panel.add(bt2);
panel.add(bt3);
panel.add(bt4);
setContentPane(panel);

Moving method after JButton selection

When I select the first option and hit select the JFrame stays as is and I want it to close and move into the next method being called and open a different JFrame. Can anyone see the problem? I can't figure out where I am going wrong
public class GUI extends JFrame
{
public static void main(String args [])
{
final JFrame frame = new JFrame("Choose an option");
frame.setSize(350, 180);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 0, 0));
final JRadioButton sb = new JRadioButton("Student");
final JRadioButton lb = new JRadioButton("Lecturer");
final JRadioButton cdb = new JRadioButton("Course Director");
final JRadioButton ab = new JRadioButton("Admin");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(sb);
buttonGroup.add(lb);
buttonGroup.add(cdb);
buttonGroup.add(ab);
JPanel panel = new JPanel();
panel.add(sb);
panel.add(lb);
panel.add(cdb);
panel.add(ab);
frame.getContentPane().add(panel);
panel.setLayout(new GridLayout(0, 1, 0, 0));
JButton select = new JButton("Select");
JButton cancel = new JButton("Cancel");
select.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(sb.isSelected())
{
frame.dispose();
StudentGUI();
}
else if(lb.isSelected())
System.out.println("Lecturer");
else if(cdb.isSelected())
System.out.println("Course Director");
else if(ab.isSelected())
System.out.println("Admin");
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JPanel panel2 = new JPanel();
panel2.add(select);
panel2.add(cancel);
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 0));
frame.getContentPane().add(panel2);
frame.setVisible(true);
}
public static void StudentGUI()
{
JFrame frame1 = new JFrame("Input Username");
frame1.setSize(350, 180);
frame1.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JTextField tf = new JTextField("Input username here");
JButton submit = new JButton("Submit");
JPanel panel1 = new JPanel();
panel1.add(tf);
panel1.add(submit);
frame1.getContentPane().add(panel1);
}
You forgot to set frame1.setVisible(true); in your StudentGUI method, and you never close the window in the first method (use yourframe.dispose()).
So try:
public void actionPerformed(ActionEvent e)
{
if(sb.isSelected())
StudentGUI();
else if(lb.isSelected())
System.out.println("Lecturer");
else if(cdb.isSelected())
System.out.println("Course Director");
else if(ab.isSelected())
System.out.println("Admin");
yourframe.dispose();//don't know your frame variable
}
public static void StudentGUI()
{
JFrame frame1 = new JFrame("Input Username");
frame1.setSize(350, 180);
frame1.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
//code omitted
}

Focus navigation in keyBinding

In my form, when i press ENTER button in my keyboard, the okAction() method should be invoke (and invoke perfectly).
My problem is in focus state, When i fill the text fields and then press the ENTER button, the okAction() didn't invoked, because the focus is on the second text field (not on the panel).
How fix this problem?
public class T3 extends JFrame implements ActionListener {
JButton cancelBtn, okBtn;
JLabel fNameLbl, lNameLbl, tempBtn;
JTextField fNameTf, lNameTf;
public T3() {
add(createForm(), BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new T3();
}
});
}
public JPanel createForm() {
JPanel panel = new JPanel();
panel.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Button");
panel.getActionMap().put("Button", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
okAction();
}
});
okBtn = new JButton("Ok");
okBtn.addActionListener(this);
cancelBtn = new JButton("Cancel");
tempBtn = new JLabel();
fNameLbl = new JLabel("First Name");
lNameLbl = new JLabel("Last Name");
fNameTf = new JTextField(10);
fNameTf.setName("FnTF");
lNameTf = new JTextField(10);
lNameTf.setName("LnTF");
panel.add(fNameLbl);
panel.add(fNameTf);
panel.add(lNameLbl);
panel.add(lNameTf);
panel.add(okBtn);
panel.add(cancelBtn);
panel.add(tempBtn);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 50, 10, 80, 60);
return panel;
}
private void okAction() {
if (fNameTf.getText().trim().length() != 0 && lNameTf.getText().trim().length() != 0) {
System.out.println("Data saved");
} else System.out.println("invalid data");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okBtn) {
okAction();
}
}
}
Declare a default button for your GUI's JRootPane:
public T3() {
//!! ..... etc...
setVisible(true);
getRootPane().setDefaultButton(okBtn);
}
In fact with a default button set, I don't see that you need to use key bindings.

Action Listener does not work on swing

I have a form , That when i click to save button, "Yes" String should display on my console!
(I use "Yes" String for test!)
But does not work when clicked.
My code:
public final class NewUserFrame1 extends JFrame implements ActionListener {
UserInformation userinfo;
JLabel fnamelbl;
JLabel lnamelbl;
JTextField fntf;
JTextField lntf;
JLabel gndlnl;
JRadioButton malerb;
JRadioButton femalerb;
ButtonGroup bgroup;
JLabel registnm;
JButton savebt;
JButton cancelbt;
JLabel showreglbl;
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
fnamelbl = new JLabel("First name");
lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
fntf = new JTextField(10);
lntf = new JTextField(10);
gndlnl = new JLabel("Gender");
malerb = new JRadioButton("Male");
femalerb = new JRadioButton("Female");
bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
registnm = new JLabel("Registration ID is:");
showreglbl = new JLabel("");
JLabel regtemp = new JLabel();
savebt = new JButton("Save");
cancelbt = new JButton("Cancell");
JLabel buttontemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
JPanel radiopanel = new JPanel();
radiopanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radiopanel.add(malerb);
radiopanel.add(femalerb);
panel.add(radiopanel);
panel.add(new JLabel());
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.add(savebt);
panel.add(cancelbt);
panel.add(buttontemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 5, 3, 50, 10, 80, 60);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == savebt) {
System.out.print("Yes");
}
}
}
You need to add an ActionListener to your button like so:
savebt.addActionListener(this);
or with an anonymous class, like so:
savebt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code.
}
});
Using anonymous classes (or inner classes) is better because you can't have more than one actionPerformed() method in a given class.
You need to tell the button to invoke the ActionListener:
savebt = new JButton("Save");
savebt.addActionListener(this);
Note if you intend to use the same method for the save and cancel buttons, you'll need to differentiate, perhaps by comparing the source of the ActionEvent against the two buttons.

Categories

Resources