How to enable buttons at start of gui in Netbeans - java

This is not a duplicate as I already know the code .setEnabled(false);. My problem is that I am making a gui in netbeans and I cannot figure out how to disable/enable buttons. Obviously I am new to JAVA and Netbeans This is what I have to do:
Start the program with all buttons disabled except the Initialize
button.
When Initialize is pressed the ArrayList will be filled with 5 CD
titles. The Initialize button then becomes disabled and the other
buttons become enabled.
The only code I know for buttons is .setEnabled(false); but it only disables button after I click it and what i need is to make one enabled and rest disabled. After I click it, it should be disabled and rest should be enabled.
The current code is not relevant but if you need it I will edit this post! Any help is greatly appreciated and thank you in advance!

You need to use interface ActionListener and add ActionListener after clicking
of button. Implement default method ActionPerformed. Use this code as example.
import java.awt.*;
import java.awt.event.*;
class calc extends Frame implements ActionListener
{
TextField t1 =new TextField(20);
TextField t2 =new TextField(29);
TextField t3 =new TextField(29);
Label l1=new Label("first");
Label l2=new Label("second");
Label l3=new Label("sum");
Button b1=new Button("Add");
Button b2=new Button("close");
calc() //CONSTRUCTOR
{
add(l1);add(t1);
add(t2);add(l2);
add(t3);add(l3);
add(b1);
add(b2);
setSize(444,555);
setVisible(true);
setLayout(new FlowLayout());
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object o=e.getSource();
if(o==b2)
{
System.exit(1);
}
String n1=t1.getText();
String n2=t2.getText();
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
t3.setText(""+(a+b));
}
}
class Gi
{
public static void main(String[] args)
{
new calc();
}
}

Related

Add multiple actionListener to multiple JButtons

I am working on a GUI and trying to get different buttons to perform different tasks.
Currently, each button is leading to the same ActionListener.
public class GUIController {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(3,3));
JLabel leight =new JLabel("8");
frame.getContentPane().add(leight);
JLabel lfive =new JLabel("0");
frame.getContentPane().add(lfive);
JLabel lthree =new JLabel("0");
frame.getContentPane().add(lthree);
JButton beight =new JButton("Jug 8");
frame.getContentPane().add(beight);
JButton bfive =new JButton("Jug 5");
frame.getContentPane().add(bfive);
JButton bthree =new JButton("Jug 3");
frame.getContentPane().add(bthree);
LISTN ccal = new LISTN (leight,lfive,lthree);
beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);
frame.pack();
frame.setVisible(true);
}
}
my actionlistener file
public class JugPuzzleGUILISTN implements ActionListener {
JLabel leight;
JLabel lfive;
JLabel lthree;
JugPuzzleGUILISTN(JLabel leight,JLabel lfive, JLabel lthree){
this.leight = leight;
this.lfive = lfive;
this.lthree = lthree;
}
public void actionPerformed(ActionEvent e) {
}
}
}
Anything I write in ActionEvent applies to all three buttons, how can I make it so that each button has their own function?
Thank you so much!
how can I make it so that each button has their own function
Add a different ActionListener to each button.
Better yet, use an Action instead of an ActionListener. An Action is just a fancy ActionListener that has a few more properties.
Read the section from the Swing tutorial on How to Use Action for examples of defining inner classes so you can create a unique Action for each button.
Anything I write in ActionEvent applies to all three buttons, how can I make it so that each button has their own function?
You have similar actions which you want all the 3 buttons to be able to trigger. However you also have different functions which you want to implement for each button.
One of the ways will creating 3 more listeners, each to be added to their respective button. So each button now will be added with 2 listeners (your current one + newly created ones).
//Example:
beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);
beight.addActionListener(ccal_beight);
bfive.addActionListener(ccal_bfive);
bthree.addActionListener(ccal_bthree);
There are other ways such as using if-statements in your current listener to check which button is clicked, but I find separate listeners easier to maintain with lower code coupling.

how to create new window with swing when clicking JButton

I need to create a bank account management program for school, I created the "skeleton" of the first page but I do not understand some things:
How to open a new window with Swing when I click a button?
How can I have different ActionListener for each button?
If I change strategy and I want to use just one big window and let appear and disappear the working text fields/Labels, how would I do it?
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class CreditUnion extends JFrame
{
//declare buttons
private JButton openAccount;
private JButton closeAccount;
private JButton makeLodgement;
private JButton makeWithdrawal;
private JButton requestOverdraft;
//constructor
public CreditUnion()
{
super("ATM#CreditUnion");
Container c = getContentPane();
c.setLayout(new FlowLayout() );
openAccount = new JButton("Open account");
c. add(openAccount);
closeAccount = new JButton("Close account");
c. add(closeAccount);
makeLodgement = new JButton("Make lodgement");
c. add(makeLodgement);
makeWithdrawal = new JButton("Make withdrawal");
c. add(makeWithdrawal);
requestOverdraft = new JButton("Request overdraft");
c. add(requestOverdraft);
/*create instance of inner class ButtonHandler
to use for button event handling*/
ButtonHandler handler = new ButtonHandler();
openAccount.addActionListener(handler);
closeAccount.addActionListener(handler);
makeLodgement.addActionListener(handler);
makeWithdrawal.addActionListener(handler);
requestOverdraft.addActionListener(handler);
setSize(800,600);
show();
}
public static void main (String args[])
{
CreditUnion app = new CreditUnion();
app.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
//inner class for button event handling
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JOptionPane.showMessageDialog(null, "You Pressed: " + e.getActionCommand() );
}
}
how to open a new window with Swing when I click a button?
Don't, use a CardLayout, it's less distracting to the user
Have a look at How to use CardLayout for more details
how can I have different ActionListener for each button?
You can use a separate class, inner class or anonymous class depending on what you to achieve
Have a look at Nested classes for more details
if I change strategy and I want to use just one big window and let appear and disappear the working Textfields/Labels, how would I do it
See the first point
1- how to open a new window with Swing when I click a button?
The same way that you would display any window. In the button's ActionListener, create a new window -- I would suggest that you create a JDialog and not a JFrame, but this will depend on your assignment requirements too, and display it
2- how can I have different ActionListener for each button?
Add a different ActionListener to each button. An anonymous inner class (search on this) would work great for this.
3- if I change strategy and I want to use just one big window and let appear and disappear the working Textfields/Labels, how would I do it?
Use a CardLayout to swap "views", usually JPanels with components that you want to swap.

JPopupMenu gets closed as soon as the mouse enters in an embedded JCheckboxMenuItem

I wrote the following code to have a JPopupMenu that allows multiple selection of different items.
The problem is that, as soon as the mouse enters one of the displayed JCheckboxMenuItems, the JPopupMenu gets closed. This issue doesn't occur if I replace JCheckboxMenuItem with, for example, JLabel but, for sure, JLabel doesn't work for my purpose.
Any idea of what could trigger this issue? Any idea of how this problem can be resolved in a better way? I apologize for the newbie question but I'm not a java developer. Thanks in advance for any help.
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedborder(),"Select Layers");
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (MyAction layer : layers) {
JCheckBoxMenuItem box = new JCheckBoxMenuItem(layer);
box.setIcon(new SquareIcon(myColor));
panel.add(box);
}
JPopup popup = new JidePopup();
popup.add(panel)
JButton button = new JButton("Layers");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
popup.show(button,0,button.getHeight())
}
});
Thats in the nature of JPopupMenus. They disappear when the invoker component loses the focus. But I found a little trick here.
Create your own class and extend it from JPopupMenu. Then override the setVisible method that it will only forward true to the super class and create an own method that will setVisible of the super class to false.
public class StayOpenPopup extends JPopupMenu{
public void setVisible(boolean visible){
if(visible == true)
super.setVisible(visible);
}
public void disappear() {
super.setVisible(false);
}
}
Then use it like this in your code
[...]
StayOpenPopup popup = new StayOpenPopup();
popup.add(panel);
[...]
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(popup.isVisible())
popup.disappear();
else popup.show(button,0,button.getHeight());
}
});
Now one click on button will show it. And it will stay visible until next click on Button.

Creating an intro screen for a Java Applet

Hi guys I have a question about Applets. I have an game applet that I would like to embed in a webpage. However I would like to add a "Start Screen" to the applet which comes up first and has a few parameter buttons and a start button. The "Game Screen" should load when the start button is pressed. What would be the best way to go about implementing this? Here is a simple 1-screen Applet as an example.
public class AppletExample extends Applet implements ActionListener{
Button okButton;
Button cancelButton;
TextField _textField;
public void init(){
okButton = new Button("Press");
cancelButton = new Button("Cancel");
_textField = new TextField("Ready", 10);
okButton.addActionListener(this);
cancelButton.addActionListener(this);
add(okButton);
add(_textField);
add(cancelButton);
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == okButton){
_textField.setText("Running...");
}
else { _textField.setText("Cancelled");
}
}
}
You could use CardLayout to manage navigation between panels.
Have a look also at using the lightweight Swing JApplet rather the old AWT applet. The start panel could be a JPanel containing the necessary components. Use next, previous or show as appropriate to navigate between game panels.
public void init() {
setLayout(new CardLayout());
JPanel startPanel = new JPanel();
okButton = new JButton("Press");
startPanel.add(okButton);
...
add(startPanel, "Card 1");
...
}

How can I prevent my JFrame Window from multiplying?

For the sake of everyone understanding my problem, I've created a simple GUI program which shows my problem. I'll first put the codes for you to analyze. And then, please watch the video below to see what I've been meaning to ask. Please bear with me, the video is just a few seconds and will not take time to load.
Menu JFrame:
//This is a Menu JFrame Window
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Menu extends JFrame implements GlobalVariables{
public Menu(){
clickMe.setBounds(75, 50, 100, 50);
clickMe.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
dispose();
SubMenu sm = new SubMenu();
sm.subMenuProperties();
}
});
add(clickMe);
}
void menuProperties(){
setLayout(null);
setSize(250,175);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Menu m = new Menu();
m.menuProperties();
}
}
SubMenu JFrame:
//This is a SubMenu JFrame Window
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class SubMenu extends JFrame implements GlobalVariables{
public SubMenu(){
clickMe2.setBounds(75, 50, 100, 50);
clickMe2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
dispose();
Menu m = new Menu();
m.menuProperties();
}
});
add(clickMe2);
}
void subMenuProperties(){
setLayout(null);
setSize(250,175);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SubMenu sm = new SubMenu();
sm.subMenuProperties();
}
}
And if your're wondering what's the "GlobalVariables" implementation, here it is:
import javax.swing.*;
public interface GlobalVariables{
//Menu Variable
JButton clickMe = new JButton("SubMenu");
//SubMenu Variable
JButton clickMe2 = new JButton("Back");
}
Now, this video will show you what I mean in JFrame being multiplied:
http://www.youtube.com/watch?v=iCavg_1SqvY
*If you watched the video, you can see what I mean when I say the JFrame is being multiplied. I've been analyzing this for days but I cannot identify my mistake. If you can just pinpoint my mistake, I'll be more than thankful. I'm also open for comments and adjustments in the code, I just wish that the structure of the code will not be re-structured because as I've said earlier, I've created this simple GUI just to show you my problem but to tell you at least, I have a whole program waiting to be finished using this kind of approach in GUI making. Please help me.
Those two classes are both a subclass of JFrame which results in a new window.
The one named Menu contains a button "clickMe" which instantiates SubMenu that contains a button "clickMe2" that instantiates Menu. This creates a endless loop creating more instances of each class. I.e creating more frames.
In the class SubMenu, remove these lines:
Menu m = new Menu();
m.menuProperties();
To get started using swing, Oracle has great tutorials.
I found the issue with the code. You need to remove the ActionListener in you actionPerformed method. For each button click, your code creates a new ActionListener object and it gets associated with your button. Subsequent clicks gets executed by this duplicate action listeners and you end up getting more JFrames.
Add the below line to actionPerformed(ActionEvent e) method of both classes after the line dispose(). This should fix your problem
Menu.java
clickMe.removeActionListener(this);
......
SubMenu.java
clickMe2.removeActionListener(this)
;

Categories