I want to develop a very basic application, well here is the code, I have 4 classes one is the main class, the second one is JMenuBar, the third one is Panel and the fourth one is for Action Listener. at the moment my problem is here how to add instance of Action Listener for class of JMenuBar, till i could do some action.
public class My_Action implements ActionListener {
public My_Action() {
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
}
public class My_Menu extends JMenuBar {
private My_Action my_action = new My_Action();
JMenu file;
JMenu Edit;
JMenu help;
public My_Menu() {
file = new JMenu("File");
Edit = new JMenu("Edit");
help = new JMenu("help");
JMenuItem item1 = new JMenuItem("file");
JMenuItem item2 = new JMenuItem("New");
JMenuItem item3 = new JMenuItem("Setting");
JMenuItem item4 = new JMenuItem("Color");
JMenuItem item5 = new JMenuItem("Print");
JMenuItem item6 = new JMenuItem("Exit");
file.add(item1);
file.add(item2);
file.add(item3);
file.add(item4);
file.add(item5);
file.add(item6);
file.addSeparator();
this.add(file);
this.add(Edit);
this.add(help);
item1.addActionListener(my_action);
}
public void actionPerformed(ActionEvent actionEvent){
System.exit(0);
}
}
This is my test program for you.
Check the console output when executing the menu program.
package just.test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class My_Menu extends JMenuBar implements ActionListener {
private static final long serialVersionUID = 1L;
private My_Action my_action = new My_Action();
JMenu file;
JMenu Edit;
JMenu help;
public My_Menu() {
file = new JMenu("File");
Edit = new JMenu("Edit");
help = new JMenu("help");
this.add(file);
this.add(Edit);
this.add(help);
JMenuItem item1 = new JMenuItem("file");
item1.setActionCommand("file");
JMenuItem item2 = new JMenuItem("New");
item2.setActionCommand("New");
JMenuItem item3 = new JMenuItem("Setting");
item3.setActionCommand("Setting");
JMenuItem item4 = new JMenuItem("Color");
item4.setActionCommand("Color");
JMenuItem item5 = new JMenuItem("Print");
item5.setActionCommand("Print");
JMenuItem item6 = new JMenuItem("Exit");
item6.setActionCommand("Exit");
JMenuItem item7 = new JMenuItem("edit1");
item7.setActionCommand("edit1");
JMenuItem item8 = new JMenuItem("edit2");
item8.setActionCommand("edit2");
JMenuItem item9 = new JMenuItem("about..");
item9.setActionCommand("about");
file.add(item1);
file.add(item2);
file.addSeparator();
file.add(item3);
file.add(item4);
file.add(item5);
file.add(item6);
Edit.add(item7);
Edit.add(item8);
help.add(item9);
item1.addActionListener(my_action);
item2.addActionListener(my_action);
item3.addActionListener(my_action);
item4.addActionListener(my_action);
item5.addActionListener(my_action);
item7.addActionListener(this);
item8.addActionListener(this);
item9.addActionListener(this);
file.addActionListener(this);
Edit.addActionListener(this);
help.addActionListener(my_action);
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
System.out.println("----1----\n" + command);
//System.exit(0);
}
class My_Action implements ActionListener {
public My_Action() {
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
System.out.println("----2----\n" + command);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
f.add(new My_Menu(), BorderLayout.NORTH);
f.add(jp, BorderLayout.CENTER);
jp.setSize(500,400);
f.setSize(800, 600);
f.setVisible(true);
//f.pack();
}
});
}
}
You can just add a addActionListener to the component in which you have to send a message.
item1.addActionListener(my_action);
or
item7.addActionListener(this);
Don't forget to implement a ActionListener on your My_Menu class.
What you have is right.
It should call action performed when you click on file menu item. Just put a print ln in that method to see it being called.
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.
I am completely new to JAVA, I am trying to make a simple application and there is no way I can get my JOptionPane to show correctly and I guess I am missing something:
here's the code:
import java.awt.Color;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Frame extends JFrame
{
private static final long serialVersionUID = 1L;
final static int WIDTH = 400;
final static int HEIGHT = 400;
public Frame()
{
super("Convert to Dxf alpha ver. - survey apps 2014");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocation(100, 100);
setBackground(Color.WHITE);
setVisible(true);
WelcomePanel welcomePanel = new WelcomePanel(this);
add(welcomePanel);
}
public void createMenuPanel()
{
MenuPanel menu = new MenuPanel();
setJMenuBar(menu.createMenu(this));
}
}
class MenuPanel extends JPanel implements ActionListener
{
private JMenuItem open,save,close;
private JMenu file,about;
private Frame frame;
private static final long serialVersionUID = 1L;
public JMenuBar createMenu(Frame frame)
{
this.frame = frame;
JMenuBar menuBar = new JMenuBar();
file = new JMenu("File");
about = new JMenu("About");
menuBar.add(file);
menuBar.add(about);
open = new JMenuItem("Open");
save = new JMenuItem("Save");
close = new JMenuItem("Close");
file.add(open);
file.add(save);
file.addSeparator();
file.add(close);
open.addActionListener(this);
save.addActionListener(this);
close.addActionListener(this);
about.addActionListener(this);
return menuBar;
}
public MenuPanel()
{
setVisible(true);
setOpaque(true);
setBackground(Color.WHITE);
setSize(Window.WIDTH,Window.HEIGHT);
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == open)
{
frame.dispose();
}
if(source == save)
{
}
if(source == close)
{
}
if(source == about)
{
JOptionPane.showMessageDialog(frame, "EasyDxfCreator - alpha version");
}
}
}
(I skipped the WelcomeFrame because it's just like a welcome screen that disappears after a mouse click)
JMenu does not operate in that way. TO get JMenu Events you need to implement MenuListener instead of ActionListener. ActionListener is good for JMenuItem.
Hope this helps.
public class BasicGuiOnlyText extends JPanel{
static String outputHtml="<html>";*>Creating The String*
private JFrame f = new JFrame("Static Web Page Builder"); *>Creating the Frame*
private JMenuBar mb = new JMenuBar(); *>Creating Menu*
private JMenu mnuFile = new JMenu("File");
private JMenuItem mnuItemNew=new JMenuItem("New HTML");
private JMenuItem mnuItemSave=new JMenuItem("Save");
private JMenuItem mnuItemQuit = new JMenuItem("Quit");
private JMenu mnuCreate = new JMenu("Create");
private JMenuItem mnuItemFinish=new JMenuItem("Finish");
private JMenu mnuHelp = new JMenu("Help");
private JMenuItem mnuItemAbout = new JMenuItem("About");
public BasicGuiOnlyText(){
f.setJMenuBar(mb);
mnuFile.add(mnuItemNew);>Adding Menu Items
mnuItemNew.addActionListener(new TextFieldSet());*>Adding MenuItemListeners*
mnuFile.add(mnuItemSave);
mnuFile.add(mnuItemQuit);
mnuItemQuit.addActionListener(new ListenMenuQuit());
mnuHelp.add(mnuItemAbout);
ButtonHandler phandler = new ButtonHandler();
mnuItemAbout.addActionListener(phandler);
mnuCreate.add(mnuItemFinish);
ButtonHandler1 fhandler = new ButtonHandler1();
mnuItemFinish.addActionListener(fhandler);
mb.add(mnuFile);
mb.add(mnuCreate);
mb.add(mnuHelp);
f.getContentPane().setLayout(new BorderLayout());
f.addWindowListener(new ListenCloseWdw());
}
>public class TextFieldSet implements ActionListener{
>JTextField tf=new JTextField(20);
>JPanel tfPanel = new JPanel(new GridLayout(1,1));
>public void actionPerformed(ActionEvent e){
>JTextArea text1 = new JTextArea("Write Your Text", 15, 40);
>JPanel textAreaPanel = new JPanel(new BorderLayout());
>textAreaPanel.add(text1, BorderLayout.CENTER);
>tfPanel.setText("Write your text here:");
>tfPanel.add(tf);
>}
>}
Here i want to add the text field only when this new Html button is clicked. I tried with this code. But this is not working. How it can be done?
class ButtonHandler1 implements ActionListener{ >For the Final HTML tag
public void actionPerformed(ActionEvent e){
outputHtml="</html>";
//Here i need help. i have to add </html> tag when the finish button is clicked. But this code is not working. What should i do?***
}
}
public class ListenMenuQuit implements ActionListener{ *>For the Exit*
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
class ButtonHandler implements ActionListener{ *>For displaying the Help*
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "It supports GUI environment to enter your choices.", "HELP", JOptionPane. INFORMATION_MESSAGE);
}
}
public class ListenCloseWdw extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
public void launchFrame(){ *>Launches the Frame*
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
f.setVisible(true);
f.setLocationRelativeTo(null);
}
public static void main(String args[]){ *>Main Method*
BasicGuiOnlyText gui = new BasicGuiOnlyText();
gui.launchFrame();
try {
OutputStream htmlfile= new FileOutputStream(new File("test.html"));*>For >the creation of HTML file*
PrintStream printhtml = new PrintStream(htmlfile);
printhtml.println(outputHtml);
printhtml.close();
htmlfile.close();
}
catch (Exception e) {}
}
}
I hope I did understood your question correctly. See below for an example which adds the text "Hello world!" to a JTextField when the JButton is pressed.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AppendTextDemo {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame testFrame = new JFrame( "AppendTextDemo" );
JPanel content = new JPanel( new BorderLayout( ) );
JTextField textField = new JTextField( 20 );
content.add( textField, BorderLayout.CENTER );
JButton appendButton = new JButton( "Append text" );
content.add( appendButton, BorderLayout.SOUTH );
appendButton.addActionListener( new AppendTextActionListener( "Hello world!", textField ) );
testFrame.setContentPane( content );
testFrame.pack();
testFrame.setVisible( true );
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} );
}
private static class AppendTextActionListener implements ActionListener{
private final String textToAppend;
private final JTextComponent textComponent;
private AppendTextActionListener( String textToAppend, JTextComponent textComponent ) {
this.textToAppend = textToAppend;
this.textComponent = textComponent;
}
#Override
public void actionPerformed( ActionEvent e ) {
Document document = textComponent.getDocument();
try {
document.insertString( document.getLength(), textToAppend, null );
} catch ( BadLocationException e1 ) {
e1.printStackTrace();//do something useful with the exception
}
}
}
}
If this was not what you meant, please clarify your question
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