I have two java classes: Menu and PMotion. The Menu class contains a JButton as shown below. When this JButton is pressed, I want it to go to PMotion.java
How to achieve this?
Menu.java
public void actionPerformed(ActionEvent e) {
// Here I need to write the code which takes the user to PMotion.java
}
Here's a sample on how to open a new JFrame using a JButton.
JButton show = new JButton("show Form2");
show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
PMotion pMotion = new PMotion();
pMotion.setVisibile(true); // Show pMotion form
Form1.this.setVisible(false); // Hide current form where Form1 is your current JFrame class
}
});
Related
I'm curious how can I use a dialog designer that is built into IntelliJ IDEA since I find it an option with big potential but I don't really know how to use it.
Let's consider a desktop program with two classes created using designer: MainWindow and MainDialog. Let's assume that MainWindow class already has all fields, components etc. required for a simple form to be displayed. Then in the MainWindow class we have:
JLabel label = new JLabel("This is default text");
JButton showDialog = new JButton("Show dialog");
showDialog.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
MainDialog dialog = new MainDialog ();
dialog.pack();
dialog.setVisible(true);
}
});
which makes the dialog visible. The MainDialog class designed by default by designer looks like this:
public class MainDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
public MainDialog() {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
private void onOK() {
// add your code here
dispose();
}
private void onCancel() {
// add your code here if necessary
dispose();
}
}
Now let's also assume that in the dialog class I have a text field:
JTextField textField = new JTextField();
that I am getting a text to be displayed by label in the MainWindow class from.
Since I have an onOK() function created by default I'd like it to update a label in MainWindow class with text typed in text field in MainDialog class.
The problem is: how can I perform an action on another class's field using this pattern without writing in MainDialog a line MainWindow window = new MainWindow or making label static? Is it possible? I know that this can be done much simpler but this is also an easy example and I'd like to perform much more complex operations using this structure.
Yes, it's possible.
First option: since the dialog is modal, the code opening the modal in the main window will be blocked until the dialog is closed. So you could just do something like this in the modal:
public String getEnteredText() {
return textField.getText();
}
and in the main window:
dialog.setVisible(true);
myLabel.setText(dialog.getEnteredText());
Or (but I would use the first option), you can pass the main window, or any other callback, to the dialog. For example:
MainDialog dialog = new MainDialog(this);
And in the dialog:
private void onOK() {
mainWindow.setLabelText(textField.getText());
dispose();
}
My recommendation is to avoid UI designers. Especially if you're not able yet to write the code that they generate by yourself, and you don't have a deep understanding of how Swing works.
I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});
I have the following code. How would I make a textbox displaying the text on each button come up when that button is pushed? I'm taking a beginning java class online that gives little to no instruction and then asks me to do stuff like this, so any and all help is very much appreciated. I want to learn! Thank You!
import java.awt.*;
public class FinalProj2 extends Frame
{
FinalProj2()
{
setTitle("Buttons");
setSize(600,600);
show();
}
public static void main(String args[])
{
Frame objFrame;
Button objButton1;
Button objButton2;
Button objButton3;
Label objLabel2;
objFrame= new FinalProj2();
objButton1= new Button("Submit");
objButton2= new Button("Cancel");
objButton3= new Button("What Now");
objLabel2= new Label();
objButton1.setBounds(60,200,80,80);
objButton2.setBounds(150,300,80,80);
objButton3.setBounds(60,400,80,80);
objFrame.add(objButton2);
objFrame.add(objButton1);
objFrame.add(objButton3);
objFrame.add(objLabel2);
}
}
Attach an ActionListener using addActionListener() method on each of the buttons instances you need. In actionPerformed()method text in textbox
btn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
lbl.setText(btn.getLabel());
}
});
If I understand you correctly, You want that when you press any button then the button label should be displayed in TextField
For this you have to create an object of TextField like:
final TextField box = new TextField();
Then you can add ActionListener on that TextField like:
objButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
box.setText(objButton1.getLabel());
}
});
Same for other buttons.
I am creating an application that has 1 JFrame java file and 1 JDialog java file.
In the JFrame, I have a button and when pressed I want it to display what I have designed in the JDialog.
So for example, my JFrame java file is called MMainView.java and my JDialog is called OptionView.java. So when the button in MMainView.java is pressed I want to display the JDialog I have designed in OptionView.java.
So in my MMainView.java file, I have a function that is called when that button is pressed. How do I display the dialog in OptionView.java?
SOLVED
For those wondering. This is what I did:
private JDialog optionView; ~~> JDialog Declaration
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (optionView == null) {
JFrame mainFrame = myApp.getApplication().getMainFrame();
optionView = new OptionView(mainFrame, true);
optionView.setLocationRelativeTo(mainFrame);
}
myApp.getApplication().show(optionView);
}
Sounds like you want to create an ActionListener for your button, and set the visibility of the JDialog to true when you press the button.
Something on these lines:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionevent)
{
//set the visibility of the JDialog to true in here
}
});
Let's say your button is called myBtn.
The class should look like this.
public class MMainView extends JFrame
implements ActionListener
You should use a listener for the button.
JButton myBtn = new JButton();
myBtn.addActionListener(this);
And finally:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myBtn) {
new OptionView();
You don't really need the if, it's just in case you want to add more buttons for the actionPerformed.
First register the button in "MainView.java", like below.
b1.addActionListener(this);
b1.setName("OpenJDialog");
//this is to read in actionperformed method incase you have more than one button
// in action performed method call the dialogue class
public void actionPerformed(ActionEvent ae){
JButton jb = (JButton)ae.getSource();
String str = jb.getName();
if(str.equals("OpenJDialog"){
new OptionView();
//I am assuming u are configuring jdialog content in OptionView constructor
}
}
I have a various panels with various buttons. Some buttons should call a method initiating a search through an array list, other buttons should call methods that send information to different JTextArea boxes.
After adding an event listener for each button, how do I create specific actions depending on the button clicked in my actionPerformed method? Below is my code for various gui properties, as you can see there are 3 different JPanels, the buttons of each needing to perform different functions. I just need to know how to determine which button was clicked so I can link it to the appropriate method (already written in another class). Does this require an if statement? Can my other class access the buttons on the GUI if I make them public, or is there a more efficient way to do this.
JPanel foodOptions;
JButton[] button= new JButton[4]; //buttons to send selected object to info panel
static JComboBox[] box= new JComboBox[4];
JPanel search;
JLabel searchL ;
JTextField foodSearch;
JButton startSearch; //button to initialize search for typed food name
JTextArea searchInfo;
JPanel foodProfile;
JLabel foodLabel;
JTextArea foodInfo;
JButton addFood; //but to add food to consumed calories list
JPanel currentStatus;
JLabel foodsEaten;
JComboBox foodsToday;
JLabel calories;
JTextArea totalKCal;
JButton clearInfo; //button to clear food history
As per people's comments, you need to use listeners of some sort, here is a real basic example to get you started, however I would define your listeners elsewhere in most cases, rather than on the fly:
JButton startSearch = new JButton("startSearch");
JButton addFood = new JButton("addFood");
startSearch.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//DO SEARCH RELATED THINGS
}
});
addFood.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//DO FOOD ADD RELATED THINGS
}
});
Something like this:
JButton searchButton = new JButton("Start search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do some search here
}
});
JButton addFoodButton= new JButton("Add food");
addFoodButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// add your food
}
});
and so on. If you need to reuse an behaviour through multiple buttons, create a ActionListener instance instead of using anonymous classes and assign it multiple times to your buttons.
Well there any many ways to do that I guess. I suppose you can do the following:
public class Myclass implements ActionListener
{
private JButton b1,b2;
private MyClassWithMethods m = new MyClassWithMethods();
// now for example b1
b1 = new JButton("some action");
b1.setActionCommand("action1");
b1.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if ("action1".equals(e.getActionCommand()))
{
m.callMethod1();
} else {
// handle other actions here
}
}
}
And you can do the same for more buttons and test which action triggered the event and then call the appropriate methods from you class.