Open another Java form using Menubar - java

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);
}
}

Related

need help debugging. swing event handlers in window builder

I have been trying to attach event handlers to abstract list model. didn't work out so I switched to default list model. now I need help debugging. why do I have so many errors? im working with windowbuilder so I recon it shouldn't be this hard.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Window {
private JFrame frame;
/**
* Launch the application. The main method is the entry point to a Java application.
* For this assessment, you shouldn't have to add anything to this.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. This is the constructor for this Window class.
* All of the code here will be executed as soon as a Window object is made.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame. This is where Window Builder
* will generate its code.
* #return
*/
public JPanel initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem mntmSave = new JMenuItem("Save");
File.add(mntmSave);
JMenuItem mntmLoad = new JMenuItem("Load");
File.add(mntmLoad);
JMenuItem mntmExit = new JMenuItem("Exit");
File.add(mntmExit);
frame.getContentPane().setLayout(null);
JList Left_list = new JList();
Left_list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
}
});
Left_list.setFont(new Font("Tahoma", Font.PLAIN, 14));
Left_list.setModel(new AbstractListModel() {
String[] values = new String[] {"Case", "Motherboard", "CPU", "RAM", "GPU", "HDD", "PSU"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
Left_list.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
Left_list.setBounds(10, 11, 146, 218);
frame.getContentPane().add(Left_list);
JList Right_list = new JList();
Right_list.setModel(new AbstractListModel() {
String[] values = new String[] {};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
Right_list.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
Right_list.setBounds(278, 16, 146, 213);
frame.getContentPane().add(Right_list);
JButton btnNewButton = new JButton("Add>>");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton.setBounds(166, 91, 102, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("<<Remove");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(166, 125, 102, 23);
frame.getContentPane().add(btnNewButton_1);
}
}
}

Implement copy/paste in JTextArea?

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");
}
}

Objects not displaying in GUI - Java

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

JSwing Split Panes won't display

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!?!

Having a bit of trouble with a JScrollPane

I'm trying to make a scrollable JTextArea. I'm not quite sure what's wrong with my code here... When I create this GUI, it doesn't create the chatBox
package GUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
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.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import Client.Client;
#SuppressWarnings("serial")
public class GUI extends JFrame implements KeyListener {
public static JPanel contentPane;
public static JTextField usernameBox;
public static JTextField inputBox;
public static JTextField ipBox;
public static JLabel usernameLabel;
public static JButton connectButton;
public static JButton disconnectButton;
public static JLabel usersLabel;
public static JTextArea usersBox;
public static JTextArea chatBox;
public static JButton sendButton;
public static JLabel ipLabel;
public static JMenuBar menuBar;
public static JMenu file;
public static JMenuItem about;
public static JMenuItem connect;
public static JMenuItem disconnect;
public static JMenuItem setDefaultUsername;
public static JMenuItem setDefaultIP;
public static String setUser;
public static String setIP;
public static String title;
public static JScrollPane scroll = new JScrollPane(chatBox);
#SuppressWarnings("unused")
private static About aboutFrame;
public GUI() {
System.out.println("Creating new client...");
addItems();
System.out.println("DONE");
}
public void addItems() {
// Frame
title = "title";
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 760, 355);
setTitle(title);
setSize(770, 385);
setResizable(false);
// Panel
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
// Username Box
usernameBox = new JTextField();
usernameBox.setBounds(88, 6, 117, 28);
usernameBox.setColumns(10);
contentPane.add(usernameBox);
// Username Label
usernameLabel = new JLabel("Username");
usernameLabel.setBounds(17, 12, 72, 16);
contentPane.add(usernameLabel);
// Connect Button
connectButton = new JButton("Connect");
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Connect");
Client.Connect();
}
});
connectButton.setBounds(365, 7, 117, 29);
contentPane.add(connectButton);
// Disconnect Button
disconnectButton = new JButton("Disconnect");
disconnectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Disconnect");
Client.Disconnect();
}
});
disconnectButton.setBounds(493, 7, 117, 29);
contentPane.add(disconnectButton);
// Users Label
usersLabel = new JLabel("Users");
usersLabel.setBounds(664, 12, 61, 16);
contentPane.add(usersLabel);
// Users Box
usersBox = new JTextArea();
usersBox.setEditable(false);
usersBox.setBounds(622, 40, 122, 282);
contentPane.add(usersBox);
// Chat Box
chatBox = new JTextArea();
chatBox.setEditable(false);
chatBox.setBounds(17, 40, 593, 226);
scroll = new JScrollPane(chatBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
contentPane.add(scroll);
// Input Box
inputBox = new JTextField();
inputBox.setBounds(17, 274, 506, 48);
contentPane.add(inputBox);
inputBox.setColumns(10);
inputBox.addKeyListener(this);
inputBox.setEditable(false);
// Send Button
sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Send");
Client.Send();
}
});
sendButton.setBounds(526, 274, 84, 48);
contentPane.add(sendButton);
// ipLabel
ipLabel = new JLabel("IP");
ipLabel.setBounds(215, 12, 17, 16);
contentPane.add(ipLabel);
// ipBox
ipBox = new JTextField();
ipBox.setBounds(236, 6, 117, 28);
contentPane.add(ipBox);
ipBox.setColumns(10);
// Set Pane
setContentPane(contentPane);
// send disconnect on close of window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Client.Disconnect();
}
});
menuBar = new JMenuBar();
setJMenuBar(menuBar);
file = new JMenu("File");
menuBar.add(file);
about = new JMenuItem("About");
file.add(about);
connect = new JMenuItem("Connect");
file.add(connect);
disconnect = new JMenuItem("Disconnect");
file.add(disconnect);
setDefaultUsername = new JMenuItem("Set default username.");
file.add(setDefaultUsername);
setDefaultIP = new JMenuItem("Set default IP address.");
file.add(setDefaultIP);
about.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
aboutFrame = new About();
}
});
setDefaultUsername.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
promptDefaultUser();
}
});
setDefaultIP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
promptDefaultIP();
}
});
connect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Client.Connect();
}
});
disconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Client.Disconnect();
}
});
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER)
Client.Send();
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Don't use a null layout!!!
Your scrollpane doesn't have a proper size so its not painted. Even if it does get painted. Swing was designed to be used with layout managers for too many reasons to list here.
Read the JTextArea API and follow the link to the Swing tutorial where you will find working examples of the proper way to use a text area in a scrollpane.
You need to place the JTextArea and the JScrollPane at the right places, then everything should work.
The JTextArea resides inside the JScrollPane and it is not required to call setBounds(...) on it. This is because the origin of the JTextArea inside the scrollpane should be (0,0).
The JScrollPane needs to be placed at the location where you placed the JTextArea at.
chatBox = new JTextArea();
chatBox.setEditable(false);
scroll = new JScrollPane(chatBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds(17,40,593,226);
contentPane.add(scroll);
chatBox = new JTextArea();
chatBox.setEditable(false);
chatBox.setBounds(17, 40, 593, 226);
scroll = new JScrollPane(chatBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
contentPane.add(scroll);
// Input Box
issues:
where are you setting the Bound of JSCrollPane to become visible in the panel with null layout?
You are using null layout! you should use LayoutManager which will lay out your GUI component for you. start learning them.
JScrollPane uses the component's preferred size under it's view to scroll it. Well don't rush to set the preferred size of chatBox right now. The LayoutManager should do it for you.
start learning from : A Visual Guide to Layout Managers

Categories