How to display another class in a gui class java? - java

I'm trying to create an employee payroll system. Im creating a dropdown menu with JMenuItem Add Employee, and when you click that menu item then it will display another jframe below to enter in all the employee details. I have the add employee JFrame made and it runs perfectly. So i was wondering how do link the two? This is a part of it that might help
public static void main(String[] args) {
final JFrame frame = new JFrame("Payroll");
//create the Employee menu
JMenu employee = new JMenu("Employee");
employee.setMnemonic(KeyEvent.VK_E);
employee.add(new JMenuItem("Add"));
final JMenuItem add = new JMenuItem();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (add.isSelected()) {
JFrame f = new EmployeeTaxDetails1();
final JFrame frame = new JFrame();
f.setVisible(true);
frame.setVisible(false);
}
}});

JInternal Frame is a frame within a frame in java so you should probably use JInternalFrame
You can learn how to use it here.

Related

How to get a JFrame in Swing

I'm working on a simple app and I need to access JFrame created when initializing a program from different places where it's not always possible to access it directly (e.g. contentPane is empty so SwingUtilities.getWindowAncestor(Component) won't work). Is there any other way to do this? For example, this is a class resposinble for initialization:
public final class Application{
public static void start(){
//Empty screen with menu
SwingUtilities.invokeAndWait(() -> {
JFrame frame = new JFrame("Main frame");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Start");
menuBar.add(menu);
frame.setJMenuBar(menuBar);
});
}
}
And I need to use it from some other places, e.g.
JPanel panel = new JPanel();
//initialize the panel
//push it to the content pane of Main frame
So, in order to share the main frame I tend to wrap it in a singleton class and then provide a static method. Maybe there is another way of doing that?
You can store it in a static reference:
public final class Application{
static JFrame mainFrame; //static attribute
public static void start(){
//Empty screen with menu
SwingUtilities.invokeAndWait(() -> {
JFrame frame = new JFrame("Main frame");
mainFrame = frame; //Storing in static attribute
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Start");
menuBar.add(menu);
frame.setJMenuBar(menuBar);
});
}
}
An call it as follows:
JPanel panel = new JPanel();
//initialize the panel
Application.mainFrame.getContentPane().add(panel);
This is a ugly solution maybe you can review Design Patterns for a better solution:
http://www.tutorialspoint.com/design_pattern/

How to identify which button the mouse has entered using mouse listener in Dr Java

how do I set the Jlabel info3 to different text messages depending on which button the mouse hovers over? Right now I do not know how to distinguish which button the mouse is currently hovering over. Here is my code
import javax.swing.*;//You need these two libraries to do the GUI stuff
import java.awt.*;
import java.awt.event.*;
public class GUI_integrator extends JFrame implements ActionListener, MouseListener//You are telling Java that this is a GUI application
{
// *** CREATE THE GUI COMPONENTS: Here we are only creating the following: Buttons, Labels, and Text field
//buttons
JButton EI = new JButton ("Emotional intelligence");//emotional intelligence test button
JButton MI = new JButton ("Multiple intelligences");//multiple intelligences test
JButton MB = new JButton ("Myers-Briggs assessment");//myers-briggs assessment
JButton LS = new JButton ("Learning styles");//learning styles test
JButton CP = new JButton ("Career preferences");//career preferences test
//panels
JPanel p1 = new JPanel();// panel for the information
JPanel p2 = new JPanel();//panel for the selection of tests
JPanel p3 = new JPanel();// panel to display information on the tests
//labels
JLabel info1 = new JLabel("Welcome! Please take a variety of tests so information can be gathered in order to determine what ",JLabel.RIGHT);
JLabel info2 = new JLabel ("learning strategies will be most beneficial to you ", JLabel.RIGHT);
JLabel info3 = new JLabel ("Select the desired test");
// **********
// *** CONSTRUCTOR - Has the same name as the class and it runs once (when the program begins)
// This is were the GUI should be configured.
public GUI_integrator() //This section adds the components on to the frame
{
setTitle("Psychology Simulator 2015"); //Set the window title or frame
setSize(640, 480); //Set the dimensions of
FlowLayout fl1 = new FlowLayout(); //used to organize window
GridLayout g1 = new GridLayout();
g1.setColumns(1);
g1.setRows(5);
setLayout(g1);
//set the layout of the panels
p1.setLayout(fl1);
p2.setLayout(fl1);
p3.setLayout(fl1);
//add welcome greeting to first panel
p1.add(info1);
p1.add(info2);
p3.add(info3);
//add buttons to second panel
p2.add(EI);
p2.add(MI);
p2.add(MB);
p2.add(LS);
p2.add(CP);
//add the panels
add(p1);
add(p2);
add(p3);
//add action listeners to buttons
EI.addActionListener(this);
MI.addActionListener(this);
MB.addActionListener(this);
LS.addActionListener(this);
CP.addActionListener(this);
//add mouse listeners
EI.addMouseListener(this);
MI.addMouseListener(this);
MB.addMouseListener(this);
LS.addMouseListener(this);
CP.addMouseListener(this);
setVisible(true); // display the gui on the screen
setResizable(false); //the user cannot resize the window
}
public void actionPerformed(ActionEvent event)
{
String command =event.getActionCommand();
//check to see if buttons are pressed
if (command.equals ("Emotional intelligence"))
{}
if (command.equals("Multiple intelligences"))
{}
if (command.equals("Myers-Briggs assessment"))
{}
if (command.equals("Learning styles"))
{}
if (command.equals("Career preferences"))
{}
}
public void mouseExited(MouseEvent event)
{}
public void mousePressed(MouseEvent event)
{}
public void mouseEntered(MouseEvent event)
{info3.setText("hi");}
public void mouseReleased (MouseEvent event)
{}
public void mouseClicked(MouseEvent event)
{}
// **** This is the main method - It just starts the GUI
public static void main(String[] args) {
GUI_integrator frame1 = new GUI_integrator(); //start the GUI!
}
}
The information about the Component that generated the event is containted in the MouseEvent itself:
public void mouseEntered(MouseEvent event)
{
Component c = event.getComponent();
System.out.println(c);
}
For other events you would use the getSource() method.

invisible JMenuBar, Accelerator not working

My Program has a JMenuBar with JMenuItems.
They have a ActionListener, and I set a Shortcut with setAccelerator.
Now I am hiding the menu bar when the window become unfocused, to get more space for a displayed image.
But after the first hiding of the menubar, the hotkeys just stop working.
How can I fix that?
I created a little example code to illustrate that strange behavior:
import javax.swing.*;
import java.awt.event.*;
class Example extends JFrame{
public static void main(String[] args) {
new Example(); //main is static
}
static JMenuBar menubar; //be accessable for the ActionListener
Example() {
//JPanel
this.setSize(50,50);
this.setVisible(true);
//Menubar, static
menubar = new JMenuBar();
this.setJMenuBar(menubar);
//Menu
JMenu filemenu = new JMenu("File");
menubar.add(filemenu);
//Item
JMenuItem menuitem = new JMenuItem("Do Something...");
filemenu.add(menuitem);
menuitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.SHIFT_DOWN_MASK)); // Shift + D
menuitem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action!");
}
});
JButton button = new JButton("Show/Hide menubar");
this.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Toggle Bar!");
menubar.setVisible(!menubar.isVisible()); //Toggle
}
});
}
}
For reference:
I'm using Java 1.7.0_60-ea (Java 7) on a Mac.
But this error occurs independent of using the Mac native menu bar or the normal java menu bar inside the JFrame.
You could try to add global keybindings. How to add keybindings is explained here.
Here is an example of what you could do:
//Any component that is always visible in the window (like the image)
JComponent c;
//Get input and action map
InputMap imap = c.getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap amap = c.getActionMap();
//Put keybinding and action
imap.put(KeyStroke.getKeyStroke("shift D"), "doSomething");
amap.put("doSomething", anAction);
Note that it only works in the focused window. But should work regardless of the menubar being visible or not.

Creating Distinct Datamodels for jTables in different internal frames

First, let me point out that I'm new to programming Java Desktop GUI's. I have created a desktop pane that can hold multiple JInternalFrames. For now, each JinternalFrame contains the same GUI components and a new jInternalFrame (Herein referred to as Internal Frame) can be created via a menu item click.
The elements on each internal Frame are as follows: 3 Jlabels, 3 JTextFields, a Jbutton and a Jtable. After rendering the first Internal Frame I populate the 3 text fields with information and then click the button and a new row is added to the table. The row contains the information used to populate the text fields.
Opening a second Internal Frame gives me, visually, the exact interface of the first. I populate this frame in the same manner,click the button and voila, the table in the second frame is populated.
The issue arises when I return to the previous internal frame. I can type into the text fields without issue but clicking the button to populate the table causes the table in the second Internal Frame to be populated. I suspect that I'm sharing a datamodel but am uncertain as to how to create distinct datamodels for jInternalFrame jTables when the GUI for each frame is the same.
Below is the code (as I am new to Java Desktop GUI development I followed one of the Oracle How-To's to render the internal Frame itself - very simple example):
public class InternalFrames extends JFrame
implements ActionListener {
private static final long serialVersionUID = 1L;
JDesktopPane desktop;
JLabel label1;
JLabel label2;
JLabel label3;
JLabel label4;
JTextField text1;
JTextField text2;
JTextField text3;
JTable table1;
public InternalFrames(){
super("Practice Internal Frames");
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset,inset,screenSize.width - (inset*2),screenSize.height - (inset*2));
desktop = new JDesktopPane();
createFrame();
setContentPane(desktop);
setJMenuBar(setMenuBar());
}
protected JMenuBar setMenuBar(){
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Document");
menu.setMnemonic(KeyEvent.VK_D);
menuBar.add(menu);
JMenuItem menuItem = new JMenuItem("New");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.ALT_MASK));
menuItem.setActionCommand("New");
menuItem.addActionListener(this);
menu.add(menuItem);
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK));
menuItem.setActionCommand("Quit");
menuItem.addActionListener(this);
menu.add(menuItem);
return menuBar;
}
public void actionPerformed(ActionEvent e){
if ("New".equals(e.getActionCommand())){
createFrame();
} else if ("Quit".equals(e.getActionCommand())){
}
}
protected void createFrame(){
InternalFrame internalFrame = new InternalFrame();
label1 = new JLabel("Name");
label2 = new JLabel("Email Address:");
label3 = new JLabel("Mobile Number:");
label4 = new JLabel("Test Frames");
label1.setSize(100,10);
label2.setSize(100,10);
label3.setSize(100,10);
label4.setSize(200,10);
text1 = new JTextField(40);
text2 = new JTextField(40);
text3 = new JTextField(40);
internalFrame.setLayout(new MigLayout());
internalFrame.getContentPane().add(label1);
internalFrame.getContentPane().add(text1, "wrap");
internalFrame.getContentPane().add(label2);
internalFrame.getContentPane().add(text2, "wrap");
internalFrame.getContentPane().add(label3);
internalFrame.getContentPane().add(text3,"wrap");
internalFrame.getContentPane().add(label4, "span 2, wrap");
internalFrame.getContentPane().add(new JScrollPane(createTable()), "span 2 2, wrap");
internalFrame.getContentPane().add(createButton());
internalFrame.setVisible(true);
desktop.add(internalFrame);
try {
internalFrame.setSelected(true);
} catch (java.beans.PropertyVetoException pve){ }
}
protected JTable createTable(){
DefaultTableModel dModel = new DefaultTableModel();
table1 = new JTable(dModel);
dModel.addColumn("Name");
dModel.addColumn("Email Address");
dModel.addColumn("Mobile Number");
return table1;
}
protected JButton createButton(){
JButton button1 = new JButton("Add New List Member");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
populateTable(table1);
}
});
return button1;
}
protected void populateTable(JTable theTable){
if (validateEntry() == 0)
{
ListMembers listMember = new ListMembers();
listMember.setName(text1.getText());
listMember.setEmailAddress(text2.getText());
listMember.setMobilePhone(text3.getText());
Object[] data = {listMember.getName(),listMember.getEmailAddress(),listMember.getMobilePhone()};
DefaultTableModel dm = (DefaultTableModel) table1.getModel();
dm.addRow(data);
}
}
private static void createAndShowGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
InternalFrames internalFrame = new InternalFrames();
internalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
internalFrame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Any help would be greatly appreciated.
Each time you create a new frame, you initialize a single field (table1) with this newly created table. And the listener of every button you create populates the table referenced by this unique table1 variable. The same goes for your text fields, etc.
Either only use local variables, and pass them between methods (for example, you need to pass the table you just created to the method creating the button, in order for this button to populate this table. Or you extract all the code to a new class, MyInternalFrame (choose a better name), make the table, textfields and buttons instance fields of this new class, and create a new instance of this MyInternalFrame class each time you need a new one.
This second solution looks like the best one to me.

How do I open new windows from menubars?

This is my code so far:
public static void main(String[] args){
JFrame frame = new JFrame("Breakout!");
frame.setLocation(300, 300);
//Making the menubar
JMenuBar mb = new JMenuBar();
frame.setJMenuBar(mb);
JMenu fileMenu = new JMenu("File");
mb.add(fileMenu);
JMenuItem newAction = new JMenuItem("About");
fileMenu.add(newAction);
newAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("open new window here");
}
});
BreakoutCourt c = new BreakoutCourt();
frame.add(c);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
I am making a Breakout game. I want to make an About window that displays information about the game (like, how to play it and so on). How would I go about doing that? Thank you for the help! I'm very new to Java Swing, so yeah.
You could do a simple one with the message type of JOptionPane:
JOptionPane.showMessageDialog(frame, "Breakout! v1.0");
(You'll need to make the frame final to do this, since it's being accessed from within the anonymous action listener).
For more control over what is displayed, and whether it should be modal or not, you could look at JDialog. There's an overview of using dialogs in Swing here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html.

Categories

Resources