I am trying to program an applet that has four buttons, all of which play a short audio file. The goal is to try and have the user successfully click the buttons any number of times, therefore creating a beat. Here is my attempt:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
public class drumKit extends JApplet
{
private JButton snareButton;
private JButton hiHatButton;
private JButton bassButton;
private JButton cymbalsButton;
private AudioClip snare;
private AudioClip hiHat;
private AudioClip bass;
private AudioClip cymbals;
public void init()
{
setLayout (new FlowLayout());
sampleButtons();
snare = getAudioClip(getDocumentBase(), "Snare.wav");
hiHat = getAudioClip(getDocumentBase(), "HiHat.wav");
bass = getAudioClip(getDocumentBase(), "Kick.wav");
cymbals = getAudioClip(getDocumentBase(), "Crash.wav");
}
private void sampleButtons()
{
snareButton = new JButton("Snare");
hiHatButton = new JButton("Hi Hat");
bassButton = new JButton("Kick");
cymbalsButton = new JButton("Cymbals");
snareButton.addActionListener(new ButtonListener());
hiHatButton.addActionListener(new ButtonListener());
bassButton.addActionListener(new ButtonListener());
cymbalsButton.addActionListener(new ButtonListener());
add(snareButton);
add(hiHatButton);
add(bassButton);
add(cymbalsButton);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == snareButton)
snare.play();
if (e.getSource() == hiHatButton)
hiHat.play();
if (e.getSource() == bassButton)
bass.play();
if (e.getSource() == cymbalsButton)
cymbals.play();
}
}
}
The problem is, when I click the buttons, nothing plays. I referred to the solutions listed here, a window pops up preventing any further interactions with the applet. Sorry, a bit of a newbie here.
//Thanks for your help.
When you say "applet or GUI" I think you really mean applet or application--they are both GUIs. I'm not really familiar with AudioClip, but if it works as easy as it seems, then all you need to do is change your JApplet to a JPanel, then create a main method which creates a JFrame and set its content pane to your JPanel:
disclaimer: This code has not been tested and probably contains complilation errors (I will correct anything pointed out).
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
public class drumKit extends JPanel implements ActionListener
{
private final JButton snareButton;
private final JButton hiHatButton;
private final JButton bassButton;
private final JButton cymbalsButton;
private final AudioClip snare;
private final AudioClip hiHat;
private final AudioClip bass;
private final AudioClip cymbals;
public drumKit()
{
super();
// create buttons
snareButton = new JButton("Snare");
hiHatButton = new JButton("Hi Hat");
bassButton = new JButton("Kick");
cymbalsButton = new JButton("Cymbals");
// setup audio clips
snare = getAudioClip(getDocumentBase(), "Snare.wav");
hiHat = getAudioClip(getDocumentBase(), "HiHat.wav");
bass = getAudioClip(getDocumentBase(), "Kick.wav");
cymbals = getAudioClip(getDocumentBase(), "Crash.wav");
// set layout
setLayout (new FlowLayout());
// add this action listener to the buttons and add to this panel
sampleButtons();
}
private void sampleButtons()
{
// add this as the each button's action listener
snareButton.addActionListener(this);
hiHatButton.addActionListener(this);
bassButton.addActionListener(this);
cymbalsButton.addActionListener(this);
// add each button to this panel
this.add(snareButton);
this.add(hiHatButton);
this.add(bassButton);
this.add(cymbalsButton);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == snareButton)
snare.play();
else if (e.getSource() == hiHatButton)
hiHat.play();
else if (e.getSource() == bassButton)
bass.play();
else if (e.getSource() == cymbalsButton)
cymbals.play();
}
/**
* main method creates a frame which contains this custom panel
* and displays it.
*/
public static void main(String ...args){
// set the look and feel to the system's look and feel
try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
// if this fails, who cares, the look and feel will be Java's
// just continue
}
// create frame and make sure that when you close the frame the
// program exits!
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create your panel, set it to the frame's content pane,
// then show the frame
final JPanel panel = new drumKit();
frame.setContentPane(panel);
frame.setVisible(true);
// resize the frame to be the preferred size of your panel
frame.pack();
}
If you cannot read the files, then I would suggest putting in the fully qualified path name rather than just "Snare.wav" (for example) which looks in the current CLASSPATH directory (which for eclipse, I believe is the project directory).
Related
Hi guyz i have a prob in writing java code for my project as am unable to tackle that, i want my "Categories" button to perform action like it should show bread class in it but am unable to inherit it and put a pic on it so can anyone here just tell me whats the problem in it..
here is the code:
JButton b1 = new JButton("Categories");
b1.setSize(120,25);
b1.setLocation(130,650);
b1.setBackground(Color.LIGHT_GRAY) ;
b1.addActionListener(new AL());
f.add(b1);
public class AL implements ActionListener{
public void actionPerformed(ActionEvent ae){
JFrame f3 = new JFrame("Delicious Bakery");
f3.setVisible(true);
f3.setSize(400,200);
f3.add(Bread);
Now here is the Bread class:
public class Bread extends AL implements ActionListener
{
Bread()
{
ImageIcon BreadImage = new ImageIcon("C:\\Users\\Baba\\Downloads\\Documents\\Bread1.jpg");
JButton Bread = new JButton("Bread",BreadImage);
Bread.setSize(128,96);
}}
You appear to be making several basic mistakes including what looks to be trying to add a class that implements ActionListener to your GUI as if it were a button, but it's not. This suggests that you'd greatly benefit from first reading through the JButton Tutorial and the ActionListener Tutorial.
Note that if this were my project, I'd use AbstractActions a concept that is sort of like an "ActionListener on steroids". You would set your JButton with this Action and in doing so, gain the button its name text, its icon and its ActionListener behavior.
Some notes on your code:
JButton b1 = new JButton("Categories"); // (1)
b1.setSize(120,25); // (2)
b1.setLocation(130,650); // (3)
b1.setBackground(Color.LIGHT_GRAY) ;
b1.addActionListener(new AL()); // (4)
f.add(b1); // (5)
You here create a JButton with a String name text
Here you try to set absolute size, something that we don't recommend as doing this, and using null layouts leads to rigid hard to improve and debug programs
Same for setting locations
You appear to be adding an ActionListener OK
And then add your button to a container (the JFrame perhaps)?
public class AL implements ActionListener{ // (6)
public void actionPerformed(ActionEvent ae){
JFrame f3 = new JFrame("Delicious Bakery"); // (7)
f3.setVisible(true); // (8)
f3.setSize(400,200); // (9)
f3.add(Bread); // (10)
OK, so the AL class implements ActionListener and has an actionPerformed method, so far so good
OK, so inside it you create a new JFrame, a bit unusual since most GUI's have only one JFrame
You're calling setVisible(true) on the JFrame before adding components -- not code, since this may sometimes not allow the JFrame to fully render components added after this setVisible was called
Same notes as previous about setting sizes
Now you add Bread to the JFrame. But Bread looks to not be a component but rather only an ActionListener. This line should not compile.
public class Bread extends AL implements ActionListener { // (11)
Bread() {
// (12)
ImageIcon BreadImage = new ImageIcon("C:\\Users\\Baba\\Downloads\\Documents\\Bread1.jpg");
JButton Bread = new JButton("Bread",BreadImage); // (13)
Bread.setSize(128,96); // (14)
}
}
Your Bread class extends AL but also implements ActionListener which is redundant since AL already implements ActionListener.
You are creating an image icon using a file and an absolute path, a slight no-no. Better to use resources and absolute paths
OK you create a new JButton, but you give it the same name as the non-JButton class -- very confusing. Simply don't do this. Ever. Name your fields with unique names, and obey Java naming issues.
Same issue regarding setting sizes.
For example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestBread extends JPanel {
// String to url for bread image
private static final String BREAD_IMG_PATH = "http://findicons.com/files/icons/339/"
+ "coffee_break/128/sliced_bread.png";
// preferred size of jpanel
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private BreadAction breadAction; // our abstract action
private JButton breadButton; // our jbutton
public TestBread() {
Icon breadIcon = null;
try {
// get image and put into Icon
URL breadUrl = new URL(BREAD_IMG_PATH);
BufferedImage breadImg = ImageIO.read(breadUrl);
breadIcon = new ImageIcon(breadImg);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
breadAction = new BreadAction("Bread", KeyEvent.VK_B, breadIcon); // create Action
breadButton = new JButton(breadAction); // create button with Action
breadButton.setVerticalTextPosition(AbstractButton.BOTTOM); // position text
breadButton.setHorizontalTextPosition(SwingConstants.CENTER);
add(breadButton);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
TestBread mainPanel = new TestBread();
JFrame frame = new JFrame("TestBread");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Our AbstractAction or "super" ActionListener
#SuppressWarnings("serial")
class BreadAction extends AbstractAction {
public BreadAction(String name, int mnemonic, Icon icon) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
putValue(LARGE_ICON_KEY, icon);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("bread pressed");
}
}
So I have 1 class, with a radio button and 1 class, that will create an applet depending on the outcome of the Radio Button. I don't know how to make the graphics run depending on an if/else statement. All help will be greatly appreciated.
Radio Button Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
protected JRadioButton displacement;
protected JRadioButton accel;
protected JRadioButton time;
public RadioButton() {
// Create the radio buttons
displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setSelected(true);
//Displacement Button, set to automatically be clicked
accel = new JRadioButton("Acceleration");
accel.setMnemonic(KeyEvent.VK_A);
accel.setActionCommand("acceleration");
//Acceleration Button
time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(accel);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
accel.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(accel);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand()
+ ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
If/Else Statements class:
import java.lang.Object;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.*;
public class RadioButtonMain extends RadioButton {
public static void main(String [ ] args) {
new RadioButtonMain().doMain();
}
public void doMain() {
if ( displacement.isSelected()) {
//option 1 for applet
}
if ( accel.isSelected()) {
//Option 2 for applet
}
else {
//Option 3 for applet
}
}
}
How would I get the graphics to run based on whether or not the variables accel and displacement are pressed? Thanks.
Remember, a GUI is an event driven environment, things don't run within a linear manner. Instead of trying run a method yourself, you need to use a callback or listener of some kind which will tell you when the state of the program/buttons change...
When the JRadioButton actionPerformed event is raised, you need to call another method which provides information about what has occurred. You can then override these methods in your RadioButtonMain class and take action when they are called
This is very similar to an Observer Pattern
Very new to Java, but I am slowly picking my way through things. So please be kind. I understand most things I've tried so far, and built a version of the following that uses console output, but now I'm trying to make a GUI. I tried the netbeans GUI maker, but it created so much new code that when I tried to pick through it, I got lost. I'm much better at learning by piecing new things together myself, not having an IDE generate a ton of code and then attempt to find where I want to work.
I am trying to build an window that has a list with three choices on the left side, a button in the middle that confirms your choice, and an answer output on the right. Once the button is pressed, the input from the list is read and is converted into a corresponding answer. As of right now, all I get is "We recommend... null" after selecting an option in the list. The button appears to do nothing at the moment.
I have used tutorials, hacked up others' code from online, and referenced a few books, but I'm stuck.
Here is what I have:
package diffguidegui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DiffGuideGUI extends JPanel implements ListSelectionListener {
private JList resultsTabList;
private DefaultListModel listModel;
private static final String recommendString = "Recommend a Option";
private JButton recommendButton;
private String recommendOutput;
final JLabel output = new JLabel("We recommend..." + recommendOutput);
//build list
public DiffGuideGUI () {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("A");
listModel.addElement("B");
//create the list and put it in the scroll pane
resultsTabList = new JList(listModel);
resultsTabList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTabList.setSelectedIndex(0);
//listener for user input
resultsTabList.addListSelectionListener(this);
resultsTabList.setVisibleRowCount(2);
JScrollPane listScrollPane = new JScrollPane(resultsTabList);
//build the button at the bottom to fire overall behavior
recommendButton = new JButton(recommendString);
recommendButton.setActionCommand(recommendString);
recommendButton.addActionListener(new RecommendListener());
//create a panel that uses Boxlayout for the button
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(recommendButton);
//create a panel that uses Boxlayout for the label
JPanel outputPane = new JPanel();
outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.LINE_AXIS));
outputPane.add(output);
add(listScrollPane, BorderLayout.WEST);
add(buttonPane, BorderLayout.CENTER);
add(outputPane, BorderLayout.EAST);
}
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
}
}
public void valueChanged(ListSelectionEvent e) {
if(e.getValueIsAdjusting() == false) {
if(resultsTabList.getSelectedIndex() == -1) {
recommendButton.setEnabled(false);
} else {
recommendButton.setEnabled(true);
}
}
}
//Create GUI and show it
private static void createAndShowGUI() {
JFrame frame = new JFrame("Recommend Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and set up content pane
JComponent newContentPane = new DiffGuideGUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The button appears to do nothing at the moment.
It does something. It calculates the value for your recommendOutput varable. But you never output this value.
try the following:
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
System.out.println(recommendOutput); // <-###################
}
}
This should print the value to stdout
To put the value into your label try this instead:
output.setText(recommendOutput);
where do you set the text for the JLabel? It says "We recommend NULL" because recommenedOutput is null when the object is created. I dont see
output.setText("We recommend "+value) anywhere. You probably need output.invalidate() also. Try putting setText(String text)/invalidate() in the RecommendListener.actionPerformed() method.
output.setText("We recommend A");
output.invalidate();
For class I'm working on my first GUI application. It's just a simple image viewer with four buttons: Previous, Next, Stop, Play. Previous and Next work fine, but honestly I don't even know how to begin working on the slideshow part (Play & Stop). I know there's a timer class that would probably be handy for controlling the speed as the images change...but I'm not sure what kind of logic is typically used to cycle through the images. Can anyone point me in the right direction, my brain is a little fried at this point :0
I've included my code below. I'm new to this, so hopefully people won't be too critical of my technique. If it matters, I'm working in eclipse.
here's my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.TimerTask;
public class ImageGallery extends JFrame
{
private ImageIcon myImage1 = new ImageIcon ("Chrysanthemum.jpg");
private ImageIcon myImage2 = new ImageIcon ("Desert.jpg");
private ImageIcon myImage3 = new ImageIcon ("Jellyfish.jpg");
private ImageIcon myImage4 = new ImageIcon ("Penguins.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages = new ImageIcon[4];
private int curImageIndex=0;
public ImageGallery ()
{
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
myImages[2]=myImage3;
myImages[3]=myImage4;
add(ImageGallery, BorderLayout.NORTH);
JButton PREVIOUS = new JButton ("Previous");
JButton PLAY = new JButton ("Play");
JButton STOP = new JButton ("Stop");
JButton NEXT = new JButton ("Next");
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,4));
Menu.add(PREVIOUS);
Menu.add(PLAY);
Menu.add(STOP);
Menu.add(NEXT);
add(Menu, BorderLayout.SOUTH);
//register listener
PreviousButtonListener PreviousButton = new PreviousButtonListener ();
PlayButtonListener PlayButton = new PlayButtonListener ();
StopButtonListener StopButton = new StopButtonListener ();
NextButtonListener NextButton = new NextButtonListener ();
//add listeners to corresponding componenets
PREVIOUS.addActionListener(PreviousButton);
PLAY.addActionListener(PlayButton);
STOP.addActionListener(StopButton);
NEXT.addActionListener(NextButton);
}
public static void main (String [] args)
{
ImageGallery frame = new ImageGallery();
frame.setSize(490,430);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
class PreviousButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(curImageIndex>0 && curImageIndex <= 3)
{ ImageGallery.remove(0);
curImageIndex=curImageIndex-1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
}
else
{
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage1));
curImageIndex=0;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
class PlayButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// *need help here*//
}
}
class StopButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// *need help here*//
}
}
class NextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(curImageIndex>=0 && curImageIndex < 3)
{ ImageGallery.remove(0);
curImageIndex = curImageIndex + 1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
}
else
{
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage4));
curImageIndex=3;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
}
Why complicating simple things,
I think that this is job for CardLayout and for slideshow is there Swing Timer
put images as Icon to the JLabel
This example shows a start/stop button that controls a javax.swing.Timer. Instead of replacing the label each time, just update the label's Icon, as suggested by #mKorbel and shown here.
You need use a thread for the slideshow. You can use a flag in the run method for continue with the show or stop if this flag change, for example, a boolean var. One example you can see in http://java.sun.com/developer/technicalArticles/Threads/applet/.
These are some guidelines that might get you started:
First you will need a separate thread to control the changing images. I suggest you write a class that implements TimerTask. Override the run() method in this class. In this run method you should put the functionality to change the current image being displayed (similar to what you did in the next and previous function).
In the actionPerformed() method for the play button you will need to create an instance of a Timer class and start your timer using the scheduleAtFixedRate(TimerTask task, long delay, long period) method (other methods in this class may be used as well, scheduleAtFixedRate() seem more appropriate though).
For the stop you will then need to add enough functionality to stop the running timer using the cancel() method in the Timer class
I'm learning Java and GUI. I have some questions, and the first is if there are any major difference between creating a subclass of JFrame and an instance of JFrame. It seems like like a subclass is more powerful? I also wonder if it's necessary to use this code when creating a GUI:
Container contentPane = getContentPane();
contentPane.setLayot(new Flowlayout());
I add my GUI class, it's a simple test so far, to a task that I have to hand in. When a user has entered some text in the textfield and press the button to continue to the next step, how do I do to clear the frame and show a new content or is there a special way to do this is in Java? I guess there must be better to use the same window instead of creating a new!? Help id preciated! Thanks
// Gui class
import java.awt.FlowLayout; // layout
import java.awt.event.ActionListener; // listener
import java.awt.event.ActionEvent; // event
import javax.swing.JFrame; // windows properties
import javax.swing.JLabel; // row of text
import javax.swing.JTextField; // enter text
import javax.swing.JOptionPane; // pop up dialog
import javax.swing.JButton; // buttons
// import.javax.swing.*;
public class Gui extends JFrame {
private JLabel text1;
private JTextField textInput1;
private JTextField textInput2;
private JButton nextButton;
// constructor creates the window and it's components
public Gui() {
super("Bank"); // title
setLayout(new FlowLayout()); // set default layout
text1 = new JLabel("New customer");
add(text1);
textInput1 = new JTextField(10);
add(textInput1);
nextButton = new JButton("Continue");
add(nextButton);
// create object to handle the components (action listener object)
frameHandler handler = new frameHandler();
textInput1.addActionListener(handler);
nextButton.addActionListener(handler);
}
// handle the events (class inside another class inherits contents from class outside)
private class frameHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
String input1 = "";
// check if someone hits enter at first textfield
if(event.getSource() == textInput1){
input1 = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, input1);
}
else if(event.getSource() == nextButton){
// ??
}
}
}
}
This small code might help you explain things :
import java.awt.event.*;
import javax.swing.*;
public class FrameDisplayTest implements ActionListener
{
/*
* Creating an object of JFrame instead of extending it
* has no side effects.
*/
private JFrame frame;
private JPanel panel, panel1;
private JTextField tfield;
private JButton nextButton, backButton;
public FrameDisplayTest()
{
frame = new JFrame("Frame Display Test");
// If you running your program from cmd, this line lets it comes
// out of cmd when you click the top-right RED Button.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel1 = new JPanel();
tfield = new JTextField(10);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
nextButton.addActionListener(this);
backButton.addActionListener(this);
panel.add(tfield);
panel.add(nextButton);
panel1.add(backButton);
frame.setContentPane(panel);
frame.setSize(220, 220);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (tfield.getText().length() > 0)
{
if (button == nextButton)
{
/*
* this will remove the first panel
* and add the new panel to the frame.
*/
frame.remove(panel);
frame.setContentPane(panel1);
}
else if (button == backButton)
{
frame.remove(panel1);
frame.setContentPane(panel);
}
frame.validate();
frame.repaint(); // prefer to write this always.
}
}
public static void main(String[] args)
{
/*
* This is the most important part ofyour GUI app, never forget
* to schedule a job for your event dispatcher thread :
* by calling the function, method or constructor, responsible
* for creating and displaying your GUI.
*/
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FrameDisplayTest();
}
});
}
}
if you want to switch (add then remove) JComponents, then you have to
1) add/remove JComponents and then call
revalidate();
repaint()// sometimes required
2) better and easiest choice would be implements CardLayout
If your requirement is to make a wizard, a panel with next and prev buttons, and on clicking next/prev button showing some component. You could try using CardLayout.
The CardLayout manages two or more components (usually JPanel instances) that share the same display space. CardLayout let the user choose between the components.
How to Use CardLayout
If your class extends JFrame, you can do:
getContentPane().removeAll();