I have written a small test program which creates a split pane in which one of the pane's is a text area. I have added a meubar and menuitems to the pane but i donot see them in the gui that is created.
Could anyone pls point out what the wrong thing did i do over here in the below program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenuBar;
import java.util.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.IOException;
//SplitPaneDemo itself is not a visible component.
public class SplitPaneDemo extends JFrame
implements ActionListener {
private JTextArea ta;
private JMenuBar menuB;
private JMenu dbM;
private JMenuItem cnadb,bsmdb,cdmdb;
private JLabel picture;
private JSplitPane splitPane;
public SplitPaneDemo() {
ta = new JTextArea(); //textarea
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke )
{
int code = ke.getKeyCode();
int modifiers = ke.getModifiers();
if(code == KeyEvent.VK_ENTER && modifiers == KeyEvent.CTRL_MASK)
{
System.out.println("cmd in table:");
}
}
});
JScrollPane taPane = new JScrollPane(ta);
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
JScrollPane pictureScrollPane = new JScrollPane(picture);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
taPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(450);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 100);
taPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(900, 900));
menuB = new JMenuBar(); //menubar
dbM = new JMenu("DB"); //file menu
cnadb = new JMenuItem("CNA");
bsmdb = new JMenuItem("BSM");
cdmdb = new JMenuItem("CDM");
setJMenuBar(menuB);
menuB.add(dbM);
dbM.add(cnadb);
dbM.add(bsmdb);
dbM.add(cdmdb);
cnadb.addActionListener(this);
bsmdb.addActionListener(this);
cdmdb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
public void valueChanged(ListSelectionEvent e) {
}
public JSplitPane getSplitPane() {
return splitPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You add the JMenuBar in your SplitPaneDemo class, but when you actually call createAndShowGUI, you make a new JFrame and only add the SplitPane to it with the call to getSplitPane. This new frame has no knowledge of the menu bar.
If you are extending JFrame in SplitPaneDemo, why not use that to make the frame for your gui?
Related
class MemberBook extends Frame {
MenuBar mb;
Menu menu;
MenuItem miReg, miList, miExit;
MemberBook() {
super();
mb = new MenuBar();
menu = new Menu("Menu");
miReg = new MenuItem("Register");
miList = new MenuItem("List");
miExit = new MenuItem("Exit");
menu.add(miReg);
menu.add(miList);
menu.addSeparator();
menu.add(miExit);
mb.add(menu);
setMenuBar(mb);
MenuHandler handler = new MenuHandler(this);
miReg.addActionListener(handler);
miList.addActionListener(handler);
miExit.addActionListener(handler);
setSize(300, 500);
setVisible(true);
}
public static void main(String args[]) {
MemberBook win = new MemberBook();
}
class MenuHandler implements ActionListener {
MemberBook frame;
// I want to add panel to outer class but I don't know
// other way to do it so, get _frame in constructor
MenuHandler(MemberBook _frame) {
frame = _frame;
}
// show different panels for each menu
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Register")) {
RegisterPanel panel = new RegisterPanel();
frame.add(panel, "Center");
}
// else if ...
}
}
// predefined panel to show in MemberBook frame
class RegisterPanel extends Panel {
}
}
I want to make pre defined member register panel, member list panel (you can see members list and edit members) and show when choose menu but RegisterPanel doesn't show when I choose register menu. I don't know other way to add panel to frame in inner Listener class, so transferred frame to Listener constructor.
So, the basic answer is, use a CardLayout, see How to Use CardLayout for more details.
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.border.EmptyBorder;
public class MemberBook {
public static void main(String[] args) {
new MemberBook();
}
private JMenuBar mb;
private JMenu menu;
private JMenuItem miReg, miList, miExit;
public MemberBook() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
mb = new JMenuBar();
menu = new JMenu("Menu");
miReg = new JMenuItem("Register");
miList = new JMenuItem("List");
miExit = new JMenuItem("Exit");
menu.add(miReg);
menu.add(miList);
menu.addSeparator();
menu.add(miExit);
mb.add(menu);
MainPane mainPane = new MainPane();
MenuHandler handler = new MenuHandler(mainPane);
miReg.addActionListener(handler);
miList.addActionListener(handler);
miExit.addActionListener(handler);
JFrame frame = new JFrame();
frame.setJMenuBar(mb);
frame.add(mainPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface MemberBookController {
public void registerUser();
}
public class MainPane extends JPanel implements MemberBookController {
private CardLayout cardLayout;
public MainPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
add(new WelcomePane(), "welcome");
add(new RegisterPanel(), "register");
cardLayout.show(this, "welcome");
}
#Override
public void registerUser() {
cardLayout.show(this, "register");
}
}
public class MenuHandler implements ActionListener {
private MemberBookController controller;
// I want to add panel to outer class but I don't know
// other way to do it so, get _frame in constructor
MenuHandler(MemberBookController controller) {
this.controller = controller;
}
// show different panels for each menu
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Register")) {
controller.registerUser();
}
// else if ...
}
}
public class WelcomePane extends JPanel {
public WelcomePane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
add(new JLabel("Welcome"));
setBackground(Color.BLUE);
}
}
// predefined panel to show in MemberBook frame
public class RegisterPanel extends JPanel {
public RegisterPanel() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
add(new JLabel("Register"));
setBackground(Color.RED);
}
}
}
This example also demonstrates the use of a interface to provide "information hiding". The MenuHandler doesn't really need access to the frame or base pane, in fact, it shouldn't care. All it needs to do is tell interested parties that some action has occurred.
I might consider using the Action API to do this, so you can isolate the functionality a little more, see How to Use Actions for more details.
The idea is to have one "global" JFrame which I can then add/remove JPanels as needed to make a smooth flowing application. Currently, when I try changing from the first JPanel to the second, the second won't display. My code is below:
Handler (class to run the app):
package com.example.Startup;
import com.example.Global.Global_Frame;
public class Handler
{
public Handler()
{
gf = new Global_Frame();
gf.getAccNum();
gf.setVisible(true);
}
public static void main(String[] args)
{
new Handler();
}
Global_Frame gf = null;
}
public static void main(String[] args)
{
new Handler();
}
Global_Vars gv = null;
Global_Frame gf = null;
}
Global Frame:
package com.example.Global;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.example.FirstRun.AccDetails;
import com.example.FirstRun.FirstTimeRun;
public class Global_Frame extends JFrame
{
private static final long serialVersionUID = 1L;
ActionListener val = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
getUserDetails();
}
};
public Global_Frame()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // get look and feel based on OS
}
catch (ClassNotFoundException ex) // catch all errors that may occur
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (UnsupportedLookAndFeelException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() //run the class's constructor, therefore starting the UI being built
{
initComponents();
}
});
}
public void initComponents()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
revalidate(); // revalidate the elements that will be displayed
repaint(); // repainting what is displayed if going coming from a different form
pack(); // packaging everything up to use
setLocationRelativeTo(null); // setting form position central
}
public void getAccNum()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
FirstTimeRun panel1 = new FirstTimeRun(val);
add(panel1);
revalidate();
repaint();
pack();
}
public void getUserDetails()
{
getContentPane().removeAll();
resizing(750, 500);
AccDetails panel2 = new AccDetails();
add(panel2);
revalidate();
repaint();
pack();
}
private void resizing(int width, int height)
{
timer = new Timer (10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
getContentPane().removeAll();
setPreferredSize(new Dimension(sizeW, sizeH));
revalidate();
repaint();
pack();
if (!wToggle)
sizeW += 2;
if (!hToggle)
sizeH += 2;
if (toggle)
{
setLocationRelativeTo(null);
toggle = false;
}
else
toggle = true;
if (sizeW == width)
wToggle = true;
if (sizeH == height)
hToggle = true;
if (hToggle && wToggle)
timer.stop();
}
});
timer.start();
}
//variables used for window resizing
private Timer timer;
private int sizeW = 600;
private int sizeH = 400;
private boolean toggle = false;
private boolean wToggle = false;
private boolean hToggle = false;
public int accNum = 0;
}
First Panel:
package com.example.FirstRun;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class FirstTimeRun extends JPanel
{
private static final long serialVersionUID = 1L;
public FirstTimeRun()
{
}
public FirstTimeRun(ActionListener val)
{
initComponents(val);
}
private void initComponents(ActionListener val) // method to build initial view for user for installation
{
pnlStart = new JPanel[1];
btnNext = new JButton();
pnlStart[0] = new JPanel();
btnNext.setText("Next"); // adding text to button for starting
btnNext.setPreferredSize(new Dimension(80, 35)); //positioning start button
btnNext.addActionListener(val);
pnlStart[0].add(btnNext); // adding button to JFrame
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlStart[0]);
}
// objects used in UI
private JPanel[] pnlStart;
private JButton btnNext;
}
Second Panel:
package com.example.FirstRun;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AccDetails extends JPanel
{
private static final long serialVersionUID = 1L;
public AccDetails()
{
accAssets();
}
private void accAssets()
{
// instantiating elements of the GUI
pnlAccDetails = new JPanel[2];
lblWelcome = new JLabel();
lblMain = new JLabel();
for (int i = 0; i < 2; i++)
pnlAccDetails[i] = new JPanel();
lblWelcome.setText("Welcome to Example_App"); // label welcoming user
pnlAccDetails[0].setLayout(new BoxLayout(pnlAccDetails[0], BoxLayout.LINE_AXIS));
pnlAccDetails[0].add(lblWelcome); // adding label to form
lblMain.setText("<html>The following information that is collected will be used as part of the Example_App process to ensure that each user has unique Example_App paths. Please fill in all areas of the following tabs:</html>"); // main label that explains what happens, html used for formatting
pnlAccDetails[1].setLayout(new BorderLayout());
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_START);
pnlAccDetails[1].add(lblMain, BorderLayout.CENTER); //adding label to JFrame
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_END);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlAccDetails[0]);
add(pnlAccDetails[1]);
}
private JLabel lblWelcome;
private JLabel lblMain;
private JPanel[] pnlAccDetails;
}
I have tried using both a CardLayout and the "revalidate();" "repaint();" and "pack();" options and I'm stumped as to why it's not showing. Thanks in advance for any help that can be offered.
EDIT:
While cutting down my code, if the "resizing" method is removed, the objects are shown when the panels change. I would like to avoid having to remove this completely as it's a smooth transition for changing the JFrame size.
#John smith it is basic example of switch from one panel to other panel I hope this will help you to sort out your problem
Code:
package stack;
import java.awt.BorderLayout;
import java.awt.Dimension;
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;
public class RemoveAndAddPanel implements ActionListener{
JFrame frame;
JPanel firstPanel;
JPanel secondPanel;
JPanel controlPanel;
JButton nextButton;
public RemoveAndAddPanel() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.add(new JLabel("FirstPanel"));
firstPanel.setPreferredSize(new Dimension(100,100));
secondPanel = new JPanel();
secondPanel.add(new JLabel("Second panel"));
secondPanel.setPreferredSize(new Dimension(100,100));
nextButton = new JButton("Next panel");
controlPanel = new JPanel();
nextButton.addActionListener(this);
controlPanel.add(nextButton);
frame.setLayout(new BorderLayout());
frame.add(firstPanel,BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(300,100);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == nextButton) {
frame.remove(firstPanel);
frame.add(secondPanel);
nextButton.setEnabled(false);
}
frame.validate();
}
public static void main(String args[]) {
new RemoveAndAddPanel();
}
}
As mentioned in the edit, the problem lay within the resizing method. When the timer stopped, it wouldn't go anywhere, causing the UI to not load. The fix to the code is clearing the screen and adding the call to resizing to the actionlistener. Then adding a call to the next method after:
timer.stop();
Thanks for getting me to remove the mess around it and find the source of the problem #matt & #Hovercraft Full of Eels upvotes for both of you.
The main thing to consider while changing panel in a jframe is the layout, for a body(main) panel to change to any other panel the parent panel must be of type CardLayout body.setLayout(new java.awt.CardLayout());
After that you can now easily switch between panels wiht the sample code below
private void updateViewLayout(final HomeUI UI, final JPanel paneeelee){
final JPanel body = UI.getBody(); //this is the JFrame body panel and must be of type cardLayout
System.out.println("Page Loader Changing View");
new SwingWorker<Object, Object>() {
#Override
protected Object doInBackground() throws Exception {
body.removeAll();//remove all visible panel before
body.add(paneeelee);
body.revalidate();
body.repaint();
return null;
}
#Override
protected void done() {
UI.getLoader().setVisible(false);
}
}.execute();
}
I started codig Java last weekend and I've read most of the basic stuff. I'm trying to separate my frame from main method, and panels from the frame so they are all in separate class files. I have trouble calling ActionLister in "Frame1" class with a button (buttonBack) in the "TheGame" class. The button should trigger the Listener which in turn should remove theGame panel and add mainMenu panel to frame1. I know that CardLayout is better suited for swapping panels but i want to learn the limits and workarounds before i go do it the "easy" way, i feel that you learn much more that way.
Here is some of my code:
Main:
public class Main {
public static void main(String[] args){
Frame1 frame1 = new Frame1();
frame1.frame1();
}
}
Frame1:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
class Frame1 {
private JFrame frame1 = new JFrame("Name");
public void frame1() {
TheGame theGame = new TheGame();
MainMenu mainMenu = new MainMenu();
// Frame options
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLocationRelativeTo(null);
// Creating a top menu
JMenuBar menubar = new JMenuBar();
frame1.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenuItem about = new JMenuItem("About");
help.add(about);
// Creating action for the menuitem "exit".
class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
exit.addActionListener(new exitaction());
// Creating listener for the menuitem "about".
class aboutaction implements ActionListener{
public void actionPerformed (ActionEvent e){
JDialog dialogabout = new JDialog();
JOptionPane.showMessageDialog(dialogabout, "Made by: ");
}
}
about.addActionListener(new aboutaction());
// Add the panels, pack and setVisible
theGame.theGame();
mainMenu.mainMenu();
frame1.add(theGame.getGUI());
// This is the ActionListener i have trouble connecting with the buttonBack in the "theGame" class
class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
frame1.remove(theGame.getGUI());
frame1.add(MainMenu.getGUI());
}
}
frame1.pack();
frame1.setVisible(true);
}
public JFrame getGUI() {
return frame1;
}
}
MainMenu:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class MainMenu {
private JPanel mainMenu = new JPanel (new GridBagLayout());
public void mainMenu() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating Label
JLabel introduction = new JLabel("Name");
grid.gridx = 1;
grid.gridy = 3;
mainMenu.add(introduction, grid);
// Creating buttons Start Game, Highscore and Exit Game
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 5;
mainMenu.add(buttonNewGame, grid);
JButton buttonHighscore = new JButton("Highscore");
buttonHighscore.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 6;
mainMenu.add(buttonHighscore, grid);
JButton buttonExit = new JButton("Exit Game");
buttonExit.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 7;
mainMenu.add(buttonExit, grid);
}
public JComponent getGUI() {
return mainMenu;
}
}
TheGame:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class TheGame {
private JPanel theGame = new JPanel (new GridBagLayout());
public void theGame() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating a label
JLabel label1 = new JLabel("Press the BACK button to go back to Main Menu");
label1.setVisible(true);
grid.gridx = 1;
grid.gridy = 0;
theGame.add(label1,grid);
// Creating BACK button
JButton buttonBack = new JButton("BACK");
buttonBack.setVisible(true);
grid.gridx = 1;
grid.gridy = 1;
buttonBack.addActionListener(new --); // This is the button i want to connect with the ActionListener on Frame1 class
theGame.add(buttonBack, grid);
}
public JComponent getGUI() {
return theGame;
}
}
I've tried moving the ActionListener outside of methods, inside the Main, declaring it static, but haven't been able to call it anyways. I've also looked at other posts like this: Add an actionListener to a JButton from another class but have not been able to implement it in to my code.
Any help is appreciated.
The best answer -- use MVC (model-view-controller) structure (and CardLayout) for the swapping of your views. If you don't want to do that, then your listener should have a reference to the container that does the swapping, and so that the listener can notify this container that a swap should occur. The container will then call its own code to do the swapping. To do this you need to pass references around including a reference to the main GUI to wherever it is needed. This can get messy, which is why MVC, which is more work, is usually better -- fewer connections/complexity in the long term.
Side note -- don't pass a JDialog into a JOptionPane as a JOptionPane is a specialized JDialog, and you shouldn't have a top level window displaying a top level window. Instead pass in a JPanel.
For example:
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PassRef {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
MyMain mainPanel = new MyMain();
JFrame frame = new JFrame("Pass Reference");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class MyMain extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
private CardLayout cardLayout = new CardLayout();
private MenuView menuView = new MenuView(this);
private ActionView1 actionView1 = new ActionView1(this);
public MyMain() {
setLayout(cardLayout);
add(menuView, MenuView.NAME);
add(actionView1, ActionView1.NAME);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public void showCard(String key) {
cardLayout.show(this, key);
// or swap by hand if you don't want to use CardLayout
// but remember to revalidate and repaint whenever doing it by hand
}
}
class MenuView extends JPanel {
public static final String NAME = "Menu View";
public MenuView(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder("Menu"));
add(new JButton(new GoToAction("Action 1", ActionView1.NAME, myMain)));
}
}
class ActionView1 extends JPanel {
public static final String NAME = "Action View 1";
public ActionView1(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder(NAME));
add(new JButton(new GoToAction("Main Menu", MenuView.NAME, myMain)));
}
}
class GoToAction extends AbstractAction {
private String key;
private MyMain myMain;
public GoToAction(String name, String key, MyMain myMain) {
super(name);
this.key = key;
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
myMain.showCard(key);
}
}
So, I am creating a new Canvas (JPanel) class: Canvas canvas = new Canvas(); and then I am calling a method on that class: canvas.addTextBox();
Now, from within this Canvas class, I want to add a new jTextArea to the Canvas. I tried using the code below but it isn't showing up. Not sure what I am doing wrong. Thanks!
class Canvas extends JPanel {
public Canvas() {
this.setOpaque(true);
//this.setBackground(Color.WHITE);
}
public void addTextBox() {
final JTextArea commentTextArea = new JTextArea(10, 10);
commentTextArea.setLineWrap(true);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
}
}
Full Code
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Canvas canvas = new Canvas();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(canvas);
JMenuBar menubar = new JMenuBar();
JMenuItem newTextBox = new JMenuItem("New Text Box");
newTextBox.setMnemonic(KeyEvent.VK_E);
newTextBox.setToolTipText("Exit application");
newTextBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
canvas.addTextBox();
}
});
menubar.add(newTextBox);
setJMenuBar(menubar);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Canvas extends JPanel {
public Canvas() {
this.setOpaque(true);
//this.setBackground(Color.WHITE);
}
public void addTextBox() {
final JTextArea commentTextArea = new JTextArea(10, 10);
commentTextArea.setLineWrap(true);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
}
}
The addTextBox method only creates a JTextArea. It never adds it to the JPanel
You will need to add the following line to addTextBox method:
add( commentTextArea );
In case the JFrame which contains your components is already visible on screen when the addTextBox method is called, you need to invalidate the container as well. Simply add
revalidate();
repaint();
I am trying to create a way to update a JComboBox so that when the user enters something into the text field, some code will process the entry and update the JComboBox accordingly.The one issue that I am having is I can update the JComboBox, but the first time it is opened, the box has not refresh the length of the options in it and as seen in the code below it displays extra white space. I do not know if there is a better different way to do this, but this is what I came up with.
Thanks for the help,
Dan
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Catch{
public static JComboBox dropDown;
public static String dropDownOptions[] = {
"Choose",
"1",
"2",
"3"};
public static void main(String[] args) {
dropDown = new JComboBox(dropDownOptions);
final JTextField Update = new JTextField("Update", 10);
final JFrame frame = new JFrame("Subnet Calculator");
final JPanel panel = new JPanel();
frame.setSize(315,430);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Update.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
}
public void focusLost(FocusEvent arg0) {
dropDown.removeAllItems();
dropDown.insertItemAt("0", 0);
dropDown.insertItemAt("1", 1);
dropDown.setSelectedIndex(0);
}
});
panel.add(Update);
panel.add(dropDown);
frame.getContentPane().add(panel);
frame.setVisible(true);
Update.requestFocus();
Update.selectAll();
}
}
1) JTextField listening for ENTER key from ActionListener
2) remove FocusListener
3) example about add new Item as last Item from JTextField to the JList, only you have to modify for JComboBox and add method insertItemAt() correctly
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListBottom2 {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JTextField textField = new JTextField("Use Enter to Add");
private JPanel panel = new JPanel(new BorderLayout());
public ListBottom2() {
model.addElement("First");
list.setVisibleRowCount(5);
panel.setBackground(list.getBackground());
panel.add(list, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(200, 100));
frame.add(scrollPane);
frame.add(textField, BorderLayout.NORTH);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField textField = (JTextField) e.getSource();
DefaultListModel model = (DefaultListModel) list.getModel();
model.addElement(textField.getText());
int size = model.getSize() - 1;
list.scrollRectToVisible(list.getCellBounds(size, size));
textField.setText("");
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ListBottom2 frame = new ListBottom2();
}
});
}
}