How do I open a JFrame from a button click - java

I making a game but I have a main meny and too outer menys and I want to open one of the menys by clicking on the respective button in the JFrame.
code of main.java
package main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import game.client.mainClient;
import game.server.mainServer;
public class main extends JPanel {
/**
*
*/
private static final long serialVersionUID = 6590770928148744094L;
private JLabel jcomp1;
private JButton jcomp5;
private JButton jcomp6;
private JLabel jcomp8;
private JLabel jcomp9;
private JLabel jcomp10;
public main() {
//construct components
jcomp1 = new JLabel ("test game");
jcomp5 = new JButton ("singel player");
jcomp6 = new JButton ("multiplayer");
jcomp8 = new JLabel ("this game is made by kebe_");
jcomp9 = new JLabel ("gui is made in guigenie");
jcomp10 = new JLabel ("game verision dev 1.0");
//adjust size and set layout
setPreferredSize (new Dimension (681, 466));
setLayout (null);
//add components
add (jcomp1);
add (jcomp5);
add (jcomp6);
add (jcomp8);
add (jcomp9);
add (jcomp10);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (295, 5, 70, 25);
jcomp5.setBounds (265, 30, 115, 30);
jcomp6.setBounds (265, 65, 115, 30);
jcomp8.setBounds (0, 430, 180, 25);
jcomp9.setBounds (0, 415, 155, 20);
jcomp10.setBounds (0, 445, 140, 25);
// close and open
// singleplayer
jcomp5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
mainClient mc = new mainClient();
mc.setVisible(true);
}
});
// multiplayer
jcomp6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
mainServer ms = new mainServer();
ms.setVisible(true);
}
});
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Test game");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new main());
frame.pack();
frame.setVisible (true);
}
}
code of mainClient.java
package game.client;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class mainClient extends JPanel
{
/**
*
*/
private static final long serialVersionUID = -1271816540338950462L;
private JLabel jcomp1;
private JComboBox jcomp2;
private JButton jcomp3;
public mainClient() {
//construct preComponents
String[] jcomp2Items = {"save 1", "save 2", "save 3", "save 4", "save 5"};
//construct components
jcomp1 = new JLabel ("singel player");
jcomp2 = new JComboBox (jcomp2Items);
jcomp3 = new JButton ("play selected save");
//adjust size and set layout
setPreferredSize (new Dimension (681, 466));
setLayout (null);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (290, 5, 85, 25);
jcomp2.setBounds (280, 30, 100, 25);
jcomp3.setBounds (255, 70, 150, 25);
jcomp3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Singel player");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new mainClient());
frame.pack();
frame.setVisible (true);
}
}
code of mainServer
package game.server;
import java.awt.*;
import javax.swing.*;
public class mainServer extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 2726545572728204122L;
private JLabel jcomp1;
private JButton jcomp2;
private JButton jcomp3;
public mainServer() {
//construct components
jcomp1 = new JLabel ("multiplayer");
jcomp2 = new JButton ("host game");
jcomp3 = new JButton ("join game");
//adjust size and set layout
setPreferredSize (new Dimension (681, 466));
setLayout (null);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (300, 0, 75, 25);
jcomp2.setBounds (285, 25, 100, 25);
jcomp3.setBounds (285, 50, 100, 25);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Multiplayer");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new mainServer());
frame.pack();
frame.setVisible (true);
}
}
how can I open the JFrame in mainClient.java when I click on the singleplayer button, and the JFrame in mainServer.java when I click on the multiplayer button?

Create ActionListeners for your buttons. Define your frames, and you can access them with your class name. For example;
class mainClient extends JPanel {
JFrame mainClientFrame = new JFrame();
}
and then;
mainClient mc = new mainClient();
mc.mainClientFrame.setVisible(true);
if you want to use this frames in your main void, define them static.
class mainClient extends JPanel {
static JFrame mainClientFrame = new JFrame();
}

Related

How to get ArrayList from another class to show up inside a JComboBox?

I'm trying to build a program and I am having trouble getting my ArrayList from another class to show up in a JComboBox. My program will look something like this but before where "Melissa" is written, I want to have a JComboBox that has a list of users and be able to select from it to get the results:
UPDATE Here is my error:
----jGRASP exec: javac -g UserHistory.java
UserHistory.java:20: error: cannot find symbol
String[] userListItems = users.toArray(new String[0]);
^
symbol: variable users
location: class UserHistory
Note: UserHistory.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Here is my incomplete code which gives me an error because it cannot locate my arrayList:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = users.toArray(new String[0]);
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
}
}
Here's my code for another panel that contains the ArrayList:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public ArrayList<User> users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
Here's my User class that was used to make the ArrayList:
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
// public String toString() {
// return userName + "\n";
// }
}
First of all you would better call user manager module from history main like
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
Which will start both JPanels so you can manage users and watch history at the same time.
Additionally,
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
And one more thing, as soon as you initialize userlist you need to attach a listener like below:
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
These two corrections would you make be able to list user names on the combo box and the dynamic change of user list would be reflected to the listing in the box.
Cheers.
Let me upload the whole source code here
User.java -- Source code just follows (I don't know why they came out of box.)
package userchorelist;
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
}
ManageUsersGUI.java -- Source code just follows (I don't know why they came out of box, again.)
package userchorelist;
import javax.swing.;
import java.awt.;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public static ArrayList users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
UserHistory.java -- Source code just follows (I don't know why they came out of box, third and final time.)
import java.awt.;
import javax.swing.;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import userchorelist.ManageUsersGUI;
import static userchorelist.ManageUsersGUI.manageUsers;
import static userchorelist.ManageUsersGUI.users;
import userchorelist.User;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = new String[users.size()];
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
}
}
I suggest you add receive the list of users as an explicit parameter in both classes UserHistory and ManageUsersGUI:
class UserHistory
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
class ManageUsersGUI
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
Then, you can create a unique list of users as an external class, let's say UserManagement, and make it a singleton:
public class UserManagement
{
private static final UserManagement INSTANCE=new UserManagement();
private final List<User> list=new ArrayList<User>();
public static UserManagement getInstance()
{
return INSTANCE;
}
private UserManagement()
{
}
public List<User> getUsers()
{
return users;
}
}
Then, you must provide the list of users when instatiating both classes in the main methods (and further, future instatiations you may have):
public static void main (String[] args) {
...
UserManagement.getInstance().getUsers().add("winkum");
UserManagement.getInstance().getUsers().add("blinkum");
UserManagement.getInstance().getUsers().add("nod");
frame.getContentPane().add (new UserHistory(UserManagement.getInstance().getUsers()));
...
}

Set Layout of panel within CardLayout

I am trying to create a UI for an imaginary vehicle that has both Automatic and Manual modes. When the user sets the vehicle into one of the modes, it should only display the controls relevant to that mode, and I've accomplished this using a CardLayout.
However, I'd also like to be able to specify the location of the various elements of the layout for each card manually - for a static layout I'd do something along the lines of mainPanel.setLayout(null), but this simply gives a blank window when used on a CardLayout (hence the two commented-out lines in the code below).
How would I achieve both of these things? My current code is below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UI extends JFrame implements ActionListener{
public UI() {
initUI();
}
private JPanel cardPanel;
private CardLayout cardLayout = new CardLayout();
public final void initUI() {
cardPanel = new JPanel();
cardPanel.setLayout(cardLayout);
JPanel manualPanel = new JPanel();
getContentPane().add(manualPanel);
//manualPanel.setLayout(null);
cardPanel.add(manualPanel, "manual");
JPanel autoPanel = new JPanel();
//autoPanel.setLayout(null);
cardPanel.add(autoPanel, "auto");
JButton startButton = new JButton("START/STOP");
startButton.setBounds(50, 150, 200, 50);
startButton.addActionListener(new startListener());
manualPanel.add(startButton);
autoPanel.add(startButton);
JButton autoButton = new JButton("SWITCH TO AUTO");
autoButton.setBounds(50, 250, 200, 50);
autoButton.addActionListener(new autoListener());
manualPanel.add(autoButton);
JButton upButton = new JButton("^");
upButton.setBounds(125, 320, 50, 50);
upButton.addActionListener(new returnListener());
manualPanel.add(upButton);
JButton downButton = new JButton("\\/");
downButton.setBounds(125, 380, 50, 50);
downButton.addActionListener(new returnListener());
manualPanel.add(downButton);
JButton ccwButton = new JButton("<-");
ccwButton.setBounds(55, 350, 50, 50);
ccwButton.addActionListener(new returnListener());
manualPanel.add(ccwButton);
JButton cwButton = new JButton("->");
cwButton.setBounds(195, 350, 50, 50);
cwButton.addActionListener(new returnListener());
manualPanel.add(cwButton);
JButton ngzButton = new JButton("SOMETHING ELSE");
ngzButton.setBounds(50, 450, 200, 50);
ngzButton.addActionListener(new returnListener());
manualPanel.add(ngzButton);
JButton manualButton = new JButton("SWITCH TO MANUAL");
manualButton.setBounds(50, 250, 200, 50);
manualButton.addActionListener(new manualListener());
autoPanel.add(manualButton);
JButton returnButton = new JButton("SOMETHING ELSE");
returnButton.setBounds(50, 350, 200, 50);
returnButton.addActionListener(new returnListener());
autoPanel.add(returnButton);
setTitle("UI");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(cardPanel, BorderLayout.NORTH);
}
public static void main(String[] args) {
UI ui = new UI();
ui.setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
private class returnListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
}
}
private class autoListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
cardLayout.show(cardPanel, "auto");
}
}
private class startListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
}
}
private class manualListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
cardLayout.show(cardPanel, "manual");
}
}
}
In your example, you create a startButton, but you then attempt to add the same instance to two different panels. Because a component can only occupy one container, you'll need to create two buttons, one for each panel.
As an aside, instead of using a null layout, give each panel BorderLayout, add the buttons to a JPanel having the default FlowLayout, and add the button panel to the SOUTH. You can then nest your illustrations in the CENTER using whatever layout is appropriate.
Addendum: As #Frakcool comments, using a layout will improve the cross-platform appearance of your buttons. Invoke pack() on the enclosing window, and override getPreferredSize() on the nested illustration panel to give it the needed size. In this related example, the CENTER panel is used for drawing only; having no components, its layout then becomes irrelevant.

Problems with having a "this" statement in my source

so this is the current code and it has been so far working except for the background color, anything that has "//" before it is what causes errors between other things
package com.Luminate.luminatemedia;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame implements ActionListener{
static JFrame mediaform = new JFrame();
public static void main(String[] args) {
}
public static void load() {
ImageIcon fileIcon = new ImageIcon ("assets/icon.png");
ImageIcon exitIcon = new ImageIcon ("assets/exit.png");
JButton exitButton = new JButton();
JLabel text = new JLabel("Luminate Media");
JPanel panel = new JPanel();
mediaform.add(panel);
panel.add(exitButton);
panel.add(text);
mediaform.setTitle("Luminate");
mediaform.setIconImage(fileIcon.getImage());
mediaform.setBounds(0, 688, 1366, 40);
//mediaform.setLayout(null);
mediaform.setUndecorated(true);
mediaform.setResizable(false);
mediaform.setVisible(true);
mediaform.setAlwaysOnTop(true);
//mediaform.getContentPane().setBackground(Color.DARK_GRAY);
mediaform.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text.setFont(new Font("dandelion in the spring", Font.PLAIN, 32));
text.setBounds(0, 0, 0, 0);
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setSize(0, 0);
text.setForeground(Color.black);
text.setHorizontalAlignment(0);
exitButton.setBorder(null);
exitButton.setBounds(1326, 0, 40, 40);
exitButton.addActionListener(null);
exitButton.setIcon(exitIcon);
//BELOW IS MY ISSUE
exitButton.addActionListener(this);
panel.setLayout(null);
panel.setBackground(DARK_GRAY);
}
#Override
public void actionPerformed(ActionEvent e) {
//code to close the whole program
}
}
so there's an error with the emphasized text where it says "this"
also what would the code be to close the main class at the click of the button and am I doing this correctly ?
Try this
public class Window extends JFrame implements ActionListener{
public static void main(String[] args) {
new Window();
}
public Window() {
ImageIcon fileIcon = new ImageIcon ("assets/icon.png");
ImageIcon exitIcon = new ImageIcon ("assets/exit.png");
JButton exitButton = new JButton("Label");
JLabel text = new JLabel("Luminate Media");
JPanel panel = new JPanel();
setTitle("Luminate");
setIconImage(fileIcon.getImage());
setBounds(0, 688, 1366, 40);
setLayout(null);
setUndecorated(true);
setResizable(false);
setVisible(true);
setAlwaysOnTop(true);
getContentPane().setBackground(Color.DARK_GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text.setFont(new Font("dandelion in the spring", Font.PLAIN, 32));
text.setBounds(0, 0, 0, 0);
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setSize(0, 0);
text.setForeground(Color.black);
text.setHorizontalAlignment(0);
exitButton.setBorder(null);
exitButton.setBounds(1326, 0, 40, 40);
exitButton.setIcon(exitIcon);
exitButton.addActionListener(this);
panel.setLayout(null);
panel.setBackground(DARK_GRAY);
panel.add(exitButton);
panel.add(text);
add(panel);
}
#Override
public void actionPerformed(ActionEvent e) {
//code to close the whole program
}
}

Why isn't anything showing up in my JFrame?

Why is my GUI not showing any buttons, labels, or text fields?
I think I have it all setup, but when I run it, only the frame shows, and none of the contents appear.
package BasicGame;
import java.awt.Container;
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.JTextField;
import javax.swing.SwingConstants;
public class Gui extends JFrame{
private static final long serialVersionUID = 1L;
private JLabel label;
private JTextField textField;
private JButton button;
private buttonHandler bHandler;
public Gui(){
setTitle("Basic Gui");
setResizable(false);
setSize(500, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
pane.setLayout(null);
button = new JButton("button");
button.setBounds(50, 60, 50, 70);
bHandler = new buttonHandler();
button.addActionListener(bHandler);
label = new JLabel("Hello", SwingConstants.RIGHT);
label.setBounds(50, 60, 50, 70);
textField = new JTextField(10);
textField.setBounds(50, 60, 50, 70);
pane.add(button);
pane.add(label);
pane.add(textField);
}
public class buttonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
#SuppressWarnings("unused")
public static void main(String[] args){
Gui gui = new Gui();
}
}
Move your setVisible() to the end of the constructor. You are adding all of your components after you set your JFrame up and make is visible, so you don't see any of the changes.
This should show your JFrame with all the components:
public Gui(){
setTitle("Basic Gui");
setResizable(false);
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
pane.setLayout(null);
button = new JButton("button");
button.setBounds(50, 60, 50, 70);
bHandler = new buttonHandler();
button.addActionListener(bHandler);
label = new JLabel("Hello", SwingConstants.RIGHT);
label.setBounds(50, 60, 50, 70);
textField = new JTextField(10);
textField.setBounds(50, 60, 50, 70);
pane.add(button);
pane.add(label);
pane.add(textField);
setVisible(true); // Move it to here
}
Here's what the frame's looked like before and after I moved the setVisible statement and compiled your code.
Before:
After:

Java Open a new window by clicking a button

Been sitting here at my computer for about 13 hours and I think my eyes are bleeding.
I found a little gui editor I love called GuiGenie.
It works perfect for creating the window with the buttons and all that good stuff.
The problem is i want to click a button in my first menu and have it open my other menu i made.
I just starting programming 4 weeks ago so I'm a complete noob.
I have a feeling its messing up because of the main methods but I have no idea and 13 hours of sitting here trying millions of things is making me go crazy : )
here is what i got so far
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
public MyPanel() {
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("How long were you parked?");
jcomp3 = new JLabel ("Minutes");
jcomp4 = new JButton ("openNewWindow");
//adjust size and set layout
setPreferredSize (new Dimension (315, 85));
setLayout (null);
//add components
add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
//set component bounds (only needed by Absolute Positioning)
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setBounds (0, 0, 315, 25);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
When the button is pressed, I want it to open this new window
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPanel2 extends JPanel {
private JButton jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JTextField jcomp4;
public MyPanel2() {
//construct components
jcomp1 = new JButton ("test1");
jcomp2 = new JButton ("test2");
jcomp3 = new JButton ("test3");
jcomp4 = new JTextField (5);
//adjust size and set layout
setPreferredSize (new Dimension (395, 156));
setLayout (null);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (20, 45, 100, 25);
jcomp2.setBounds (135, 60, 100, 25);
jcomp3.setBounds (260, 35, 100, 25);
jcomp4.setBounds (105, 115, 100, 25);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel2());
frame.pack();
frame.setVisible (true);
}
}
If anyone could help I would appreciate it greatly!!
I have a lot of respect for you pros out there because if you are a pro at this, you are probably smarter than 99.9% of the world.
This stuff hurts my brain.
Here is something you can do, for this situation, where you have multiple Forms or Windows what you can do is to use a JPanel which can have this CardLayout set as it's LayoutManager and then you can add the two JPanels to it and access them with the methods provided by the same.
Don't use setBounds() when using Absolute Positioning this is really not the right way of putting components to the parent container. Instead use setLocation(...) and setSize(...) methods. Consider not to use Absolute Positioning as much as possible for you. Certain lines in favour of the before said line taken from Java Docs are as follows :
Although it is possible to do without a layout manager, you should use a
layout manager if at all possible. A layout manager makes it easier to
adjust to look-and-feel-dependent component appearances, to different
font sizes, to a container's changing size, and to different locales.
Layout managers also can be reused easily by other containers, as well as
other programs.
Since the output of your program is really not a soothing experience in any sense. Atleast LayoutManager, can make that work a lot more easier for you, since you need not have to specify position and size for each and every component. Try walking through the Layout Mangers Tutorials, and get accustomed to them as soon as possible. They are the real life savers :-)
Here is a modified code taken from your SOURCE CODE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
panel2 = new MyPanel2();
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("How long were you parked?");
jcomp3 = new JLabel ("Minutes");
jcomp4 = new JButton ("openNewWindow");
//adjust size and set layout
setPreferredSize (new Dimension (315, 85));
setLayout (null);
//set component bounds (only needed by Absolute Positioning)
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
//add components
add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
}
}
class MyPanel2 extends JPanel {
private JButton jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JTextField jcomp4;
public MyPanel2() {
//construct components
jcomp1 = new JButton ("test1");
jcomp2 = new JButton ("test2");
jcomp3 = new JButton ("test3");
jcomp4 = new JTextField (5);
//adjust size and set layout
setPreferredSize (new Dimension (395, 156));
setLayout (null);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (20, 45, 100, 25);
jcomp2.setBounds (135, 60, 100, 25);
jcomp3.setBounds (260, 35, 100, 25);
jcomp4.setBounds (105, 115, 100, 25);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
}
}
Here is the code for myPanel class, use this one:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
public MyPanel() {
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("How long were you parked?");
jcomp3 = new JLabel ("Minutes");
jcomp4 = new JButton ("openNewWindow");
jcomp4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel2());
frame.pack();
frame.setVisible (true);
}
});
//adjust size and set layout
setPreferredSize (new Dimension (315, 85));
setLayout (null);
//add components
add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
//set component bounds (only needed by Absolute Positioning)
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setBounds (0, 0, 315, 25);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel());
frame.pack();
frame.setVisible (true);
}
}

Categories

Resources