I made a simple GUI in Java, which includes a menu, context menu, button, toolbar, check box and status bar. However, the button and toolbar are not displaying. This is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class test extends JFrame {
private JLabel statusbar;
private JPopupMenu menu;
private Toolkit toolkit;
public test() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
getContentPane().add(panel);
toolkit = this.getToolkit();
menu = new JPopupMenu();
JToolBar toolbar1 = new JToolBar();
JToolBar toolbar2 = new JToolBar();
ImageIcon iconNew = new ImageIcon(getClass().getResource("new.png")); // Icons
ImageIcon iconOpen = new ImageIcon(getClass().getResource("open.png"));
ImageIcon iconSave = new ImageIcon(getClass().getResource("save.png"));
ImageIcon iconExit = new ImageIcon(getClass().getResource("exit.png"));
JButton newb = new JButton(iconNew); // Declaring Buttons for Toolbar
JButton openb = new JButton(iconOpen);
JButton saveb = new JButton(iconSave);
JButton exitb = new JButton(iconExit);
toolbar1.add(newb); // Adding Buttons to Toolbar1
toolbar1.add(openb);
toolbar1.add(saveb);
toolbar1.setAlignmentX(0); // Alignment of Toolbar1
toolbar2.add(exitb); // Adding Buttons to Toolbar2
toolbar2.setAlignmentX(0); // Alignment of Toolbar2
exitb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(toolbar1);
panel.add(toolbar2);
add(panel, BorderLayout.NORTH);
JMenuBar menubar = new JMenuBar(); // JMenuBar
JMenu file = new JMenu("File");
JMenu view = new JMenu("View");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", iconExit); // Exit Menu Item
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
ActionEvent.CTRL_MASK));
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JMenuItem nMenuItem = new JMenuItem("New", iconNew); // New Menu Item
nMenuItem.setToolTipText("New File");
JMenuItem oMenuItem = new JMenuItem("Open", iconOpen);
oMenuItem.setToolTipText("Open File");
JMenuItem sMenuItem = new JMenuItem("Save", iconSave);
sMenuItem.setToolTipText("Save File");
JMenu imp = new JMenu("Import..."); // Import Sub-Menu Item
imp.setMnemonic(KeyEvent.VK_M);
imp.setToolTipText("Import Data");
JMenuItem newsf = new JMenuItem("Import newsfeed list...");
JMenuItem bookm = new JMenuItem("Import bookmarks...");
JMenuItem mail = new JMenuItem("Import mail...");
imp.add(newsf); // Adding Sub-menu Items to Menu
imp.add(bookm);
imp.add(mail);
file.add(nMenuItem); // Adding Menu Items to "File" Menu-List
file.add(oMenuItem);
file.add(sMenuItem);
file.addSeparator();
file.add(imp);
file.addSeparator();
file.add(eMenuItem);
JButton quitButton = new JButton("Quit"); // Quit Button
quitButton.setBounds(870, 380, 80, 30);
quitButton.setToolTipText("Press me");
quitButton.setBackground(new Color(66, 89, 205));
quitButton.setForeground(new Color(255, 255, 255));
quitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JButton nextButton = new JButton("Next >"); // Next Button
nextButton.setBounds(770, 380, 80, 30);
nextButton.setToolTipText("Next...");
nextButton.setBackground(new Color(66, 89, 205));
nextButton.setForeground(new Color(255, 255, 255));
nextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(quitButton); // Adding Buttons to panel
panel.add(nextButton);
JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar"); // Creating
// Status-bar
// Check-box
sbar.setState(true);
sbar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (statusbar.isVisible()) {
statusbar.setVisible(false);
} else {
statusbar.setVisible(true);
}
}
});
view.add(sbar); // Adding Check-box to the View Menu-List
JMenuItem menuItemBeep = new JMenuItem("Beep"); // Beep option in Pop-Up
menuItemBeep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
toolkit.beep();
}
});
menubar.add(file); // Adding Menu-Lists to Menu Bar
menubar.add(view);
menu.add(menuItemBeep); // Adding Beep option in Pop-Up
JMenuItem menuItemClose = new JMenuItem("Close"); // Close option in
// Pop-Up
menuItemClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(menuItemClose); // Adding Close option in Pop-Up
this.addMouseListener(new MouseAdapter() { // Mouse Listener for Pop-Up
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
setJMenuBar(menubar); // Menu-bar???
statusbar = new JLabel(" Statusbar"); // Creating Status Bar
statusbar.setBorder(BorderFactory
.createEtchedBorder(EtchedBorder.RAISED));
add(statusbar, BorderLayout.SOUTH);
panel.setLayout(null); // Panel Design and additional Arguments
panel.setBackground(new Color(18, 33, 110));
this.setTitle("My First GUI in Java");
this.setSize(1000, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
test ex = new test();
ex.setVisible(true);
}
});
}
}
I'm very new to this so any comments are appreciated.
Thank you!
"However, the button and toolbar are not displaying."
Looking through your init() method, I only see you adding two components to your frame.
add(panel, BorderLayout.NORTH);
add(statusbar, BorderLayout.SOUTH);
Then with the same panel as above, you set the layout to null, when you first already specified it to be a BoxLayout
panel.setLayout(null);
I comment the above code out, and some components appear.
You are setting the Layout of panel twice once at beginning:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
and once later on:
panel.setLayout(null);
You should try getting rid of the second one. That should fix the problem
Related
So I'm making a simple AutoClicker just to test myself. Now I've ran into a small problem. I am trying to make it so when I use "control + minus" it stops the auto clicker. Problem is I have to have the jframe focused to do so. Is there any way I get the key the user touched outside of the jframe?
For example: Your playing cookie clicker and you hit "control and =" to start the auto clicker, then you can stop it while playing cookie clicker by doing "control and +"
My Listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "exit") {
GUIs.frame.dispose();
AutoClicker.getTimer().cancel();
} else if(e.getActionCommand() == "start") {
} else if(e.getActionCommand() == "stop") {
AutoClicker.getTimer().cancel();
}
}
}
My GUI:
import java.awt.Event;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class GUIs
{
public static JFrame frame = new JFrame("AutoClicker");
private JPanel panel = new JPanel();
private GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private int width = gd.getDisplayMode().getWidth();
private int height = gd.getDisplayMode().getHeight();
//Componenets
private static JButton startbutton = new JButton("Start");
private static JLabel autoclick = new JLabel("AutoClicker 2.0");
public void createMainGui() {
//frame
frame.setSize(width/2,height/2);
frame.setResizable(true);
frame.setLocation(width/4, height/4);
//JPanel
panel.setLayout(null);
panel.setSize(frame.getWidth(), frame.getHeight());
//JMenu -> Different method
createJMenu(frame);
//Initialize Components
//startbutton.setBounds((frame.getWidth() / 2), (frame.getHeight()), 100, 25);
//Add components
panel.add(startbutton);
frame.add(panel);
//show frame
frame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
System.out.println(e);
resizeComponents(frame);
}
});
frame.setVisible(true);
}
public static void createJMenu(JFrame fr) {
//Menu Bar
JMenuBar jbar = new JMenuBar();
//Listener -> different class
JListener l = new JListener();
//Exit Menu
JMenu exitmenu = new JMenu("Exit");
jbar.add(exitmenu);
//Exit Item
JMenuItem exit = new JMenuItem("Exit");
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));
exit.setActionCommand("exit");
exit.addActionListener(l);
exitmenu.add(exit);
//Options Menu
JMenu optionsmenu = new JMenu("Options");
jbar.add(optionsmenu);
//Start Item
JMenuItem start = new JMenuItem("Start");
start.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Event.CTRL_MASK));
start.setActionCommand("start");
start.addActionListener(l);
optionsmenu.add(start);
//Stop Item
JMenuItem stop = new JMenuItem("Stop");
stop.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Event.CTRL_MASK));
stop.setActionCommand("stop");
stop.addActionListener(l);
optionsmenu.add(stop);
//set JMenu to frame
fr.setJMenuBar(jbar);
}
public void resizeComponents(JFrame frame) {
System.out.println(frame.getHeight());
startbutton.setBounds((frame.getWidth() / 2) - 50, (int) (frame.getHeight() / 1.5), 100, 25);
frame.revalidate();
frame.repaint();
}
}
Thank you!
Here is my code. I want to open another Java form using menu bar but when I click on menu item, it shows me an error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
adding a window to a container
What should I do now?
package Driver;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
public class frmTestMenu extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frmTestMenu frame = new frmTestMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frmTestMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100,653, 425);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 434, 31);
contentPane.add(menuBar);
JMenu mnFile = new JMenu("FIle");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
frmTestMenu.this.dispose();
}
});
mnFile.add(mntmExit);
JMenu mnItem = new JMenu("Item1");
menuBar.add(mnItem);
JMenuItem mntmMenuItem = new JMenuItem("open Test Internal Form");
mnItem.add(mntmMenuItem);
JMenuItem mntmMenuItem_3 = new JMenuItem("open Test Internal Form 2");
mnItem.add(mntmMenuItem_3);
JMenu mnItem_1 = new JMenu("item 2");
menuBar.add(mnItem_1);
JMenuItem mntmMenuItem_1 = new JMenuItem("Menu 2 item 1");
mnItem_1.add(mntmMenuItem_1);
JMenu mnItem_2 = new JMenu("item 3");
menuBar.add(mnItem_2);
JMenuItem mntmMenuItem_2 = new JMenuItem("Menu 3 item 1");
mnItem_2.add(mntmMenuItem_2);
final JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBounds(0, 0, 633, 366);
mntmMenuItem.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
frm3_0 test1 = new frm3_0();
test1.setBounds(10, 10, 426, 229);
desktopPane.add(test1);
test1.setVisible(true);
}
});
mntmMenuItem_3.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
frmcity_A test2 = new frmcity_A();
test2.setBounds(10, 10, 426, 229);
desktopPane.add(test2);
test2.setVisible(true);
}
});
JScrollPane scrollPane = new JScrollPane(desktopPane);
JDesktopPane desktopPane_1 = new JDesktopPane();
desktopPane_1.setBounds(145, 88, 1, 1);
desktopPane.add(desktopPane_1);
scrollPane.setBounds(0, 30, 633, 336);
contentPane.add(scrollPane);
}
}
I am attempting to create a custom popup menu.
Hard requirements are the following:
1) Speech bubble shape
2) Transparency
3) Menu is open until closed via a close button
I have managed to achieve all three of the above, but when I attempt to add a normal sub-menu, it just won't work. It renders as if it were a sub menu, but does not seem to register mouse interaction. I even tried adding an ActionListener to the menu directly, but that had no effect.
** EDIT ** Adding new sample based on feedback as lack of layout and color are not applicable to the problem I am trying to solve, original sample follows the new one
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.RoundRectangle2D;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
public class CustomMenu extends JFrame
{
public CustomMenu()
{
super();
setUndecorated(true);
setAlwaysOnTop(true);
setOpacity(0.75f);
setSize(100, 110);
setLocation(800, 600);
setShape(new RoundRectangle2D.Float(0, 0, 100, 110, 25, 25));
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setBackground(Color.black);
JButton closeButton = new JButton();
closeButton.setSize(16, 16);
closeButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
CustomMenu.this.dispose();
}
});
closeButton.setLocation(75, 5);
getContentPane().add(closeButton);
JLabel label = new JLabel("Menu Title");
label.setSize(90, 25);
getContentPane().add(label);
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
separator.setSize(90,5);
getContentPane().add(separator);
JMenu menu = new JMenu("Sub Menu");
JMenuItem menuItem = new JMenuItem("Sub Menu Item One");
menuItem.setSize(100, 25);
menu.add(menuItem);
menuItem = new JMenuItem("Sub Menu Item Two");
menuItem.setSize(100, 25);
menu.add(menuItem);
menu.setSize(100, 25);
getContentPane().add(menu);
menuItem = new JMenuItem("Menu Item One");
menuItem.setSize(100, 25);
getContentPane().add(menuItem);
menuItem = new JMenuItem("Menu Item Two");
menuItem.setSize(100, 25);
getContentPane().add(menuItem);
menuItem = new JMenuItem("Menu Item Three");
menuItem.setSize(100, 25);
getContentPane().add(menuItem);
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new CustomMenu().setVisible(true);
}
});
}
}
Simplest self contained example I could come up with is below. Thanks in advance for any assistance.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
public class CustomMenu extends JFrame
{
public CustomMenu()
{
super();
setUndecorated(true);
setAlwaysOnTop(true);
setOpacity(0.75f);
setSize(100, 110);
setLocation(800, 600);
setShape(new RoundRectangle2D.Float(0, 0, 100, 110, 25, 25));
setLayout(null);
setBackground(Color.black);
JButton closeButton = new JButton();
closeButton.setSize(16, 16);
closeButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
CustomMenu.this.dispose();
}
});
closeButton.setLocation(75, 5);
add(closeButton);
JLabel label = new JLabel("Menu Title");
int y = 0;
label.setLocation(10, y);
label.setSize(90, 25);
add(label);
y += label.getHeight();
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
separator.setSize(90,5);
separator.setLocation(5, y);
add(separator);
y += separator.getHeight();
JMenu menu = new JMenu("Sub Menu");
JMenuItem menuItem = new JMenuItem("Sub Menu Item One");
menuItem.setBackground(new Color(0,0,0,0));
menuItem.setSize(100, 25);
menuItem.setLocation(0,0);
menu.add(menuItem);
menuItem = new JMenuItem("Sub Menu Item Two");
menuItem.setBackground(new Color(0,0,0,0));
menuItem.setSize(100, 25);
menuItem.setLocation(0,25);
menu.add(menuItem);
menu.setBackground(new Color(0,0,0,0));
menu.setSize(100, 25);
menu.setLocation(-1, y);
add(menu);
y += menu.getHeight();
menuItem = new JMenuItem("Menu Item One");
menuItem.setBackground(new Color(0,0,0,0));
menuItem.setSize(100, 25);
menuItem.setLocation(-1, y);
add(menuItem);
y += menuItem.getHeight();
menuItem = new JMenuItem("Menu Item Two");
menuItem.setBackground(new Color(0,0,0,0));
menuItem.setSize(100, 25);
menuItem.setLocation(-1, y);
add(menuItem);
y += menuItem.getHeight();
menuItem = new JMenuItem("Menu Item Three");
menuItem.setBackground(new Color(0,0,0,0));
menuItem.setSize(100, 25);
menuItem.setLocation(-1, y);
add(menuItem);
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new CustomMenu().setVisible(true);
}
});
}
}
Problems...
Null layout
Negative layout position
Alpha based background color
Swing doesn't like negative positions for its components
Swing can't render alpha based background colors, it only knows how to render opaque and fully transparent components. Using an alpha based color will prevent swing from updating the area beneath the componet, which leads to weird paint artefacts and other issues
Solutions...
Use a appropriate layout manager
See point 1.
Use setOpaque. If you need a translucent background, you'll need to create a custom component and override its paintComponent method and paint the background yourself
It should be noted, you can actually control the popup window that sub menus use, these a created deep down in the bowels of the api (I think maybe even via a static method, but it's been a while since I dug that deep)
I wanted to create this little application for school which automatically calculates the grades you need to get in order to pass. Came up with two classes, the frame class, which basically holds the jframe and the menubar, and the login class which (obviously) handles the login form.
Now when I click on the login button from the menu, I want a new window to pop up and display the login form, which will then continue to load in the grades.
I have no idea how I can do that though, and everything I've tried failed so far.
How can I do this?
Code for class Login:
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login {
public static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(100, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(10, 40, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 40, 160, 25);
panel.add(passwordText);
JButton loginButton = new JButton("Login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
}
}
Code for my Frame class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
#SuppressWarnings("serial")
public class Frame extends JFrame {
Login login = new Login();
public Frame() {
setTitle("Grade calculation");
setSize(300, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
JMenuItem loginAction = new JMenuItem("Log in");
JMenuItem exitAction = new JMenuItem("Close");
JMenuItem cutAction = new JMenuItem("Cut");
JMenuItem copyAction = new JMenuItem("Copy");
JMenuItem pasteAction = new JMenuItem("Paste");
JCheckBoxMenuItem checkAction = new JCheckBoxMenuItem("Inloggegevens onthouden");
fileMenu.add(loginAction);
fileMenu.add(checkAction);
fileMenu.add(exitAction);
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction);
loginAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
exitAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
public static void main(String[] args) {
Frame me = new Frame();
me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
me.setResizable(false);
me.setLocationRelativeTo(null);
me.setVisible(true);
}
}
You could use a pop-up window in Java Swing, see some info here.
Here is the first example from the link above, just creating a simple message dialogue window.
//default title and icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.");
You can put any input fields you need in the pop-up window.
Here is an example that possibly can point you in the right direction with out doing too much of your project. I would not separate my GUI over multiple classes to prevent ever having your frame lose control over what's happening inside of it, a few other reasons as well. You will also probably want to create another class for your data. If you simply want to display the login details and grades in a new frame then you can easily just create another class extending JFrame for that.
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class Frame extends JFrame implements ActionListener{
private JMenuItem loginAction; //defined here to allow access in actionPerformed().
private JMenuItem exitAction;
private JButton loginButton;
public Frame() {
setTitle("Grade calculation");
setSize(300, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
loginAction = new JMenuItem("Log in");
exitAction = new JMenuItem("Close");
JMenuItem cutAction = new JMenuItem("Cut");
JMenuItem copyAction = new JMenuItem("Copy");
JMenuItem pasteAction = new JMenuItem("Paste");
JCheckBoxMenuItem checkAction = new JCheckBoxMenuItem("Inloggegevens onthouden");
fileMenu.add(loginAction);
fileMenu.add(checkAction);
fileMenu.add(exitAction);
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction);
loginAction.addActionListener(this);
exitAction.addActionListener(this);
}
public JPanel loginPanel()
{
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(10, 40, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 40, 160, 25);
panel.add(passwordText);
loginButton = new JButton("Login");
loginButton.addActionListener(this);
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
return panel;
}
public void close()
{
System.exit(0);
}
public void addLogin()
{
add(loginPanel());
validate();
}
//action method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton)
System.out.println("loginButton was pressed so I should do something, maybe?");
if (e.getSource() == loginAction)
addLogin();
if (e.getSource() == exitAction)
close();
}
public static void main(String[] args) {
Frame me = new Frame();
me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
me.setResizable(false);
me.setLocationRelativeTo(null);
me.setVisible(true);
}
}
You will notice that I created the loginPanel() method to return a JPanel when called. When you select the loginAction menu item it will add the panel to the frame. It isn't as easily removed if you wanted to replace it with another panel, but I believe that you want to move away from this frame towards one for purely displaying data after.
This might not be the direction that you wish to go with your project. If not, leave a comment and I will see if I'm able to help.
I have a very simple code that creates a frame object from the class MyJFrame accepts the first string which is used as a title. Place the second string is the text to be displayed in a JScrollPane. You can see the code below. What I need is to use copy and paste of text highlighted. I need help implementing it. So that if copy selected from a menubar it copies the highlighted portion and if paste is pastes it.
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
public class DisplayText
{
private static JTextArea text;
public DisplayText(String title, String info)
{
MyJFrame f = new MyJFrame(title);
Container c = f.getContentPane();
//default text
text = new JTextArea(info);
//Scrollpane
JScrollPane sp = new JScrollPane(text);
c.add( sp );
f.setBounds(100,200, 500, 400 );
f.setVisible(true);
}
Use the Actions that are available in the DefaultEditorKit including DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, and DefaultEditorKit.PasteAction.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.text.*;
public class TestActions {
private String[] texts = {
"Hello", "Goodbye", "What the f***?", "Heck if I know", "Peace out man!"
};
private JTextArea textArea = new JTextArea(10, 30);
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
private JPanel mainPanel = new JPanel();
private JMenuBar menubar = new JMenuBar();
private JPopupMenu popup = new JPopupMenu();
private PopupListener popupListener = new PopupListener();
public TestActions() {
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
btnPanel.add(new JButton(textAction));
menu.add(new JMenuItem(textAction));
popup.add(new JMenuItem(textAction));
}
menubar.add(menu);
JPanel textFieldPanel = new JPanel(new GridLayout(0, 1, 5, 5));
for (String text: texts) {
JTextField textField = new JTextField(text, 15);
textField.addMouseListener(popupListener);
textFieldPanel.add(textField);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
((JTextComponent)e.getSource()).selectAll();
}
});
}
textArea.addMouseListener(popupListener);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel textFieldPanelWrapper = new JPanel(new BorderLayout());
textFieldPanelWrapper.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(btnPanel, BorderLayout.NORTH);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(textFieldPanelWrapper, BorderLayout.EAST);
}
public JComponent getMainPanel() {
return mainPanel;
}
private JMenuBar getMenuBar() {
return menubar;
}
private class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(),
e.getX(), e.getY());
}
}
}
private static void createAndShowGui() {
TestActions testActions = new TestActions();
JFrame frame = new JFrame("Test Actions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(testActions.getMainPanel());
frame.setJMenuBar(testActions.getMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
code borrowed from my answer here.
Edit
You ask in comment:
I appreciate the answer. However, could you make it a bit simpler to understand, I am fairly new to Java.
Sure, here is a simple JMenuBar that holds an edit JMenu that holds JMenuItems for copy, cut, and paste with just that code borrowed from my example. Note that as an aside, you should not setBounds on anything, you should instead set the rows and columns of your JTextArea, and that you should not use a static JTextArea, and in fact no Swing components should ever be static.
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultEditorKit;
public class DisplayText {
private JTextArea text;
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
public DisplayText(String title, String info) {
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
menu.add(new JMenuItem(textAction));
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
JFrame f = new JFrame(title);
f.setJMenuBar(menuBar);
Container c = f.getContentPane();
text = new JTextArea(info, 20, 50);
JScrollPane sp = new JScrollPane(text);
c.add(sp);
// f.setBounds(100,200, 500, 400 );
f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new DisplayText("Title", "This is info text");
}
}