I have created a "Main Menu" JFrame with different JButtons for different periods. If I click on one of the buttons a new JFrame opens up but whenever I dispose of it and go back to the main menu and open it back up it it seems as if it more buttons and I don't know why.
Main Menu
public class GUI extends JFrame implements ActionListener {
public static final int WIDTH=1000;
public static final int LENGTH=900;
public static JFrame myFrame = new JFrame("TOK Discussion Participation");
static JPanel myPanel = new JPanel();
public static JComponent buttonPanel;
public static JPanel IPanel = new JPanel();
public static JFrame Period7 = new JFrame("Period 7");
JPanel myPanel1 = new JPanel();
public static Object createPanelPERIOD7;
public JFrame getMyFrame()
{
return myFrame;
}
public void setWindow()
{
//// Creates Icon in frame
JLabel Image = new JLabel();
ImageIcon myIcon = new ImageIcon(new ImageIcon("/users/Antti/Desktop/GUI/TOKParticipation/src/TOK.jpg").getImage().getScaledInstance(200, 200, 1));
Image.setIcon(myIcon);
//set window
Color backgroundColor = new Color(5,149,251);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setBounds(550,200,1000,600);
myFrame.getContentPane().setBackground(Color.LIGHT_GRAY);
myFrame.setLayout(new BorderLayout());
myFrame.add(myPanel1,BorderLayout.NORTH);
myFrame.add(new JLabel(new ImageIcon("/users/Antti/Desktop/GUI/TOKParticipation/src/TOK.jpg")), BorderLayout.CENTER);
//myFrame.setIconImage("/users/Antti/Desktop/GUI/TOKParticipation/src/TOK.jpg");
myFrame.getContentPane().setBackground(backgroundColor);
myFrame.setVisible(true);
//set label
JLabel myLabel = new JLabel("TOK Discussion Participation");
JLabel myLabel1= new JLabel("");
JLabel myLabel2 = new JLabel("");
//set button (PERIOD 7)
JButton Period_7_BUTTON = new JButton("Period 7");
//set Listener (PERIOD 7)
Period_7_BUTTON.addActionListener(new GUI());
//2nd button (PERIOD 5)
JButton Period_5_BUTTON = new JButton("Period 5");
//set Listener PERIOD 5)
Period_5_BUTTON.addActionListener(new GUI());
//2nd button (PERIOD 2)
JButton Period_2_BUTTON = new JButton("Period 2");
//set Listener PERIOD 2)
Period_2_BUTTON.addActionListener(new GUI());
//2nd button (PERIOD 2)
JButton Period_4_BUTTON = new JButton("Period 4");
//set Listener PERIOD 4)
Period_4_BUTTON.addActionListener(new GUI());
//Setting Button FONT/SIZE
Period_2_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
Period_4_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
Period_5_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
Period_7_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
//Bundle button to panel
myPanel1.setLayout(new BoxLayout(myPanel1, BoxLayout.X_AXIS));
myPanel1.add(Period_7_BUTTON);
myPanel1.add(Period_5_BUTTON);
myPanel1.add(Period_2_BUTTON);
myPanel1.add(Period_4_BUTTON);
//add content to window and make it visible
myFrame.add(myPanel1,BorderLayout.NORTH);
myFrame.setVisible(true);
}
public void dispose(){
myFrame.dispose();
}
Other JFrame that duplicates buttons once reopened
//Method to create Period 7 Frame
public static void createFramePERIOD7() {
//Creates Panel + Buttons
JPanel P7_Panel = new JPanel();
JButton Column = new JButton("Add Columns");
JButton Insert = new JButton("Insert Student 7");
JButton Back = new JButton("Home");
//Adding Buttons and Layout to Period 7 Frame
Period7.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Period7.setBounds(550,200,1000,600);
Period7.setLayout(new FlowLayout());
Period7.add(Back);
Period7.add(Column);
Period7.add(Insert);
//Add ActionListener to Buttons
Back.addActionListener(new GUI());
Insert.addActionListener(new GUI());
Column.addActionListener(new GUI());
//Adding Panel to Frame
//Period7.add(P7_Panel);
Period7.setVisible(true);
}
And finally my ending listener code
public void actionPerformed(ActionEvent e)
{
String buttonCommand = e.getActionCommand();
//Main menu Period 7 button
if(buttonCommand.equals("Period 7"))
{
myFrame.dispose();
createFramePERIOD7();
}
if(buttonCommand.equals("Home"))
{
setWindow();
Period7.dispose();
}
Your method adds 3 buttons everytime... You can fix it by changing your
createFramePERIOD7() method
By inserting the line indicated below.
public static void createFramePERIOD7() {
//Creates Panel + Buttons
JPanel P7_Panel = new JPanel();
JButton Column = new JButton("Add Columns");
JButton Insert = new JButton("Insert Student 7");
JButton Back = new JButton("Home");
Period7 = new JFrame(); //<-------------------------- Insert this line
//Adding Buttons and Layout to Period 7 Frame
Period7.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Period7.setBounds(550,200,1000,600);
Period7.setLayout(new FlowLayout());
Period7.add(Back);
Period7.add(Column);
Period7.add(Insert);
//Add ActionListener to Buttons
Back.addActionListener(new GUI());
Insert.addActionListener(new GUI());
Column.addActionListener(new GUI());
//Adding Panel to Frame
//Period7.add(P7_Panel);
Period7.setVisible(true);
}
Related
When i run this program sometimes shows me all buttons, but sometimes only 2 or 3 or 4 or 5 or even just 1.. why is that??
I really do not get it. There should always be 6 buttons, but it doesnt show them. Is there any logical reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class testnet
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Knjigarna");
frame.setVisible(true);
frame.setSize(800,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("Prikazi vse");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("Prikazi knjigo");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Dodaj knjigo");
panel.add(button3);
button3.addActionListener (new Action3());
JButton button4 = new JButton("Brisi knjigo");
panel.add(button4);
button4.addActionListener (new Action4());
JButton button5 = new JButton("Uredi knjigo");
panel.add(button5);
button5.addActionListener (new Action5());
JButton button6 = new JButton("Izhod");
panel.add(button6);
button6.addActionListener (new Action6());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("Pikaz vseh knjig");
frame2.setVisible(true);
frame2.setSize(500,800);
JLabel label = new JLabel("Seznam vseh knjig:");
JPanel panel = new JPanel();
JTextField text1=new JTextField("Naslov: ");
JTextField text2=new JTextField("Avtor: ");
frame2.add(panel);
panel.add(label);
panel.add(text1);
panel.add(text2);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("Prikaz knjige");
frame3.setVisible(true);
frame3.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige:");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Dodajanje knjige");
frame4.setVisible(true);
frame4.setSize(600,300);
JLabel label = new JLabel("Vpisi podtke o knjigi");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
static class Action4 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame5 = new JFrame("Brisanje knjige");
frame5.setVisible(true);
frame5.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis brisati");
JPanel panel = new JPanel();
frame5.add(panel);
panel.add(label);
}
}
static class Action5 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame6 = new JFrame("Urejanje knjige");
frame6.setVisible(true);
frame6.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis urejati");
JPanel panel = new JPanel();
frame6.add(panel);
panel.add(label);
}
}
static class Action6 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
try something with layout. JFrame and or remove managed by inside with a content pane. content pane default layout is BorderLayout. so you need to try border layout stuff.
or you can try this code in you main method
frame.setLayout(new FlowLayout());
this will add component by one by one.
for more about layout you can get in here
This is just a fix and not really an explanation of why the problem is occurring.
Call frame.revalidate() after adding all the buttons.
From the Java Docs,
public Component add(Component comp)
This method
changes layout-related information, and therefore, invalidates the
component hierarchy. If the container has already been displayed, the
hierarchy must be validated thereafter in order to display the added
component.
UPDATE UPDATE UPDATE
thank you :))) I did What u told me
I put frame.add(FirstScreen) first
they appeared .....
but now the events are not working , why???????
Can u help me again???
I'm sorry ........
..................
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class InterFace extends JFrame implements ActionListener,ItemListener
{
JFrame frame = new JFrame("Al-murshed Dictionary");
JPanel FirstScreen = new JPanel();
JPanel SecondScreen = new JPanel();
JPanel ThirdScreen = new JPanel();
JPanel ForthScreen = new JPanel();
JButton Translate = new JButton ("Translate");
JButton About = new JButton ("About");
JButton Help= new JButton ("Help");
JButton Quit= new JButton ("Quit");
JButton Quit1= new JButton ("Quit");
JButton Quit2= new JButton ("Quit");
JButton Back= new JButton ("Back");
JButton Back1= new JButton ("Back");
JTextField WordField = new JTextField("Write Your Word Here",50);
JTextArea ArbField = new JTextArea(40,40);
JTextArea EngField = new JTextArea(40,40);
CardLayout c1 = new CardLayout ();
public InterFace()
{
FirstScreen.setLayout(c1);
SecondScreen.add(WordField);
SecondScreen.add(Translate);
ThirdScreen.add(Back);
ForthScreen.add(Back1);
ThirdScreen.add(Quit1);
ForthScreen.add(Quit2);
FirstScreen.add(SecondScreen,"1");
FirstScreen.add(ThirdScreen,"2");
FirstScreen.add(ForthScreen,"3");
JPanel controlButtons = new JPanel();
controlButtons.add(Help);
controlButtons.add(About);
controlButtons.add(Quit);
JPanel wordTranslate = new JPanel();
wordTranslate.add(WordField);
wordTranslate.add(Translate);
JPanel controlTextArea = new JPanel();
controlTextArea.add(EngField);
controlTextArea.add(ArbField);
c1.show(FirstScreen,"1");
About.addActionListener(this);
Back.addActionListener(this);
Help.addActionListener(this);
Back1.addActionListener(this);
Quit.addActionListener(this);
Quit1.addActionListener(this);
Quit2.addActionListener(this);
frame.add(FirstScreen);
Container pane = frame.getContentPane();
pane.add(wordTranslate, BorderLayout.NORTH);
pane.add(controlTextArea, BorderLayout.CENTER);
pane.add(controlButtons, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
//EventHandler
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==About)
c1.show(FirstScreen,"2");
if(e.getSource()==Help)
c1.show(FirstScreen,"3");
if(e.getSource()==Quit)
System.exit(0);
if(e.getSource()==Quit1)
System.exit(0);
if(e.getSource()==Quit2)
System.exit(0);
if(e.getSource()==Back)
c1.show(FirstScreen,"1");
if(e.getSource()==Back1)
c1.show(FirstScreen,"1");
}
public static void main (String args[])
{
InterFace d = new InterFace ();
}
}
pane.add(controlTextArea, BorderLayout.CENTER);
...
frame.add(FirstScreen);
First you add the text area panel to the content pane.
Then you add the "FirstScreen" to the frame.
The problem is that when you add the "FirstScreen" to the frame you are really adding it to the content pane of the frame. So basically you are replacing the text area panel with the first screen.
Also, follow Java naming conventions. Variable names should NOT start with an upper case character.
The button "closebutton" does not respond. I'm very new to java and I know the error has something to do with actionpreformed in the nested if. I've set up a test to see if words will print the the console when closebutton is pressed. They don't. Any help is appreciated
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class myGuiTester implements ActionListener
{
JPanel pane = new JPanel();
JPanel mainPanel = new JPanel();
JFrame MenuFrame = new JFrame("Main Menu");
JFrame Instructions = new JFrame("Instructions");
JFrame game = new JFrame("Game");
JPanel gamepan = new JPanel();
JFrame inst = new JFrame("Instructions");
JPanel instpan = new JPanel(new FlowLayout());
JButton playButton = new JButton("Play");
JButton instButton = new JButton("Instructions");
JButton exitButton = new JButton("Exit");
JButton closebutton = new JButton("Close");
public static void main(String[] args)
{
new myGuiTester ();
}
public myGuiTester ()
{
MenuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inst.setVisible(false);
game.setVisible(false);
JLabel title = new JLabel(" Slot Machine");
JLabel blank = new JLabel("");
JLabel blank1 = new JLabel("");
JLabel blank2 = new JLabel("");
JLabel blank3 = new JLabel("");
playButton.addActionListener(this);
instButton.addActionListener(this);
JLabel game1 = new JLabel("Test");
JLabel inst1 = new JLabel();
exitButton.addActionListener(this);
closebutton.addActionListener(this);
pane.setLayout(new GridLayout(9,1));
pane.add(blank);
pane.add(title);
pane.add(blank1);
pane.add(playButton);
pane.add(blank2);
pane.add(instButton);
pane.add(blank3);
pane.add(exitButton);
mainPanel.add(pane);
MenuFrame.setContentPane(mainPanel);
MenuFrame.setSize(500,400);
MenuFrame.setVisible(true);
//Game Panel
game.setContentPane(gamepan);
game.setSize(500,400);
game1.setText("Game goes here");
gamepan.add(game1);
//Instructions Panel
inst.setContentPane(instpan);
inst.setSize(500,300);
inst1.setText("Instructions go here.");
instpan.add(inst1);
instpan.add(closebutton);
}
//ActionListener
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals("Play"))
{
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
MenuFrame.setVisible(false);
System.out.print("test play");
}
else if (e.getActionCommand().equals("Instructions"))
{
inst.setVisible(true);
//suspected error
if (e.getActionCommand().equals("Close"))
{
System.out.print("Test inst");
inst.setVisible(false);
}
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
}
You must handle "Close" in the elseif- statement but not inside "Instructions. I should be its own block like:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Play")) {
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
MenuFrame.setVisible(false);
System.out.print("test play");
} else if (e.getActionCommand().equals("Instructions")) {
inst.setVisible(true);
// suspected error
}else if (e.getActionCommand().equals("Close")) {
System.out.print("Test inst");
inst.setVisible(false);
} else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
When you check which button is called you are comparing the ActionCommand of the Event with the label of the button, which are not the same thing :
e.getActionCommand().equals("Close")
What you should do is checking if the button IS the source of the event
e.getSource() == closeButton
I really didn't now how to form the question i have a gridlayout with 4 buttons. When the user press Add module i want under the buttons a form instead of a new windows if this is possible.
frame = new JFrame("ModuleViewer");
makeMenu(frame);
Container contentPane = frame.getContentPane();
// Specify the layout manager with nice spacing
contentPane.setLayout(new GridLayout(0, 2));
addModule = new JButton("Toevoegen Module");
contentPane.add(addModule);
overview = new JButton("Overzicht Modules");
contentPane.add(overview);
addSchoolweeks = new JButton("Aapassen schoolweken");
contentPane.add(addSchoolweeks);
weekheavy = new JButton("Weekbelasting");
contentPane.add(weekheavy);
frame.pack();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
frame.setVisible(true);
I know that i first need to add een action method for the buttons i know how to do that so that isn't important. I only want to know how i could create a layout under the buttons so when a user clicks the layout will be draw.
Each panel can only have one layout, but you can use multiple panels for the desired effect: a top panel using GridLayout to hold your buttons, and a bottom panel using CardLayout to hold multiple other panels, one for each button click. Each of these panels can use whatever layout you want, depending on its contents.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements Runnable
{
final static String CARD1 = "Red";
final static String CARD2 = "Green";
final static String CARD3 = "Blue";
JPanel cards;
CardLayout cardLayout;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new CardLayoutDemo());
}
public void run()
{
JButton btnRed = createButton("Red");
JButton btnGreen = createButton("Green");
JButton btnBlue = createButton("Blue");
JPanel buttons = new JPanel(new GridLayout(1,3));
buttons.add(btnRed);
buttons.add(btnGreen);
buttons.add(btnBlue);
JPanel card1 = new JPanel();
card1.setBackground(Color.RED);
JPanel card2 = new JPanel();
card2.setBackground(Color.GREEN);
JPanel card3 = new JPanel();
card3.setBackground(Color.BLUE);
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, CARD1);
cards.add(card2, CARD2);
cards.add(card3, CARD3);
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(buttons, BorderLayout.NORTH);
f.add(cards, BorderLayout.CENTER);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JButton createButton(final String name)
{
JButton button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
cardLayout.show(cards, name);
}
});
return button;
}
}
I'm trying to use a grid layout to make a GUI window. I add all my components and it compiles but when it runs it doesn't show anything. I'm trying to make a simple layout grouped and stacked like this.
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
Here is my code
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
You've added nothing to the JFrame that your class above extends. You need to add your components to containers whose hierarchy eventually leads to the top level window, to the this if you will. In other words, you have no add(someComponent) or the functionally similar this.add(someComponent)method call in your code above.
Consider adding all of your JPanels to a single JPanel
Consider adding that JPanel to the JFrame instance that is your class by calling add(thatJPanel).
Even better would be to not extend JFrame and just to create one when needed, but that will likely be the subject of another discussion at another time.
Before setVisible (true) statement add following statements:
add (introP);
add (timeP);
add (gravityP);
add (answerP);
add (buttonsP);
There is nothing in your JFrame. That is the reason
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setLayout(new GridLayout(5, 1));
this.add(introP);
this.add(timeP);
this.add(gravityP);
this.add(answerP);
this.add(buttonsP);
setTitle("Falling Distance Calculator");
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.validate();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TurnerRandyFallingGUI();
}
});
}
}
Consider the following
In GridLayout, the first parameter is Rows, Second is columns
Never set the size of JFrame manually. Use pack() method to decide
the size
Use SwingUtilities.InvokeLater() to run the GUI in another thread.