I'm trying to program my first GUI-class in Java, using the Window Builder. Ok, the GUI is ready but has no functions yet (it contains 10 checkboxes (yes, they are all neccessary) and 2 buttons and a JTextField, so nothing special). So I just drag'n'dropped the checkboxes and button into the window, I haven't coded anything yet.
I have two classes:
GUI.java -> only for the layout
Main.java -> should get 'inputs' from GUI.java
Now the user should check or uncheck the checkboxes and then finally press a button.
But how do I 'read out' if a checkbox is checked or not - I have two classes?
I have to add that I'm a beginner to Java and especially to GUI-programming, but I just want to learn it. I would be happy to receive some help but NOT the complete code.
Basically you instantiate an object of your GUI from the Main.java. Then you have access to this GUI (assumed you have setter/getter-methods or the Components in the GUI are public). In the GUI constructor you call all builder methods, so when you then call new GUI() from Main.java, you got a) the GUI running and b) access to it from Main.java
For your specific question about the checkboxes, you can call
nameOfCheckbox.isSelected()
which returns a boolean wheter the checkbox is checked or not.
Viceversa: since your Main.java has (or should have) static methods (like the main-method), you can then simply call Main.anyMethodName() from GUI.java (assuming this anyMethod is static) and pass data from the "visual area" to the "logic area" (it is recommended to seperate this two componentes as good as possible).
I know you said you didn't want the full, code but this isn't really it, just a very basic working demo of what you want to do
Gui.java
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Gui {
JFrame frame;
JButton button;
JCheckBox checkBox;
JLabel label;
public Gui() {
frame = new JFrame("demo");
button = new JButton("is it checked?");
checkBox = new JCheckBox();
label = new JLabel("no");
JPanel panel = new JPanel();
panel.add(checkBox);
panel.add(button);
panel.add(label);
frame.add(panel);
frame.pack();
//frame.setSize(200, 60);
frame.setResizable(false);
frame.setLocation(400, 400);
frame.setVisible(true);
}
// method to add an action listener to the gui's
// private button
public void setButtonActionListener(ActionListener al) {
button.addActionListener(al);
}
// gui method to check if box is checked
public boolean isBoxChecked() {
return checkBox.isSelected();
}
// method to set lable
public void setText(String text) {
label.setText(text);
}
}
Main.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
// create an instance of your gui class
final Gui gui = new Gui();
// add the action listener to the button
// notice how we reference the gui here by running the methods in the
// gui class
// this action listener could be created in the gui
// class but in general you don't want to do that because actions will
// involve multiple classes
gui.setButtonActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
gui.setText((gui.isBoxChecked() ? "yes" : "no"));
}
});
}
}
Attach an ItemListener.
You can determine if the box is rising (unchecked to checked) or falling (checked to unchecked) with the following line in itemStateChanged(ItemEvent e)
boolean selected = e.getStateChange() == ItemEvent.SELECTED;
To determine whether it is checked when it is not changing, just use isSelected()
Either like that:
checkbox.isSelected();
Or this would be a way by an Itemlistener which will be called if there is a change:
checkbox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
foo = false;
} else {
foo = true;
}
}
});
You could expose all of your gui objects as fields in your gui class
public JTextField getNameTextField() {
return nameTextField;
}
public JCheckBox getCheckBox1() {
return checkBox1;
}
and then in main:
if (gui.getCheckBox1().isSelected())
// do stuff
Assuming your checkbox is an object named "myCheckBox", you can check if it's selected or not by using:
myCheckBox.isSelected()
Returns true if the checkbox is selected.
I reccomend you to check Java's tutorials on how to use the various GUI components, e.g:
http://docs.oracle.com/javase/tutorial/uiswing/components/button.html
Related
my question is: how do I get the object of my CustomPanel, so that I am able to access its fields (because in my real programm I have some more fields in there) and also am able to delete it from my ArrayList?
I don't know how I have to implement an ActionListener in the Class Window, to somehow get the Object in my Arraylist, which containes the button that got pressed.
Also I am wondering if I am somehow able to implement an ActionListener in the Class CustomPanel which can influence the behaviour of the Object which is an instance of my Class Window.
I have kind of the following code:
public class Window extends JFrame{
ArrayList<CustomPanel> aLCustomPanel = new ArrayList();
JPanel jp = new JPanel();
public Window() {
for(int i=0;i<5;i++){
aLCustomPanel.add(new CustomPanel());
//here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(){
button = new JButton("button");
this.add(button);
}
public JButton getButton(){
return this.button;
}
}
my Code is much longer and weirder, so I tried to extract the (for this question) importing things.
Thanks for any help in advance!
edit:
for example: I would like to delete the object from the ArrayList, of which the button got pressed.
//imagine this comment in above code
aLCustomPanel.get(aLCustomPanel.size()-1).getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button_IwantToDeleteYou(e); //here I want to remove the panel, containing the button that got pressed from the above ArrayList, which is located in Class Window
}
});
edit2:
added a missing bracket and fixed some mistakes, code should be ok now.
Your code contained a few "gaps", i.e. missing code, which I filled in, as follows:
Added calls to [JFrame] methods setDefaultCloseOperation() and pack() and setLocationByPlatform(). I suggest you refer to the javadoc for those methods in order to understand what they do.
I set a layout manager for jp class member variable in your Window class.
Yes, you need to register an ActionListener with the JButton in class CustomPanel and that listener should reside in your Window class - the one that extends JFrame.
Here is my rewrite of your code. Note that I changed the name of class Window to CusPanel so as to distinguish between your class and java.awt.Window class. Not that it makes a difference, I just prefer not to use names of classes from the JDK.
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
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.JPanel;
import javax.swing.WindowConstants;
public class CusPanel extends JFrame implements ActionListener {
private static final int COUNT = 5;
private ArrayList<CustomPanel> aLCustomPanel = new ArrayList<>();
private JPanel jp = new JPanel(new GridLayout(0, COUNT));
public CusPanel() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
for (int i = 0; i < COUNT; i++) {
aLCustomPanel.add(new CustomPanel(this));
// here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
pack();
setLocationByPlatform(true);
}
public void actionPerformed(ActionEvent actionEvent) {
Object source = actionEvent.getSource();
if (source instanceof JButton) {
JButton button = (JButton) source;
Container parent = button.getParent();
jp.remove(parent);
jp.invalidate();
jp.repaint();
pack();
// aLCustomPanel.remove(parent); <- optional
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new CusPanel().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(ActionListener parent) {
button = new JButton("button");
button.addActionListener(parent);
this.add(button);
}
public JButton getButton() {
return this.button;
}
}
Note that after removing a CustomPanel, the GUI components need to be laid out again and the JFrame should also be resized accordingly. Hence in the actionPerformed() method, I call invalidate(), then repaint() and then pack(). I also think that if you remove a CustomPanel from the GUI, you should also remove it from the ArrayList, but hey, I still don't understand why you want to do this although I obviously don't know the whole story behind you wanting to do this in the first place.
Of-course, since each button (and each CustomPanel) looks exactly the same, you can't really know which button was removed. Again, I assume you see the big picture whereas I don't.
I'm trying to find a way how to update a panel content after changing a state variable.
Concretely in the example below, there is simple JPanel inside JFrame with two buttons. When the app starts, its state variable ("window") equals "home" so home button should be invisible. After clicking on the page button the state variable change and so both buttons visibility should change after frame repainting. (i.e. the page button should disappear and the home button should appear).
In this case, it is possible to solve it without the state variable just using setVisibility() method for buttons. But in my app, I would like to have more JComponetns connected to the state variable. Is there a way how to do it?
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JPanelUpdateTest {
private JFrame frame;
private String window = "home";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JPanelUpdateTest window = new JPanelUpdateTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JPanelUpdateTest() {
initialize();
}
private void initialize() {
frame = new JFrame("JPanelUpdateTest");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnHome = new JButton("home");
btnHome.setVisible(window == "home" ? false : true);
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
window = "page";
panel.revalidate();
frame.repaint();
}
});
panel.add(btnHome);
JButton btnPage = new JButton("page");
btnPage.setVisible(window == "page" ? false : true);
btnPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window = "home";
panel.revalidate();
frame.repaint();
}
});
panel.add(btnPage);
}
}
The problem is that initialize is only being called once, at object creation, and it should only be called once, and because of this the setVisible(...) code is not being called from the ActionListeners. Instead you need to put the mechanisms for changing the views within the ActionListeners themselves, not just changing state, not unless you are using a "bound property" and PropertyChangeListeners.
Myself, I'd recommend using a CardLayout to assist you in your swapping, and rather than directly changing Strings, call a public method of your class -- planning for when and if the ActionListener (controller) code is ever removed from the view class.
Also, regarding:
btnPage.setVisible(window == "page" ? false : true);
don't compare Strings using == or !=. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
Also, if all you want to do is change the text and behavior that a JButton is doing, then you can change this easily by using setText(...) to change only the text, and for a deeper change, call setAction(Action action) to change text and state.
I have an assignment to write a program that has three buttons, each displaying a different text that when pressed will display the text on the button in a text box. I think I have the basics of the program down but I can't get it to run. I've tried watching tutorials and reading up on the error I've been getting but I can't seem to figure it out. I am new to programming in java and have been pretty confused throughout the whole course. Any help would be greatly appreciated!
right now my errors are:
non-static variable this cannot be referenced from a static context
objButton1.addActionListener(this);
non-static variable this cannot be referenced from a static context
objButton2.addActionListener(this);
non-static variable this cannot be referenced from a static context
objButton3.addActionListener(this);
cannot find symbol
if (e.getSource()==objButton1)
cannot find symbol
else if (e.getSource()==objButton2)
import java.applet.Applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Option3 extends Frame implements ActionListener
{
Option3()
{
setTitle("Option 3");
setSize (300,300);
show();
}
public static void main (String args[])
{
Frame objFrame;
Button objButton1;
Button objButton2;
Button objButton3;
TextField objTextField;
objFrame = new Option3();
objButton1 = new Button("A");
objButton2 = new Button("B");
objButton3 = new Button("C");
objTextField = new TextField(100);
objButton1.addActionListener(this);
objButton2.addActionListener(this);
objButton3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == objButton1 )
System.out.println("A");
else if (e.getSource() == objButton2 )
System.out.println("B");
else
System.out.println("C");
}
}
There are a couple of things you need to change in order to make this work.
1) If you want to access the buttons in the actionPerformed(...) method, you need to increase their scope. As it is now, those variables can be accessed only in the main(...) method.
2) You need to pass an instance of ActionListener to the addActionListener(...) method and because main(...) is a static method, you can't use the this keyword, what you can do is to use the Option3 instance that you've just created or a better solution will be to create those components inside the Option3 constructor where you can use this.
3) If you want to display the components you've created, you need to add them to the frame.
import java.applet.Applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Option3 extends Frame implements ActionListener {
Button objButton1;
Button objButton2;
Button objButton3;
TextField objTextField;
Option3() {
setTitle("Option 3");
setSize (300,300); // is better to control the frame's size by using panels with appropriate layout managers.
objButton1 = new Button("A");
objButton2 = new Button("B");
objButton3 = new Button("C");
objTextField = new TextField(100);
objButton1.addActionListener(this);
objButton2.addActionListener(this);
objButton3.addActionListener(this);
Panel panel = new Panel(); // set a layout to this panel based on how you want the components to be displayed.
panel.add(objButton1);
panel.add(objButton2);
panel.add(objButton3);
panel.add(objTextField);
add(panel);
show();
}
public static void main (String args[]) {
Frame objFrame = new Option3();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == objButton1 ) { //delimit this kind of statements using curly braces to avoid confusion and bugs.
System.out.println("A");
} else if (e.getSource() == objButton2 ) {
System.out.println("B");
} else {
System.out.println("C");
}
}
}
I have a code that opens up a JOptionPane dialog box once the user hits a button. The first thing I want to do is close the first JFrame as soon as the user hits one of the buttons. I have tried doing this
setVisible(false); // Delete visibility
dispose(); //Delete window
but the original JFrame doesn't close as soon as a button is pressed. The goal is to have two buttons. When one is pressed, show a JOptionPane box, while simultaneously closing the first JFrame window. How can I do that? Next, after the ok is pushed in the new JOptionPane I wan't to stimulate what would be an action listener. I do this by calling the method
sinceyoupressedthecoolbutton();
right after my JOptionPane declaration. Here is where the second issue starts, it displays the JOptionPane perfectly, but doesn't go to the method
sinceyoupressedthecoolbutton();
I don't know if the problem is in the method calling or the content of the method. Basically, after ok is pressed on the JOptionPane, I wan't to move to another method, which opens a new JLabel.
Here is the code:
package Buttons;
import java.awt.Dimension;
import java.awt.FlowLayout; //layout proper
import java.awt.event.ActionListener; //Waits for users action
import java.awt.event.ActionEvent; //Users action
import javax.swing.JFrame; //Window
import javax.swing.JLabel;
import javax.swing.JButton; //BUTTON!!!
import javax.swing.JDialog;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane; //Standard dialogue box
public class ButtonClass extends JFrame {
private JButton regular;
private JButton custom;
public ButtonClass() { // Constructor
super("The title"); // Title
setLayout(new FlowLayout()); // Default layout
regular = new JButton("Regular Button");
add(regular);
custom = new JButton("Custom", b);
add(custom);
Handlerclass handler = new Handlerclass();
Otherhandlerclass original = new Otherhandlerclass();
regular.addActionListener(handler);
custom.addActionListener(original);
//THIS WAS MY FIRST PROBLEM, I WANT TO CLOSE THE FIRST JFRAME WINDOW AS THE USER HITS OK
setVisible(false); // Close the show message dialog box
dispose();
}
public class Handlerclass implements ActionListener { // This class is
// inside the other
// class
public void actionPerformed(ActionEvent eventvar) { // This will happen
// when button is
// clicked
JOptionPane.showMessageDialog(null, String.format("%s", eventvar.getActionCommand())); //opens a new window with the name of the button
}
}
public class Otherhandlerclass implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Since you pressed that button, I will open a new window when you press ok, okay?");
//Code works up until here
sinceyoupressedthecoolbutton(); //THIS METHOD SHOULD OPEN A NEW WINDOW!
}
public void sinceyoupressedthecoolbutton() {
JDialog YES = new JDialog();
JLabel label = new JLabel("Here is that new window I promised you!");
add(label);
YES.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
YES.setSize(500, 500);
YES.setVisible(true);
}
public class okay implements ActionListener {
public void actionPerformed(ActionEvent ok) {
}
}
}
}
Help would be appreciated!
You're working in a Event Driven Environment, not a linear processing one. This means that you run some code and then wait (the waiting is done for you) for some event to occur and then you respond to it...
Nothing can happen till the user presses the custom button, so it's pointless trying to close the frame before then
When your Otherhandlerclass's actionPerformed is triggered, obviously you show the JOptionPane pane, this will block the flow of the execution until it's closed. At this point, you should have the opportunity to the dispose of the original window.
So instead of calling setVisible(false) and dispose in your constructor, it would be better to move it to Otherhandlerclass
public class Otherhandlerclass implements ActionListener {
public void actionPerformed(ActionEvent e) {
dispose();
JOptionPane.showMessageDialog(null, "Since you pressed that button, I will open a new window when you press ok, okay?");
sinceyoupressedthecoolbutton();
}
public void sinceyoupressedthecoolbutton() {
JDialog YES = new JDialog();
JLabel label = new JLabel("Here is that new window I promised you!");
YES.add(label);
YES.setSize(500, 500);
YES.setVisible(true);
}
public class okay implements ActionListener {
public void actionPerformed(ActionEvent ok) {
}
}
}
Having said that, I'd encourage you to have a read of The Use of Multiple JFrames, Good/Bad Practice? and maybe consider using something like How to Use CardLayout instead
I have two Jframes where frame1 has some text fields and when a button on frame1 is clicked, I open another JFrame which contains a search box and a JTable containing search results.
When I click on a result row on JTable, I want that particular values to be reflected in the frame1 text fields.
I tried passing the JFrame1's object as a parameter but I have no clear idea on how to achieve this.
Any help would be highly appreciated.
Thanks
First of all, your program design seems a bit off, as if you are using a JFrame for one of your windows where you should in fact be using a JDialog since it sounds as if one window should be dependent upon the other.
But regardless, you pass references of GUI objects the same as you would standard non-GUI Java code. If one window opens the other (the second often being the dialog), then the first window usually already holds a reference to the second window and can call methods off of it. The key often is when to have the first window call the second's methods to get its state. If the second is a modal dialog, then the when is easy -- immediately after the dialog returns which will be in the code immediately after you set the second dialog visible. If it is not a modal dialog, then you probably want to use a listener of some sort to know when to extract the information.
Having said this, the details will all depend on your program structure, and you'll need to tell us more about this if you want more specific help.
For a simple example that has one window open another, allows the user to enter text into the dialog windows JTextField, and then places the text in the first window's JTextField, please have a look at this:
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WindowCommunication {
private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;
public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);
add(field);
add(openDialogeBtn);
}
private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}
class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");
public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}
// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}
// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}
You'd do a very similar technique to get information out of a JTable.
And again, if this information doesn't help you, then please tell us more about your program including showing us some of your code. The best code to show is a small compilable example, an SSCCE similar to what I've posted above.