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
Related
I am still learning how to code in java and I could use a bit of help right now.
This is the current code I wrote. As you can see, it's a simple panel with a bunch of buttons and a slider. I want to make a different console output whenever I hit a different button. So if I hit Back, it's supposed to write Back in the console. If I scroll a bit on the slider, it's supposed to write the new value in the console. Stuff like that. I know it has to be done with actionListener and actionPerformed but after some experimenting I couldn't get it to work.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui implements ActionListener {
// Adding all the goods
JFrame frame;
JPanel panel;
JButton endButton;
JButton backButton;
JButton calcButton;
JSlider maxIterations;
JLabel view;
Gui() {
// General
this.frame = new JFrame("Trying my best, I swear");
this.frame.setSize(500, 500);
this.frame.setVisible(true);
this.panel = new JPanel();
// Buttons
this.backButton = new JButton("Back");
this.calcButton = new JButton("Calc");
this.endButton = new JButton("End");
this.panel.add(this.endButton);
this.panel.add(this.calcButton);
this.panel.add(this.backButton);
this.frame.add(this.panel);
// Label
JLabel label1 = new JLabel();
label1.setText("Space Holer");
panel.add(label1);
// Slider
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
panel.add(slider);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// Make the buttons do something
this.endButton.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
System.out.println("End");
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Gui m = new Gui();
}
}
You could...
Take advantage of the actionCommand property of the button, which is set to the ActionEvent when it's created. If you don't supply an actionCommand to the button yourself, it will default to the text value, so you could do something like
public class ButtonActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "Back":
System.out.println("Back");
break;
case "Calc":
System.out.println("Calc");
break;
case "End":
System.out.println("End");
break;
}
}
}
This is good if the ActionListener is external to the class where the buttons are defined, because you won't have access to the button references. It's also good, because you could have a number of buttons (including toolbar buttons and menu items) which do the same thing
You could...
Make use of the ActionListener's source property
public class ButtonActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == backButton) {
System.out.println("Back");
} else if (e.getSource() == calcButton) {
System.out.println("Calc");
} else if (e.getSource() == endButton) {
System.out.println("End");
}
}
}
This is useful if the ActionListener in defined as a inner class to the parent class from where the buttons are defined
You could...
Use an anonymous class registered directly against the button...
endButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("End");
}
});
This is good where the button does a single, isolated task
You could...
Make use of the Action API which allows you to define a self contained unit of work, which can be used by buttons to configure themselves completely from it. This is useful where you have a repeated action which can be executed from different locations of the UI, like a "open file" action contained in the menu bar, tool bar and some wizard. You can even use it with the key bindings API for extended functionality
See How to use actions for more details
Need to add ActionListener to all buttons,
calcButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("calcButton");
// calculation for slider.
}
});
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("backButton");
}
});
then u get the different console output.
Call setVisible on jframe after you placed all components into it.
Add ActionListener to each button. Add ChangeListener to slider as it cannot have ActionListener.
See full code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class Gui implements ActionListener {
// Adding all the goods
JFrame frame;
JPanel panel;
JButton endButton;
JButton backButton;
JButton calcButton;
JSlider maxIterations;
JLabel view;
Gui() {
// General
this.frame = new JFrame("Trying my best, I swear");
this.frame.setSize(500, 500);
this.panel = new JPanel();
// Buttons
this.backButton = new JButton("Back");
this.calcButton = new JButton("Calc");
this.endButton = new JButton("End");
this.panel.add(this.endButton);
this.panel.add(this.calcButton);
this.panel.add(this.backButton);
this.frame.add(this.panel);
// Label
JLabel label1 = new JLabel();
label1.setText("Space Holer");
panel.add(label1);
// Slider
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
panel.add(slider);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// Make the buttons do something
this.endButton.addActionListener(this);
this.backButton.addActionListener(this);
this.calcButton.addActionListener(this);
slider.addChangeListener(e -> {
Object source = e.getSource();
if (source instanceof JSlider) {
int value = ((JSlider) source).getValue();
System.out.println(value);
}
});
frame.pack();
this.frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source instanceof JButton) {
String text = ((JButton) source).getText();
System.out.println(text);
}
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Gui m = new Gui();
}
}
Dear Friends of Stackoverflow,
I kindly ask for your help as I'm stuck with the programming of a small interface:
here's what I'm trying to do:
I have a JDesktopPane with a few internal Frames. The logic is:
- the DesktopPane starts with a Launch Window (a JInternalFrame) that has the button for level 1
- The user clicks on Level 1 and a new JInternal Window Level 1 opens (launch window closes) with a button
- the user clicks the button and sets level 1 to complete
- The JInternal Window Level 1 Closes
- the launch window re-opens but, as Level 1 has been set to completed, now the Launch window has a new button to access level 2
- the user clicks on that button and access level 2 and so on
here's what happens
- I start the program, I get the launch window with button for level 1
- I click on the button and I go back to the launch window
BUT
- there is no button for level 2
- furthermore: if I click again on button level 1 I get an error
Here my code: I hope somebody can point me in the right direction
MAIN CLASS
package gioco;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.border.EmptyBorder;
public class AllInAWindow extends JFrame {
//create components outside constructor
JDesktopPane MainDesktopPane = new JDesktopPane();
JInternalFrame IFrameLaunchWindow = new JInternalFrame();
JInternalFrame IFrameLevel1 = new JInternalFrame();
JInternalFrame IFrameLevel2 = new JInternalFrame();
//let's create the constructor
public AllInAWindow() {
initUI();
}
public void initUI(){
VariablesSetEGet VariablesSetEGetObj = new VariablesSetEGet();
//-------------------------IFrame Level1--------------------------//
//interface of IFrame Level1
IFrameLevel1.setTitle("Level 1");
IFrameLevel1.setSize(200, 200);
IFrameLevel1.setLocation(200, 200);
IFrameLevel1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton action1L1 = new JButton("action 1 Level1");
action1L1.setBorder(new EmptyBorder(5 ,5, 5, 5));
IFrameLevel1.add(action1L1);
//button action
roundLevelAction1 roundLevelAction1Obj = new roundLevelAction1(); //create object of the constructor
action1L1.addActionListener(roundLevelAction1Obj);//add listener to JButton and pass it through the constructor
//-------------------------IFrame Level2--------------------------//
//interface of IFrame Level2
IFrameLevel2.setTitle("Level 2");
IFrameLevel2.setSize(200, 200);
IFrameLevel2.setLocation(300, 300);
IFrameLevel2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton action1L2 = new JButton("action 1 Level2");
action1L2.setBorder(new EmptyBorder(5 ,5, 5, 5));
IFrameLevel2.add(action1L2);
//button action
roundLevelAction2 roundLevelAction2Obj = new roundLevelAction2(); //create object of the constructor
action1L2.addActionListener(roundLevelAction2Obj);//add listener to JButton and pass it through the constructor
//-------------------------iFrame Launch window-----------------------------//
IFrameLaunchWindow.setLayout(null);
IFrameLaunchWindow.setTitle("INIZIO");
IFrameLaunchWindow.setClosable(true);
IFrameLaunchWindow.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
IFrameLaunchWindow.setSize(400, 400);
//button level 1
JButton ButtonLevel1 = new JButton("level1"); //create the button variable
ButtonLevel1.setSize(200, 40);
ButtonLevel1.setLocation(100, 120);
ButtonLevel1.addActionListener//add the listener so that the button can launch the window with the board level
(new ActionListener()
{
public void actionPerformed (ActionEvent lanciaLevel1) //create the action
{
MainDesktopPane.add(IFrameLevel1); //launch the frame with the level 1
IFrameLevel1.setVisible(true); //set it to visible
IFrameLaunchWindow.dispose();//close this launch window
}
}
);
IFrameLaunchWindow.add(ButtonLevel1); //add the button of the level 1
ButtonLevel1.setVisible(true);
//button level 2
JButton ButtonLevel2 = new JButton("level2");
ButtonLevel2.setSize(200, 40);
ButtonLevel2.setLocation(100, 180);
ButtonLevel2.addActionListener
(new ActionListener()
{
public void actionPerformed (ActionEvent lanciaLevel2)
{
MainDesktopPane.add(IFrameLevel2); //launch the frame with the level 2
IFrameLevel1.setVisible(true); //set it to visible
IFrameLaunchWindow.dispose();//close this launch window
}
}
);
//same as before but here the if: if level1 is not set to completed the button for level2 won't appear
if (VariablesSetEGetObj.getL1()==1){
IFrameLaunchWindow.add(ButtonLevel2);
ButtonLevel2.setVisible(true);
}
//button level 3 (just for image, same logic)
JButton ButtonLevel3 = new JButton("level3");
ButtonLevel3.setSize(200, 40);
ButtonLevel3.setLocation(100, 240);
if (VariablesSetEGetObj.getL2()==1){
IFrameLaunchWindow.add(ButtonLevel3);
ButtonLevel3.setVisible(true);
}
MainDesktopPane.add(IFrameLaunchWindow); //start the main panel with the launch window
IFrameLaunchWindow.setVisible(true);
add(MainDesktopPane);//add the main desktopPane to the Frme
}
class roundLevelAction1 implements ActionListener {//action of the button in IFrame 1
public roundLevelAction1(){
//there are graphical elements here in the original code but not relevant for this
}
#Override
public void actionPerformed(ActionEvent ActionLevel1) {//if button is clicked
VariablesSetEGet VariablesSetEGetObj = new VariablesSetEGet();
VariablesSetEGetObj.setL1(1);//set Level 1 to complete
IFrameLevel1.dispose(); //close L1 window
//go back to launch window but now it should show button to access L2 as L1 has been set to completed
MainDesktopPane.add(IFrameLaunchWindow);
IFrameLaunchWindow.setVisible(true);
}
}
class roundLevelAction2 implements ActionListener {//action of button in IFrame2
public roundLevelAction2(){
//there are graphical elements here in the original code but not relevant for this
}
#Override
public void actionPerformed(ActionEvent ActionLevel2) {//if button is clicked
VariablesSetEGet VariablesSetEGetObj = new VariablesSetEGet();
VariablesSetEGetObj.setL2(1);//set level 2 to complete
IFrameLevel2.dispose(); //close L2 window
//go back to launch window but now it should show button to access L3 as L2 has been set to completed
MainDesktopPane.add(IFrameLaunchWindow);
IFrameLaunchWindow.setVisible(true);
}
}
public static void main (String[]args) {
//as this will launch the "fresh" new game, we set each level (and therefore button)
//to disabled except button 1. we do it here outside the runnable
VariablesSetEGet VariablesSetEGetObj = new VariablesSetEGet();
VariablesSetEGetObj.setL1(0);
VariablesSetEGetObj.setL2(0);
//TRIGGER LAUNCH WINDOW (see ZCode1)
EventQueue.invokeLater
(new Runnable()
{
#Override
public void run()
{
AllInAWindow AllInAWindowObj = new AllInAWindow();
AllInAWindowObj.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
AllInAWindowObj.setVisible(true);
AllInAWindowObj.setSize(800, 800);
}
}
);
}
}
SEPARATE CLASS
public class VariablesSetEGet {
static int L1 = 0;
public void setL1 (int L1){
this.L1 = L1;
}
public int getL1 (){
return L1;
}
static int L2 = 0;
public void setL2 (int L2){
this.L2 = L2;
}
public int getL2 (){
return L2;
}
}
many thanks in advance for your help
This is not THE solution to the initial problem: this is a change of logic based on the suggestion of MadProgrammer, which was to abandon the JInternalFrame and use CardLayout. And doing my research on CardLayout I managed to do what I wanted to initially do . Here the code
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CLayout {
//1) create the Frame
JFrame MainWindow = new JFrame("Finestra di Gioco");
//2) create as many JPanels as messages + levels, but...
JPanel panelCont = new JPanel(); //...the first one needs to contain them all
JPanel FinestraLancio = new JPanel();
JPanel Livello1 = new JPanel();
JPanel Livello2 = new JPanel();
//3) create the buttons to switch among panels
JButton OpenLevel1 = new JButton("Open Level 1");
JButton CompleteLevel1 = new JButton("Complete Level 1");
JButton OpenLevel2 = new JButton("Open Level 2");
JButton CompleteLevel2 = new JButton("Complete Level 2");
//4) create an instance of the card Layout method
CardLayout cl = new CardLayout();
//5) create the constructor
public CLayout(){
//5.a) assign the instance of the card Layout to the container panel
panelCont.setLayout(cl);
//5.b) create the windows insert the buttons, assign the actions
FinestraLancio.add(OpenLevel1);
FinestraLancio.add(OpenLevel2);
OpenLevel2.setVisible(false);
Livello1.add(CompleteLevel1);
Livello2.add(CompleteLevel2);
Livello1.setBackground(Color.yellow);
Livello2.setBackground(Color.blue);
OpenLevel1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent OpenLevel1){
cl.show(panelCont, "2"); //this "2" is the position indicator,
//we'll discuss it at 5c
}
});
OpenLevel2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent OpenLevel2){
cl.show(panelCont, "3");
}
});
CompleteLevel1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent CompleteLevel1){
OpenLevel2.setVisible(true);
cl.show(panelCont, "1");
}
});
CompleteLevel2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent CompleteLevel2){
OpenLevel2.setVisible(false);
cl.show(panelCont, "1");
}
});
//5.c) now put the elements in the container panel, and add the name of
//the element and the position indicator you will need that position
//indicator when you want to call that specific window
panelCont.add(FinestraLancio, "1"); //"1" is the position indicator
panelCont.add(Livello1, "2");
panelCont.add(Livello2, "3");
//now indicate that the instance of the cardlayout has the container as
//its main panel and inside the container the first panel to be displayed
//is the one with the position indicator "1", i.e. the LaunchWindow
cl.show(panelCont, "1");
//create the main window
MainWindow.add(panelCont);
MainWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
MainWindow.setSize(400, 400);
MainWindow.setVisible(true);
}
public static void main (String[]args){
SwingUtilities.invokeLater
(new Runnable(){
#Override
public void run(){
new CLayout();
}
});
}
}
I am still new to using Swing and creating GUIs in Java. I was working on a simple test code where the color of a button changes to a random color when it is pressed. Although it works, every time I press the button, it minimizes the previous window and opens a new one and they keep piling up. How will I make it so that this does not happen? Does this occur because I am creating an object in the actionPerformed method? The reason why I have made an object there is to link the Swing class with the separate Action class I have made in order to manipulate the button variable.
Therefore, my two questions are:
How can I prevent multiple windows from appearing and instead have them replace each other?
Is there a way to utilize ActionListener within the same class and would it make things easier?
Any help is greatly appreciated!
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class Swing extends JFrame{
private JFrame f;
private JLabel l;
private JButton b;
private JPanel p;
public Swing(){
test();
}
//*
public JFrame getJFrame(){
return f;
}
public JLabel getJLabel(){
return l;
}
public JButton getJButton(){
return b;
}
public JPanel getJPanel(){
return p;
}
//*
public void test(){
// Frame Setup
f = new JFrame("Frame");
f.setVisible(true);
f.setSize(500, 500);
f.setResizable(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
//
// Panel Setup
p = new JPanel();
p.setVisible(true);
//
// Other
b = new JButton("Button");
l = new JLabel("Label");
b.addActionListener(new Action());
//
// Additions
p.add(b);
p.add(l);
f.add(p); // ***
//
}
public static void main(String[] args){
Swing swing = new Swing();
swing.test();
}
}
final class Action implements ActionListener{
public void actionPerformed(ActionEvent e){
Swing swingObject = new Swing(); //
JButton button = swingObject.getJButton(); //
button.setBackground(randomColor());
}
public Color randomColor(){
Random rn = new Random();
ArrayList<Color> color = new ArrayList<Color>();
color.add(Color.BLUE);
color.add(Color.GREEN);
color.add(Color.RED);
color.add(Color.YELLOW);
color.add(Color.PINK);
color.add(Color.CYAN);
color.add(Color.ORANGE);
color.add(Color.MAGENTA);
int s = color.size();
int random = rn.nextInt(s);
return color.get(random);
}
}
From your listener, you're executing
Swing swingObject = new Swing();
This does what it should do: create a new Swing JFrame. You don't want a new JFrame, so don't call its constructor. From the listener, simply get the button that fired the event, and change its color:
JButton button = (JButton) e.getSource();
button.setBackground(randomColor());
You could also pass the button to modify when creating the listener:
class Action implements ActionListener{
private JButton buttonToUpdate;
public Action(JButton buttonToUpdate) {
this.buttonToUpdate = buttonToUpdate;
}
public void actionPerformed(ActionEvent e){
buttonToUpdate.setBackground(randomColor());
}
}
And, to create it:
b = new JButton("Button");
b.addActionListener(new Action(b));
What is the best way to define the action a button will perform in the code? I want to be able to have one button do one action and the next button do a different action. Is this possible?
You can add action listener like this.
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
You can do this way.
JButton button = new JButton("Button Click");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//do your implementation
}
});
JButton subclasses AbstractButton, which has a method, addActionListener. By calling this method and passing it the action listener you wish to add, the action listener is added and will be called once an action is fired, either programatically, or by way of user interaction. Other listners can be added such as mouse listeners.
One way is to have your class implement ActionListener. Then implement the actionPerformed() method. Here is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Driver extends JFrame implements ActionListener {
private static final long serialVersionUID = 3549094714969732803L;
private JButton button = new JButton("Click");
public Driver(){
JPanel p = new JPanel(new GridLayout(3,4));
p.add(button);
button.addActionListener(this);
add(p);
}
public static void main(String[] args){
Driver frame = new Driver();
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked me!");
}
}
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();