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!?!
Related
I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}
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
I am trying to add text in a JTextArea.
But i need some of the text to be strike through and some to added as it is.
I have searched over the internet, but couldn't find any answer.
Any help on what to refer?
JTextArea allow you set font style, but you cannot set style to text partially. Please see the code below, you can use setFont method to specify font with strikethru style, but it applies to all text in the JTextArea:
JTextArea area = new JTextArea();
Font font = new Font("arial", Font.PLAIN, 12);
Map fontAttr = font.getAttributes();
fontAttr.put (TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
Font myFont = new Font(fontAttr);
area.setFont (myFont);
area.setText ("Hello");
Whereas, if you want some text are in strikethru and some not, then you have to use JTextPane with StyledDocument, but I do not recommend this because you need a lot of tweaking to display your content with specific style. Below code may give you the idea:
DefaultStyledDocument doc = new DefaultStyledDocument();
StyleContext sc = new StyleContext();
Style style = sc.addStyle("strikethru", null);
StyleConstants.setStrikeThrough (style,true);
doc.insertString (0, "Hello ", null);
doc.insertString (6, "strike through ", style);
JTextPane pane = new JTextPane(doc);
You can use below code. Here some of the strike text "#11#","#22#" and some to added text "#yicHFRx1nc#" ,"#icHFRx1nc#" which replace of strike text.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JTextAreaExample {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public JTextAreaExample() {
prepareGUI();
}
public static void main(String[] args) {
JTextAreaExample swingControlDemo = new JTextAreaExample();
swingControlDemo.showTextAreaDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("JTextArea Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo() {
headerLabel.setText("JTextArea");
JLabel descriptionLabel = new JLabel("Description: ", JLabel.RIGHT);
final JTextArea descriptionTextArea = new JTextArea("Enter String ", 5, 20);
JScrollPane scrollPane = new JScrollPane(descriptionTextArea);
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String b = descriptionTextArea.getText().replace("#11#", "#yicHFRx1nc#")
.replace("#22#", "#icHFRx1nc#");
System.out.println("b=" + b);
statusLabel.setText(b);
}
});
controlPanel.add(descriptionLabel);
controlPanel.add(scrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
Hi again i've put in my original code just to let you see what i was talking about for the GridBagConstrainsts thats i was trying to put each image to be stuck to the south of the panel immediately next to each other
package prototype;
import java.awt.BorderLayout;
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.JPanel;
import javax.swing.WindowConstants;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
//Declare the class which extends JFrame and
//implements ActionListener to enable bottons to respond whenever clicked or selected
public class Master extends JFrame implements ActionListener {
//create the bottons visible by the user
JButton check = new JButton("");
JButton playList = new JButton("");
JButton update = new JButton("");
JButton quit = new JButton("");
JCheckBox tick = new JCheckBox("Tick");
JPanel top = new JPanel();
public static void main(String[] args) {
//declare object of the class
Master jf = new Master();
}
public Master() {
setLayout(new BorderLayout());
setSize(1050, 400);
setTitle("Master");
// close application only by clicking the quit button
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//show the frame in the middle of the screen when run
setLocationRelativeTo(null);
top.add(new JLabel("Select an option by clicking one of the buttons below"));
add("North", top); // add the text above to the upper part of the frame (North)
JPanel bottom = new JPanel();
bottom.setLayout(new GridBagLayout());
bottom.add(check);
check.addActionListener(this);
bottom.add(playList);
playList.addActionListener(this);
bottom.add(update);
update.addActionListener(this);
bottom.add(quit);
quit.addActionListener(this);
add("South", bottom);
//make the frame non resizable but visible
setResizable(true);
setVisible(true);
try{
Image img = ImageIO.read(getClass().getResource("gui/Exit.png"));
Image resize = img.getScaledInstance(290, 180, 18);
quit.setIcon(new ImageIcon(resize));
img = (bottom, new JLabel("NAME"), 0,0,1,1, GridBagConstraints.SOUTH);
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/Untitled.png"));
Image resize = img.getScaledInstance(290, 180, 18);
check.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/CPL.png"));
Image resize = img.getScaledInstance(290, 180, 18);
playList.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/UpdateLib.png"));
Image resize = img.getScaledInstance(290, 180, 18);
update.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == check) {
new CheckLibrary();
} else if (e.getSource() == update) {
new UpdateLibrary();
} else if (e.getSource() == quit) {
System.exit(0);
} else if (e.getSource() == playList) {
new CreatePlaylist();
}
}
}
For that purposes you need to use anchor and weighty properties of GridBagConstraints.
In next example I set JTextField to the south:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Example extends JFrame {
public Example (){
JTextField f = new JTextField(20);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.SOUTHEAST;
c.weighty = 1;
add(f,c);
}
public static void main(String...strings ){
Example e = new Example();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.pack();
e.setLocationRelativeTo(null);
e.setVisible(true);
}
}
If you need to fill all horizontal space by component add next :
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
For Image you can use JLabel instead of JTextField in my example :
JLabel l = new JLabel(new ImageIcon(getClass().getResource(PATH_TO_IMAGE)));
You cannot add an image directly to a JPanel. What you can do instead is to set the image to be the image icon of a JPanel or JLabel and add that to whatever you're trying to make.
I'm creating an about JFrame for my program. I have an icon which I used for the program and I have that show up as the first thing on the about JFrame, but I'm having issues trying to center the image. If I do some kind of centering it screws up the whole alignment of everything else.
I'm trying to have all the JLabels, other than the icon, to be left aligned. Then have the icon aligned to the center.
I had to remove some personal information, whatever I did remove I put them between "[]".
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JFrame {
public About() {
super("About [PROGRAM]");
setIconImage([PROGRAM].getInstance().setIcon());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel icon = new JLabel("", new ImageIcon(getClass().getResource(Constants.ICON_FULL)), JLabel.CENTER);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
main.add(icon);
main.add(Box.createRigidArea(new Dimension(0, 10)));
main.add(name);
main.add(expandedName);
main.add(copyright);
main.add(credits);
add(main);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Consider using some layouts to help you out. Ones that come to mind include BorderLayout with the icon in the BorderLayout.CENTER position. You can stack stuff on one side using a BoxLayout using JPanel that is added to the main BorderLayout-using JPanel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class About extends JDialog {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"
+ "800px-European_Common_Frog_Rana_temporaria.jpg";
public About(JFrame frame) {
super(frame, "About [PROGRAM]", true);
ImageIcon myIcon = null;
try {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
myIcon = new ImageIcon(img);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JPanel main = new JPanel(new BorderLayout());
main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel centerLabel = new JLabel(myIcon);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
int eb = 20;
centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(name);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(expandedName);
leftPanel.add(copyright);
leftPanel.add(credits);
leftPanel.add(Box.createVerticalGlue());
main.add(centerLabel, BorderLayout.CENTER);
main.add(leftPanel, BorderLayout.LINE_START);
add(main);
pack();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("GUI");
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("About") {
#Override
public void actionPerformed(ActionEvent e) {
About about = new About(frame);
about.setLocationRelativeTo(frame);
about.setVisible(true);
}
}));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}