As of now, I have this
And this is my source code for MyFrame1:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Color;
import java.awt.Color.*;
import java.awt.Font;
import java.awt.Font.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test
{
public static void main(String[] args)
{
new Test();
}
public Test()
{
String line = "";
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
JMenuBar mBar = new JMenuBar();
//creating new JMenuItem
JMenuItem mHelp = new JMenuItem("Help");
JMenuItem mCredits = new JMenuItem("Credits");
JMenuItem mExit = new JMenuItem("Exit");
/*try
{
BufferedReader br = new BufferedReader(new FileReader("1.txt"));
line = br.readLine();
}
catch(Exception e)
{
e.printStackTrace();
}*/
JLabel jUser = new JLabel("User is: " );
mHelp.setOpaque(false);
mHelp.setForeground(Color.DARK_GRAY);
mHelp.setFont(new Font("Verdana", Font.PLAIN,12));
mCredits.setOpaque(false);
mCredits.setForeground(Color.DARK_GRAY);
mCredits.setFont(new Font("Verdana", Font.PLAIN,12));
mExit.setOpaque(false);
mExit.setForeground(Color.DARK_GRAY);
mExit.setFont(new Font("Verdana", Font.PLAIN,12));
mBar.add(mHelp);
mBar.add(mCredits);
mBar.add(mExit);
mBar.add(jUser);
//mBar.add(line);
JFrame frame = new JFrame("MYFRAME");
frame.setJMenuBar(mBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
});
}
public class TestPane extends JPanel
{
public TestPane()
{
setBorder(new EmptyBorder(20, 20, 20, 20));
setLayout(new GridLayout(3, 3, 60, 60));
add(makeButton("Account Code"));
add(makeButton("Unit Details"));
add(makeButton("Item Details"));
add(makeButton("Clearing"));
add(makeButton("Search"));
add(makeButton("Exit"));
}
protected JButton makeButton(String text)
{
JButton btn = new JButton(text);
btn.setFont(new Font("Verdana", Font.PLAIN,18));
btn.setMargin(new Insets(30, 30, 30, 30));
btn.setBackground(Color.blue);
btn.setOpaque(true);
btn.setBorderPainted(false);
return btn;
}
}
}
I am still new and still have a small knowledge about Java and GUI. I am still learning about it so I am doing Trial-Error on my program.
I tried using UIManager, or UILayout, but still not working for me or I still dont know how to use it.
I really want to learn more about GUI and Java, please help me. Any comments, remarks, suggestions are accepted and well-appreciated.
MyFrame1:
As for the output I am aiming for this kind, pls. see next picture.
MyDesireOutput:
Also if you notice there's a bufferedReader, I am practicing to read a "1.txt" with a String, and putting it as label or (still dont know about it) in the menu bar...
First you must know these
JMenuBar:
An implementation of a menu bar. You add JMenu objects to the menu bar
to construct a menu.
JMenu:
An implementation of a menu -- a popup window containing JMenuItems
that is displayed when the user selects an item on the JMenuBar.
JMenuItem:
An implementation of an item in a menu.
So add your JMenuItems to JMenu, later add this JMenu to JMenuBar.
//creating a menu `Options`
JMenu menu = new JMenu("Options");
//creating menu items
JMenuItem mHelp = new JMenuItem("Help");
JMenuItem mCredits = new JMenuItem("Credits");
JMenuItem mExit = new JMenuItem("Exit");
//adding all menu items to menu
menu.add(mHelp);
menu.add(mCredits);
menu.add(mExit);
//adding menu to menu bar
mBar.add(menu);
//aligning label to right corner of window
mBar.add(Box.createHorizontalGlue());
mBar.add(jUser);//label
Output:
You should add your JMenuItems to JMenu objects and then add your JMenus to your JMenuBar.
JMenuBar mBar = new JMenuBar();
//creating new JMenuItem
JMenuItem mHelp = new JMenuItem("Help");
JMenu help = new JMenu("Help");
help.add(mHelp);
JMenuItem mCredits = new JMenuItem("Credits");
JMenu credits = new JMenu("Credits");
credits.add(mCredits);
JMenuItem mExit = new JMenuItem("Exit");
JMenu exit = new JMenu("Exit");
exit.add(exit);
/*try
{
BufferedReader br = new BufferedReader(new FileReader("1.txt"));
line = br.readLine();
}
catch(Exception e)
{
e.printStackTrace();
}*/
JLabel jUser = new JLabel("User is: " );
mHelp.setOpaque(false);
mHelp.setForeground(Color.DARK_GRAY);
mHelp.setFont(new Font("Verdana", Font.PLAIN,12));
mCredits.setOpaque(false);
mCredits.setForeground(Color.DARK_GRAY);
mCredits.setFont(new Font("Verdana", Font.PLAIN,12));
mExit.setOpaque(false);
mExit.setForeground(Color.DARK_GRAY);
mExit.setFont(new Font("Verdana", Font.PLAIN,12));
mBar.add(help);
mBar.add(credits);
mBar.add(exit);
But adding a JLabel to JMenuBar is not a good idea. If you want to have something like you depicted in you question, you may want to add a JPanel to the north region of your frame, and then add the User label to the FlowLayout.TRAILING region of that panel:
mBar.add(help);
mBar.add(credits);
mBar.add(exit);
//mBar.add(jUser);
//mBar.add(line);
JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
statusPanel.add(jUser);
statusPanel.add(new JLabel("Loen Seto"));
JFrame frame = new JFrame("MYFRAME");
frame.setJMenuBar(mBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(statusPanel, BorderLayout.NORTH);
frame.add(new TestPane(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
Good Luck
Related
I want to have a layout like this:
The grey areas will be two different menus.
I managed to make the split panes, but I can't seem to add the menus, here's my code:
package View;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.plaf.basic.BasicSplitPaneUI;
public class TaskView extends JFrame{
JMenuBar menuBar;
JMenu addTask, refresh;
private int screenHeight,screenWidth;
public TaskView() {
setTitle("TASKS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
Toolkit myScreen = Toolkit.getDefaultToolkit();
Dimension screenSize = myScreen.getScreenSize();
screenHeight = screenSize.height;
screenWidth = screenSize.width;
setSize(screenWidth/2,screenHeight/2);
System.out.println(screenWidth/2);
setLocation(screenWidth/4,screenHeight/4);
placeComponents(this.getContentPane());
}
private void placeComponents(Container contentPane) {
JPanel jsp1 = new JPanel();
JPanel jsp2 = new JPanel();
JLabel j1 = new JLabel("Area 1");
JLabel j2 = new JLabel("Area 2");
menuBar = new JMenuBar();
addTask = new JMenu("Add Task");
refresh = new JMenu("Refresh");
menuBar.add(addTask);
menuBar.add(refresh);
jsp1.add(menuBar);
jsp1.add(j1);
jsp2.add(j2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true, jsp1, jsp2);
splitPane.setUI(new BasicSplitPaneUI());
splitPane.setOneTouchExpandable(false);
contentPane.add(splitPane);
splitPane.setEnabled(false);
setVisible(true);
splitPane.setDividerLocation(300);
}
}
Every time I try to add a menu it makes a mess in the left panel and it dosn't look at all like a menu, how can i add the menus without it looking like shit?
try this
public class TaskView extends JFrame {
public TaskView() throws HeadlessException {
createGUI();
}
private void createGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createPanel(), createPanel());
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JPanel createPanel() {
JPanel panel = new JPanel(new BorderLayout());
JMenuItem menuItem1 = new JMenuItem("MenuItem 1");
JMenuItem menuItem2 = new JMenuItem("MenuItem 2");
JMenuItem menuItem3 = new JMenuItem("MenuItem 3");
JMenu menu = new JMenu("Main");
menu.add(menuItem1);
menu.addSeparator();
menu.add(menuItem2);
menu.add(menuItem3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
menuBar.add(new JMenu("View"));
panel.add(menuBar, BorderLayout.PAGE_START);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TaskView().setVisible(true));
}
}
I need help creating a GUI (total newcomer :-( ..)
Created this with GridLayout, but now I want the text on the LEFT to be centered in the middle of the TextArea. Is it possible without using "\n" all the time?
Code:
public class guiFrame {
JLabel label;
JMenuBar menubar;
JTextArea area;
public guiFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(600,200));
frame.getContentPane().setBackground(Color.BLACK);
JPanel panel = new JPanel(new BorderLayout());
panel.setLayout(new GridLayout(1, 2));
frame.add(panel);
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu aenderFarb = new JMenu("Ändere Farbe");
menubar.add(aenderFarb);
JMenuItem blak = new JMenuItem("schwarz");
JMenuItem whit = new JMenuItem("weiß");
aenderFarb.add(blak);
aenderFarb.add(whit);
JTextArea area = new JTextArea("Hallo, Welt! Hier kann man Text reinschreiben...");
panel.add(area);
panel.setBackground(Color.BLACK);
JLabel label = new JLabel("");
label.setBackground(Color.BLACK);
panel.add(label);
frame.setVisible(true);
}
}
The purpose of this post is to answer you question, but also demonstrate the use of MCVE for future question.
See comments for explanations:
//include imports to make code MCVE
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
//use right java naming convention
public class GuiFrame {
JLabel label;
JMenuBar menubar;
JTextArea area;
public GuiFrame() throws BadLocationException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(600,200));
frame.getContentPane().setBackground(Color.BLACK);
//no point in assigning BorderLayout which is not used
//JPanel panel = new JPanel(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.setBackground(Color.BLACK);
frame.add(panel);
//remove what is not essential for the question
//to make code and MCVE
//JMenuBar menubar = new JMenuBar();
//to set horizontal alignment you need to use a JTextpane
//JTextArea area = new JTextArea("Hallo, Welt! Hier kann man Text reinschreiben...");
String text = "Hallo, Welt! Hier kann man Text reinschreiben...";
StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);
Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT);
document.insertString(document.getLength(), text, style);
JTextPane area = new JTextPane(document);
panel.add(area);
//vertical alignment is not supported.
//see possible solutions here: http:
//stackoverflow.com/questions/29148464/align-jtextarea-bottom
//remove what is not essential for the question
//to make code and MCVE
//JMenuBar menubar = new JMenuBar();
//JLabel label = new JLabel("");
frame.setVisible(true);
}
//include a main to make code an MCVE
public static void main(String[] args) {
try {
new GuiFrame();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
I know how to code Java but I'm having a lot of trouble with this. I've made a menubar but I want to put a split pane underneath it. The menubar is fine but the split pane is giving me a lot of errors and I don't know how to fix it.
Any help would be much appreciated.
package getcodinggui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
public class GetCodingGUI {
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu;
menuBar = new JMenuBar();
menu = new JMenu("Home");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"File Menu Items");
menuBar.add(menu);
menu = new JMenu("About");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Contact Us");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("FAQ");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Log In");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static class MyJFrameWin extends JFrame{
JSplitPane jSplitPane, jSplitPane2;
JPanel jPanel1, jPanel2a, jPanel2b;
jPanel1 = new JPanel();
jPanel2a = new JPanel();
jPanel2b = new JPanel();
jSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jPanel2a, jPanel2b);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setDividerLocation(100);
jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
jPanel1, jSplitPane2);
jSplitPane.setOneTouchExpandable(true);
jSplitPane.setDividerLocation(150);
getContentPane().add(jSplitPane);
}
}
//Create and set up the content pane.
GetCodingGUI demo = new GetCodingGUI();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(1280, 720);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(runJSplitPaneLater);
}
javax.swing.SwingUtilities.invokeLater(new Runnable, runJSplitPaneLater()
{
static Runnable runJSplitPaneLater = new Runnable(){
#Override
public void run() {
MyJFrameWin myJFrameWin = new MyJFrameWin();
myJFrameWin.setVisible(true);
createAndShowGUI();
}
});
}
}
I had to clean up 20 compile errors.
Here's the GUI I created.
Here are the changes I made.
I rearranged all of your code. Code is much easier to understand when it reads from top to bottom.
Since the SwingUtilities invokeLater method requires a Runnable, I made your GUI view class implement Runnable.
I put your content pane in one of the JSplitPanes. I just guessed which pane.
I put the outer JSplitPane into the JFrame.
I fixed your menu alt keys.
I returned a JPanel from your createContentPane method.
I formatted your code.
I reduced the size of your JFrame so it would fit on my screen.
Here's the code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class GetCodingGUI implements Runnable {
private JTextArea output;
private JScrollPane scrollPane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new GetCodingGUI());
}
#Override
public void run() {
// Create and set up the window.
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane jSplitPane, jSplitPane2;
JPanel jPanel1, jPanel2a, jPanel2b;
jPanel1 = new JPanel();
jPanel2a = new JPanel();
jPanel2b = createContentPane();
jSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jPanel2a,
jPanel2b);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setDividerLocation(100);
jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jPanel1,
jSplitPane2);
jSplitPane.setOneTouchExpandable(true);
jSplitPane.setDividerLocation(150);
frame.add(jSplitPane);
frame.setJMenuBar(createMenuBar());
// Display the window.
frame.setSize(800, 600);
frame.setVisible(true);
}
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu;
menuBar = new JMenuBar();
menu = new JMenu("Home");
menu.setMnemonic(KeyEvent.VK_H);
menu.getAccessibleContext().setAccessibleDescription("File Menu Items");
menuBar.add(menu);
menu = new JMenu("About");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Contact Us");
menu.setMnemonic(KeyEvent.VK_C);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("FAQ");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Log In");
menu.setMnemonic(KeyEvent.VK_L);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
return menuBar;
}
public JPanel createContentPane() {
// Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
// Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
// Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
}
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 am creating a simple messenger in Java(just for learning purposes) and I am trying to have a friends tab that, on the left side is the list of friends, and the right side is the messages with the friend that you click on, but whenever I try to add the JSplitPane in the tab, but it doesn't display. I have done this exact same code(except I only did the JSplitPane stuff and its components, not the other tabs and the menus and such.
All my code
package Client;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane, friendChatScrollPane, friendListScrollPane;
JSplitPane friendsSplitPane;
JTextArea friendChatArea, testArea;
JTextField friendChatField, testField;
JList friendList;
Box box;
DefaultListModel friends;
public ClientMain() {
super("Messenger Client");
//Networking();
/** MAIN PANEL **/
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
/** TEST PANEL **/
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
/** FRIENDS PANEL **/
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
friends = new DefaultListModel();
//method here that retrieves users' friends from the server and adds them to the friends DefaultListModel
friends.addElement("Person1");
friends.addElement("Person2");
friendList = new JList(friends);
friendList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
friendList.setLayoutOrientation(JList.VERTICAL_WRAP);
friendList.setVisibleRowCount(3);
friendList.setSize(50, 50);
friendChatArea = new JTextArea();
friendChatArea.setSize(50, 50);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
friendChatArea.append("TEST");
Dimension minimumSize = new Dimension(100, 50);
friendListScrollPane = new JScrollPane(friendList);
friendListScrollPane.setMinimumSize(minimumSize);
friendChatScrollPane = new JScrollPane(friendChatArea);
friendChatScrollPane.setMinimumSize(minimumSize);
friendsSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, friendListScrollPane, friendChatScrollPane);
friendsSplitPane.setOneTouchExpandable(false);
friendsSplitPane.setDividerLocation(50);
friendsPanel.add(friendsSplitPane);
/** TEST PANEL **/
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
/** SET UP **/
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void createSplitPane() {
friendListScrollPane = new JScrollPane();
friendListScrollPane.add(new JLabel("Hello"));
friendChatArea = new JTextArea();
friendChatArea.setBounds(0, 150, HEIGHT, HEIGHT);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
Dimension minimumSize = new Dimension(WIDTH/2 , HEIGHT);
friendListScrollPane.setMinimumSize(minimumSize);
//friendsSplitPane.setLeftComponent()
friendsSplitPane.add(friendChatArea);
friendsSplitPane.setRightComponent(friendChatScrollPane);
}
}
The specific JSplitPane code(part of the code above)
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
friends = new DefaultListModel();
//method here that retrieves users' friends from the server and adds them to the friends DefaultListModel
friends.addElement("Person1");
friends.addElement("Person2");
friendList = new JList(friends);
friendList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
friendList.setLayoutOrientation(JList.VERTICAL_WRAP);
friendList.setVisibleRowCount(3);
friendList.setSize(50, 50);
friendChatArea = new JTextArea();
friendChatArea.setSize(50, 50);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
friendChatArea.append("TEST");
Dimension minimumSize = new Dimension(100, 50);
friendListScrollPane = new JScrollPane(friendList);
friendListScrollPane.setMinimumSize(minimumSize);
friendChatScrollPane = new JScrollPane(friendChatArea);
friendChatScrollPane.setMinimumSize(minimumSize);
friendsSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, friendListScrollPane, friendChatScrollPane);
friendsSplitPane.setOneTouchExpandable(false);
friendsSplitPane.setDividerLocation(50);
friendsPanel.add(friendsSplitPane);
friendsPanel.setLayout(null);
your friendsPanel has the null layout and you are adding split pane as:
friendsPanel.add(friendsSplitPane);
to add a component to a container(friendsPanel) with null layout, you must specify the bound of the component you are adding with component.setBounds() method. But seriously why are even using null layout ? Don't use it. It has been already advice from page to page in by the swing family of stack overflow. Try to use one of the layout manager the Swing developer has created for us with effort wasting time from day after day just to save our own time.
Start learning : Lesson: Laying Out Components Within a Container. Let us give some value their efforts for saving our time, which we are spending just to find the answer: uhh! where is my component!?!