java desktop application - java

i am creating a desktop application in netbeans and i want that in my menu bar if i select a new menu item than o nly the below panel is change not full frame.so it will look like that i m working on a single frame.can anyone help me out

You can use Card Layout Managers to achieve such functionality.
Here is complete example:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class JMenuExample extends JFrame implements ActionListener {
JMenu menu;
JPanel panelMain;
JPanel panelRed;
JPanel panelBlue;
CardLayout layout;
public void createUI() {
createMenu();
createPanels();
}
private void createPanels() {
panelMain = new JPanel();
layout = new CardLayout();
panelMain.setLayout(layout);
panelRed = new JPanel();
panelRed.setBackground(Color.RED);
panelMain.add(panelRed, "Red");
panelBlue = new JPanel();
panelBlue.setBackground(Color.BLUE);
panelMain.add(panelBlue, "Blue");
add(panelMain);
}
private void createMenu() {
menu = new JMenu("Change To");
JMenuItem miRed = new JMenuItem("Red");
miRed.addActionListener(this);
menu.add(miRed);
JMenuItem miBlue = new JMenuItem("Blue");
miBlue.addActionListener(this);
menu.add(miBlue);
JMenuBar bar = new JMenuBar();
bar.add(menu);
setJMenuBar(bar);
}
public static void main(String[] args) {
JMenuExample frame = new JMenuExample();
frame.createUI();
frame.setSize(150, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JMenuItem) {
JMenuItem mi = (JMenuItem) e.getSource();
layout.show(panelMain, mi.getText());
}
}
}
Hope this helps

Related

add panel to frame in inner listener class?

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.

Calling method from one class in other

I know that this kind of issue has been discussed here many times, but I'm confused. I'm totally beginner in Java and I honestly don't know what to do and I admit that I don't have that much time to read whole documentation provided by Oracle. Here's my problem:
I'm trying to program a GUI for my program that will be show interference of acoustic waves. Mathematical functionality doesn't matter in here. I've got two classes called Window and Sliders. Window is intended to be a 'main GUI class' and Sliders is supposed to inherit (?) from it.
This comes from another issue that I need to implement ActionListener in class Window and ChangeListener in Sliders class. I heard that one class can't implement several classes that's why I made two.
Now, I wrote a little bit chaotic those two classes, but I don't know how to combine them. It's really silly, but after C++ I'm pretty confused how to tell the program that it is supposed to show in one frame either buttons defined in Window class and sliders defined in Sliders class. Currently it shows only buttons I want to make it showing sliders too.
I'm very sorry for chaotic pseudo code, please help. Please, try to explain as simply as you can/possible. Please feel free to ignore overrided methods, they're not finished yet.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Window extends JFrame implements ActionListener
{
private JButton showChord, playSound, getSample, getPlot;
private JLabel chordInfo;
private JPanel basicFunctions;
public Window()
{
init();
}
private void init()
{
setVisible(true);
setSize(new Dimension(1000,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
basicFunctions = new JPanel();
FlowLayout basicLayout = new FlowLayout();
basicFunctions.setLayout(basicLayout);
showChord = new JButton("Akord");
playSound = new JButton("Odtwórz");
getSample = new JButton("Pobierz dźwięk");
getPlot = new JButton("Pobierz wykres");
showChord.addActionListener(this);
playSound.addActionListener(this);
getSample.addActionListener(this);
getPlot.addActionListener(this);
basicFunctions.add(showChord);
basicFunctions.add(playSound);
basicFunctions.add(getSample);
basicFunctions.add(getPlot);
add(basicFunctions);
Sliders param = new Sliders();
}
public static void main(String[] args)
{
Window frame = new Window();
}
//Action Listener
#Override
public void actionPerformed(ActionEvent a)
{
Object event = a.getSource();
if(event == showChord)
{
}
else if(event == playSound)
{
}
else if(event == getSample)
{
}
else if(event == getPlot)
{
}
}
}
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.*;
import javax.swing.event.ChangeListener;
public class Sliders extends Window implements ChangeListener
{
private JPanel sliders, sliderSub;
private JTextField accAmplitude, accFrequency, accPhase;
private JSlider amplitude, frequency, phase;
private double amplitudeValue, frequencyValue, phaseValue;
public Sliders()
{
sliders = new JPanel();
sliders.setLayout(new FlowLayout());
amplitude = new JSlider(0,100,0);
amplitude.setMajorTickSpacing(10);
amplitude.setMinorTickSpacing(5);
amplitude.setPaintTicks(true);
amplitude.setPaintLabels(true);
frequency = new JSlider(0,10,0);
frequency.setMajorTickSpacing(1);
frequency.setMinorTickSpacing(1/10);
frequency.setPaintTicks(true);
frequency.setPaintLabels(true);
phase = new JSlider(0,1,0);
phase.setMinorTickSpacing(2/10);
phase.setPaintTicks(true);
phase.setPaintLabels(true);
accAmplitude = new JTextField();
accFrequency = new JTextField();
accPhase = new JTextField();
sliders.add(amplitude, BorderLayout.NORTH);
sliders.add(frequency, BorderLayout.CENTER);
sliders.add(phase, BorderLayout.SOUTH);
add(sliders);
}
#Override
public void stateChanged(ChangeEvent arg0)
{
}
}
I've done this so far, but those text fields just stopped showing sliders values and I don't know why. They are defined in the Parameters class and Window class. Can someone help? Additionally in the future I'd like to make those text fields editable so that you can set slider value by typing it in the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.*;
public class Window extends JPanel
{
private JMenuBar mainMenu = new JMenuBar();
private Plot plot = new Plot();
private Parameters param = new Parameters();
private JComboBox chooseChord = new JComboBox();
private JButton playSound = new JButton("Odtwórz");
private JButton getSample = new JButton("Pobierz dźwięk");
private JButton getPlot = new JButton("Pobierz wykres");
private JPanel mainPanel = new JPanel();
private JPanel subPanel = new JPanel();
private JPanel buttonsPanel = new JPanel();
private JPanel slidersPanel = new JPanel();
private JLabel chord = new JLabel("Akord:");
private JTextField aValue = new JTextField();
private JTextField fValue = new JTextField();
private JTextField pValue = new JTextField();
public Window()
{
mainPanel.setLayout(new FlowLayout());
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
slidersPanel.setLayout(new BorderLayout());
subPanel.setLayout(new BorderLayout());
chooseChord.addItem("A");
chooseChord.addItem("A#");
chooseChord.addItem("Ab");
chooseChord.addItem("B");
chooseChord.addItem("Bb");
chooseChord.addItem("C");
chooseChord.addItem("C#");
chooseChord.addItem("Cb");
chooseChord.addItem("D");
chooseChord.addItem("D#");
chooseChord.addItem("E");
chooseChord.addItem("F");
chooseChord.addItem("F#");
buttonsPanel.add(chord);
buttonsPanel.add(chooseChord);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(playSound);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(getSample);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(getPlot);
buttonsPanel.setBorder(BorderFactory.createTitledBorder("Menu"));
slidersPanel.add(param);
JMenu langMenu = new JMenu("Język");
mainMenu.add(langMenu);
subPanel.add(buttonsPanel, BorderLayout.NORTH);
subPanel.add(slidersPanel, BorderLayout.SOUTH);
mainPanel.add(subPanel);
mainPanel.add(plot);
add(mainPanel);
param.addAmplitudeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent a)
{
double ampValue = param.getAmplitudeValue();
aValue.setText(String.valueOf(ampValue));
}
}
);
param.addFrequencyListener(new ChangeListener()
{
public void stateChanged(ChangeEvent f)
{
double frValue = param.getFrequencyValue();
fValue.setText(String.valueOf(frValue));
}
}
);
param.addPhaseListener(new ChangeListener()
{
public void stateChanged(ChangeEvent p)
{
double phValue = param.getPhaseValue();
pValue.setText(String.valueOf(phValue));
}
}
);
}
public JMenuBar getmainMenu()
{
return mainMenu;
}
private static void GUI()
{
Window mainPanel = new Window();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getmainMenu());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
GUI();
}
}
);
}
}
class Parameters extends JPanel
{
private JPanel pane = new JPanel();
private JPanel ampPanel = new JPanel();
private JPanel frPanel = new JPanel();
private JPanel phPanel = new JPanel();
private JSlider amplitude = new JSlider(0,100,0);
private JSlider frequency = new JSlider(0,10000,0);
private JSlider phase = new JSlider(0,180,0);
private JLabel pLabel = new JLabel("Faza");
private JLabel aLabel = new JLabel("Amplituda (dB)");
private JLabel fLabel = new JLabel("Częstotliwość (Hz)");
private JTextField preciseAmplitude = new JTextField(3);
private JTextField preciseFrequency = new JTextField(4);
private JTextField precisePhase = new JTextField(3);
public Parameters()
{
preciseAmplitude.setEditable(true);
preciseFrequency.setEditable(true);
precisePhase.setEditable(true);
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
ampPanel.setLayout(new FlowLayout());
frPanel.setLayout(new FlowLayout());
phPanel.setLayout(new FlowLayout());
amplitude.setMajorTickSpacing(10);
amplitude.setMinorTickSpacing(5);
amplitude.setPaintTicks(true);
amplitude.setPaintLabels(true);
frequency.setMajorTickSpacing(2000);
frequency.setMinorTickSpacing(100);
frequency.setPaintTicks(true);
frequency.setPaintLabels(true);
phase.setMajorTickSpacing(2/10);
phase.setPaintTicks(true);
phase.setPaintLabels(true);
setBorder(BorderFactory.createTitledBorder("Parametry fali"));
ampPanel.add(aLabel);
ampPanel.add(preciseAmplitude);
pane.add(ampPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(amplitude);
pane.add(Box.createRigidArea(new Dimension(0,10)));
frPanel.add(fLabel);
frPanel.add(preciseFrequency);
pane.add(frPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(frequency);
pane.add(Box.createRigidArea(new Dimension(0,10)));
phPanel.add(pLabel);
phPanel.add(precisePhase);
pane.add(phPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(phase);
pane.add(Box.createRigidArea(new Dimension(0,10)));
add(pane);
}
public int getAmplitudeValue()
{
return amplitude.getValue();
}
public int getFrequencyValue()
{
return frequency.getValue();
}
public int getPhaseValue()
{
return phase.getValue();
}
public void addAmplitudeListener(ChangeListener ampListener)
{
amplitude.addChangeListener(ampListener);
}
public void addFrequencyListener(ChangeListener frListener)
{
frequency.addChangeListener(frListener);
}
public void addPhaseListener(ChangeListener phListener)
{
phase.addChangeListener(phListener);
}
}
class Plot extends JPanel
{
private JPanel componentWave = new JPanel();
private JPanel netWave = new JPanel();
private JLabel componentLabel = new JLabel("Fale składowe");
private JLabel netLabel = new JLabel("Fala wypadkowa");
private JLabel wave = new JLabel("Wybierz falę składową");
private JPanel labels = new JPanel();
private JComboBox chooseWave = new JComboBox();
public Plot()
{
labels.setLayout(new BoxLayout(labels, BoxLayout.PAGE_AXIS));
componentWave.setBackground(new Color(255,255,255));
netWave.setBackground(new Color(255,255,255));
componentWave.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
netWave.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
componentWave.setPreferredSize(new Dimension(400,200));
netWave.setPreferredSize(new Dimension(400,200));
labels.add(wave);
labels.add(Box.createRigidArea(new Dimension(0,10)));
labels.add(chooseWave);
labels.add(componentLabel);
labels.add(componentWave);
labels.add(Box.createRigidArea(new Dimension(0,20)));
labels.add(netLabel);
labels.add(netWave);
add(labels);
}
}
Window is intended to be a 'main GUI class' and Sliders is supposed to inherit (?) from it.
Nope: this is a misuse of inheritance and will only lead to problems since the Windows instance that Sliders inherently is, is completely distinct from the displayed Windows instance. What you need to do is to pass references.
For example, the following code uses outside classes for the JButton and JMenuItem Actions (Actions are like ActionListeners on steroids), and uses a class that holds a JSlider that allows itside classes to attach listeners to the slider.
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Foo extends JPanel {
private static final long serialVersionUID = 1L;
private Action helloAction = new HelloAction("Hello", KeyEvent.VK_H);
private Action exitAction = new ExitAction("Exit", KeyEvent.VK_X);
private JMenuBar menuBar = new JMenuBar();
private JTextField sliderValueField = new JTextField(10);
private Bar bar = new Bar();
public Foo() {
sliderValueField.setEditable(false);
sliderValueField.setFocusable(false);
add(new JButton(helloAction));
add(new JButton(exitAction));
add(new JLabel("Slider Value: "));
add(sliderValueField);
add(bar);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(new JMenuItem(exitAction));
fileMenu.add(new JMenuItem(helloAction));
menuBar.add(fileMenu);
bar.addSliderListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
int sliderValue = bar.getSliderValue();
sliderValueField.setText(String.valueOf(sliderValue));
}
});
}
public JMenuBar getJMenuBar() {
return menuBar;
}
private static void createAndShowGui() {
Foo mainPanel = new Foo();
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getJMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class HelloAction extends AbstractAction {
public HelloAction(String name, int mnemonic) {
super(name); // sets name property and gives button its title
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello!");
}
}
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
if (win == null) {
// if no window, then a JMenuItem held in a JPopupMenu
JPopupMenu popup = (JPopupMenu) component.getParent();
component = popup.getInvoker();
win = SwingUtilities.getWindowAncestor(component);
}
win.dispose();
}
}
class Bar extends JPanel {
private JSlider slider = new JSlider(0, 100, 50);
public Bar() {
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setSnapToTicks(true);
setBorder(BorderFactory.createTitledBorder("Slider Panel"));
add(slider);
}
public int getSliderValue() {
return slider.getValue();
}
// one way to let outside classes listen for changes
public void addSliderListener(ChangeListener listener) {
slider.addChangeListener(listener);
}
}
You ask about decimal labels, and yes this can be done but requires use of a label table. For example,
JSlider slider = new JSlider(0, 100, 50);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(2);
Dictionary<Integer, JLabel> labels = new Hashtable<>();
for (int i = 0; i <= 100; i += 20) {
labels.put(i, new JLabel(String.format("%.1f", i / 200.0)));
}
slider.setLabelTable(labels);
Which displays as:
You would also have to translate the value back from int to its corresponding floating point number.

Menubar not added in a java split pane

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?

java swing panel problems

I am having problems adding a panel to my main JFrame and hiding it right away, only making it visilble when a button it pressed. here is my code. Looking for any insight as to what the problem is. Also the label I try to add to the panel doesnt show up either.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cis2430_a4;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Tristan
*/
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent ae)
{
/*String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}*/
add(addPanel);
//addPanel.setVisible(true);
}
}
I have no issue with your example.
You may want to...
1- Make sure you've launched your UI in the context of the Event Dispatching Thread
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
MainWindow frame = new MainWindow();
frame.setVisible(true);
}
});
}
2- Try calling repaint after addPanel.setVisible(true)
3- Try calling invalidate after addPanel.setVisible(true) but before repaint if that doesn't work.
Much better solution is to use Card Layout for this kind of work
UPDATED
After spending some time reading through the code, what I think you seem to be concerned about is the fact that you're "intro" label isn't showing up...
This easily explained. Only one component can exists at any given position within a BorderLayout, so when you add you addPanel, even though it's invisible, it will clobber the intro2 label (effectively removing it from the container).
Below is an example using CardLayout
public class CardWindow extends JFrame implements ActionListener {
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
private JPanel cardPane;
private CardLayout cardLayout;
private final JLabel intro2;
public CardWindow() {
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
cardPane = new JPanel((cardLayout = new CardLayout()));
add(cardPane, BorderLayout.CENTER);
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
cardPane.add(intro2, "intro");
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600, 400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
addPanel.setVisible(false);
cardPane.add(addPanel, "Add");
cardLayout.show(cardPane, "intro");
}
#Override
public void actionPerformed(ActionEvent ae) {
String menuChoice = ae.getActionCommand();
System.out.println(menuChoice);
if (menuChoice.equals("Add")) {
cardLayout.show(cardPane, "Add");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
CardWindow frame = new CardWindow();
frame.setVisible(true);
}
});
}
}
Labels are showing up because you have added a panel after adding the labels on the frame so basically the panels are overlapping the labels.
Also to show different panels you can use
panel.setVisible(true); //For the panel you want to show and false for others
or you can use CardLayout which makes panels as cards and shows one of them at a time.
Just edited the code a little but it seems to work -
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
}
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent ae)
{
String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}
add(addPanel);
//addPanel.setVisible(true);
}
}

Invoking a MenuItem with one keystroke

We know that we can invoke a menu item with the help of setaccelerator() method where a combination of two keystrokes are required. what if i want to invoke a menu item by just one keystroke...here is where i am having a bit problem
menuitem=new JMenuItem("Delete");
menuitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE);
menu.add(menuitem);
Please help....!!
Check How to Use Menus for details. Below is an example that utilizes Action, that defines accelerator. You can also set accelerator on the menu item, ie: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MenuDemo {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem item = new JMenuItem(new TestAction(frame));
menu.add(item);
frame.setJMenuBar(menuBar);
frame.setSize(new Dimension(300, 300));
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
static class TestAction extends AbstractAction {
private Component parent;
public TestAction(Component parent) {
super("Test");
this.parent = parent;
putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(parent, "Test");
}
}
}

Categories

Resources