I'm have trouble change JRadioButton and do not want to select all at the same time...

80.2K

Verified Solution

Question

Programming

I'm have trouble change JRadioButton and do not want to selectall at the same time just one at a time. if one of them isunselected, then set the font as plain. Set font size as 20.

run the program and change the font and you see what I'm talkingabout

also this there anyway to shorten my code

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.*;
import java.net.URL;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
//MyMenuFrame will use Jframe with actionlistener
public class MyMenuFrame extends JFrame implementsActionListener{

//creating the main menu items
JMenu menuEdit = new JMenu(\"Edit\");
JMenu menuPrint = new JMenu(\"Print\");
JMenu mnFile = new JMenu(\"File\");
JMenu menuHelp = new JMenu(\"Help\");


//creating the submenu items here because we are gonna use theseacross the code
JRadioButton subMenuItem1 = new JRadioButton(\"Times NewRoman\");
JRadioButton subMenuItem2 = new JRadioButton(\"Arial\");
JRadioButton subMenuItem3 = new JRadioButton(\"Serif\");
JCheckBox subMenuItem4 = new JCheckBox(\"Bold\");
JCheckBox subMenuItem5 = new JCheckBox(\"Italic\");

//provide scrollable view of a component
JScrollPane scrollPane;

//creating notePadArea for notepad to input the text
JTextArea notePadArea;

public MyMenuFrame() {

//setting the border layout for JFrame
this.setLayout(new BorderLayout());

// create menu bar named menuBar

JMenuBar menuBar = new JMenuBar();

this.setJMenuBar(menuBar);//adding the menubar to JFrame

// create File menu
mnFile.setMnemonic(KeyEvent.VK_F);//Alt+F

menuBar.add(mnFile);//adding the menufile

// create Open menu item

JMenuItem mntmOpen = new JMenuItem(\"Open\");//creating the Openmenu

mntmOpen.setMnemonic(KeyEvent.VK_O);//Alt+O command

mntmOpen.setActionCommand(\"open\");//when the command equals to'open' then the corresponding action will be performed

mntmOpen.setAccelerator(KeyStroke.getKeyStroke('O',KeyEvent.CTRL_DOWN_MASK));//respond when user clicks Ctrl+O

mntmOpen.addActionListener(this);//adding actionLister to theMenu Option Open


// create Save menu item

JMenuItem mntmSave = new JMenuItem(\"Save\");//creating the Savemenu

mntmSave.setMnemonic(KeyEvent.VK_S);//Alt+S command

mntmSave.setActionCommand(\"save\");//when the command equals to'save' then the corresponding action will be performed

mntmSave.setAccelerator(KeyStroke.getKeyStroke('S',KeyEvent.CTRL_DOWN_MASK));//respond when user clicks Ctrl+S

mntmSave.addActionListener(this);//adding actionLister to theMenu Option Save

// create Exit menu item

JMenuItem mntmExit = new JMenuItem(\"Exit\");//creating the Exitmenu

mntmExit.setMnemonic(KeyEvent.VK_X);//Alt+X command

mntmExit.setActionCommand(\"exit\");//when the command equals to'exit' then the corresponding action will be performed

mntmExit.setAccelerator(KeyStroke.getKeyStroke('X',KeyEvent.CTRL_DOWN_MASK));//respond when user clicks Ctrl+X

mntmExit.addActionListener(this);//adding actionLister to theMenu Option Exit

// add open, save and exit menu to menu-bar

mnFile.add(mntmOpen);

mnFile.addSeparator();//adding separator between open andsave

mnFile.add(mntmSave);

mnFile.addSeparator();//adding separator between save andexit

mnFile.add(mntmExit);

// create Edit menu

menuEdit.setMnemonic(KeyEvent.VK_E);//creating shortcut menuwhen user press Alt+E

menuBar.add(menuEdit);//adding the Edit to the menubar

JMenu submenu1 = new JMenu(\"Color\");//creating the new menuwhich comes under Edit
submenu1.setMnemonic(KeyEvent.VK_C);//creating shortcut menu whenuser press Alt+C
JMenuItem menuItem0 = new JMenuItem(\"Change Color\");//creatingsubmenu item called change color
menuItem0.setAccelerator(KeyStroke.getKeyStroke('C',KeyEvent.CTRL_DOWN_MASK));//it responds when user clickCtrl+C
menuItem0.setActionCommand(\"color\");//setting the command used tocall the correcponding action when user click this
menuItem0.addActionListener(this);//adding actionlistener
submenu1.add(menuItem0);//adding this menu item to submenu
menuEdit.add(submenu1);//adding this submenu to editmenu
menuEdit.addSeparator();//creating separator between Color andFont

JMenu submenu = new JMenu(\"Font\");//creating the new menu whichcomes under Edit
submenu.setMnemonic(KeyEvent.VK_F);//creating shortcut menu whenuser press Alt+F
subMenuItem1.setMnemonic(KeyEvent.VK_T);//creating shortcut menuwhen user press Alt+T for Times New Roman
subMenuItem1.setActionCommand(\"times_new_roman\");//setting thecommand used to call the correcponding action when user clickthis
subMenuItem1.addActionListener(this);//adding actionlistener
submenu.add(subMenuItem1);//adding to the submenu


subMenuItem2.setMnemonic(KeyEvent.VK_A);//creating shortcut keyAlt+A
subMenuItem2.setActionCommand(\"arial\");//respond when the commandequals to arial
subMenuItem2.addActionListener(this);//adding action listener
submenu.add(subMenuItem2);//adding it to the submenu

subMenuItem3.setMnemonic(KeyEvent.VK_S);
subMenuItem3.setActionCommand(\"serif\");
subMenuItem3.addActionListener(this);
submenu.add(subMenuItem3);

submenu.addSeparator();

subMenuItem4.setMnemonic(KeyEvent.VK_B);
subMenuItem4.setActionCommand(\"bold\");
subMenuItem4.addActionListener(this);
submenu.add(subMenuItem4);

subMenuItem5.setMnemonic(KeyEvent.VK_I);
subMenuItem5.setActionCommand(\"italic\");
subMenuItem5.addActionListener(this);
submenu.add(subMenuItem5);

menuEdit.add(submenu);


// create Print menu


menuPrint.setMnemonic(KeyEvent.VK_P);

menuBar.add(menuPrint);

JMenuItem menuItemPrint = new JMenuItem(\"Send To Printer\");

menuItemPrint.setAccelerator(KeyStroke.getKeyStroke('P',KeyEvent.CTRL_DOWN_MASK));

menuItemPrint.setActionCommand(\"print\");

menuItemPrint.addActionListener(this);

menuPrint.add(menuItemPrint);

// create Help menu

menuHelp.setMnemonic(KeyEvent.VK_H);


menuBar.add(menuHelp);

JMenuItem menuItemHelp = new JMenuItem(\"About\");

menuItemHelp.setAccelerator(KeyStroke.getKeyStroke('A',KeyEvent.CTRL_DOWN_MASK));

menuItemHelp.setActionCommand(\"about\");
menuItemHelp.addActionListener(this);

JMenuItem menuItemVisitHomePage = new JMenuItem(\"Visit HomePage\");

menuItemVisitHomePage.setAccelerator(KeyStroke.getKeyStroke('V',KeyEvent.CTRL_DOWN_MASK));

menuItemVisitHomePage.setActionCommand(\"visithomepage\");
menuItemVisitHomePage.addActionListener(this);

menuHelp.add(menuItemHelp);

menuHelp.addSeparator();

menuHelp.add(menuItemVisitHomePage);

notePadArea = new JTextArea();

// set no word wrap

notePadArea.setWrapStyleWord(false);

// create scrollable pane

scrollPane = new JScrollPane(notePadArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

this.add(scrollPane,BorderLayout.CENTER);

}


@Override

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals(\"exit\")) {

System.exit(0);

}else if (e.getActionCommand().equals(\"open\")) {

JFileChooser file = new JFileChooser();

String fileName = \"\";//initial filename was empty

// show open file dialog

if (file.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){

fileName = file.getSelectedFile().getAbsolutePath();

} else {

return;

}

try(BufferedReader bufferedReader = new BufferedReader(newFileReader(fileName));) {

// load file content into text area

StringBuffer stringBuffer = new StringBuffer();//creating astring buffer for reading data from file

String lines = \"\";//for reading the lines from the selectingfile

while((lines = bufferedReader.readLine() ) != null) {//it'llread untill the file ends

stringBuffer.append(lines).append(\"\n\");//for every line readinsert new line in stringBuffer

}

bufferedReader.close();//after reading of file done, thebufferedReader will be close

notePadArea.setText(stringBuffer.toString());//converting theread text to string and inserting this text into textArea

} catch (Exception error1) {//if any exception occures

System.out.println(error1.toString());//convert the expectioninto string and print it

}

} else if (e.getActionCommand().equals(\"save\")) {//if the userclick the save command then the file will gonna saved


JFileChooser file = new JFileChooser();//creating the filechooser

String fileName = \"\";//initial file name is empty

// show open file dialog

if (file.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){//if the user select file and clicks OK button

fileName = file.getSelectedFile().getAbsolutePath();

} else {//other wise will be closed
return;
}

try(BufferedWriter bufferedWriter = new BufferedWriter(newFileWriter(fileName));) {

// write editor's content to selected file.

bufferedWriter.write(notePadArea.getText());//get the textentered in textarea
bufferedWriter.flush();//clear the writer
} catch(Exception ex1) {}

} else if (e.getActionCommand().equals(\"color\")) {

Color select_color = JColorChooser.showDialog(this, \"Select acolor\", Color.RED);
notePadArea.setForeground(select_color);

} else if (e.getActionCommand().equals(\"times_new_roman\")){
if(subMenuItem1.isSelected())
notePadArea.setFont(new Font(\"Times New Roman\", Font.PLAIN,20));

} else if (e.getActionCommand().equals(\"arial\")) {
if(subMenuItem2.isSelected())
notePadArea.setFont(new Font(\"Arial\", Font.PLAIN, 20));

} else if (e.getActionCommand().equals(\"serif\")) {
if(subMenuItem3.isSelected())
notePadArea.setFont(new Font(\"Serif\", Font.PLAIN, 20));

} else if (e.getActionCommand().equals(\"bold\")) {
if(subMenuItem4.isSelected()){
if(subMenuItem5.isSelected()){
notePadArea.setFont(new Font(\"Serif\", Font.BOLD+Font.ITALIC,12));
}else{
notePadArea.setFont(new Font(\"Serif\", Font.BOLD, 12));
}
}else{
if(!subMenuItem5.isSelected())
notePadArea.setFont(new Font(\"Serif\", Font.PLAIN, 12));
}

} else if (e.getActionCommand().equals(\"italic\")) {

if(subMenuItem5.isSelected()){
if(subMenuItem4.isSelected()){
notePadArea.setFont(new Font(\"Serif\", Font.BOLD+Font.ITALIC,12));
}else{
notePadArea.setFont(new Font(\"Serif\", Font.ITALIC, 12));
}
}else{
if(!subMenuItem4.isSelected())
notePadArea.setFont(new Font(\"Serif\", Font.PLAIN, 12));
}

} else if (e.getActionCommand().equals(\"print\")) {

int output = JOptionPane.showConfirmDialog(this, \"Do you want toprint the File\",\"Confirmation\", JOptionPane.YES_NO_OPTION);
if(output==0){
JOptionPane.showMessageDialog(this, \"The file is successfullyprinted\",\"Confirmation\", JOptionPane.INFORMATION_MESSAGE);
}
} else if (e.getActionCommand().equals(\"changecolor\")){
System.out.println(\"Color clicked\");
}
else if (e.getActionCommand().equals(\"about\")) {

JOptionPane.showMessageDialog(this, \"This software is developedin 2019\nVersion is 1.0\",\"About\",JOptionPane.INFORMATION_MESSAGE);

} else if (e.getActionCommand().equals(\"visithomepage\")) {

openWebpage(\"http://www.microsoft.com\");

}

}

private void openWebpage (String urlString) {

try {

Desktop.getDesktop().browse(new URL(urlString).toURI());

}

catch (Exception e) {

e.printStackTrace();
}
}
}

import javax.swing.JFrame;
public class MyMenuFrameTest {
public static void main(String[] args) {
MyMenuFrame frame = new MyMenuFrame();
frame.setTitle(\"MyNotepad\");
//for the title of the box
frame.setSize(600, 400);
//for the size of the box
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);
}
}

Answer & Explanation Solved by verified expert
4.4 Ratings (773 Votes)
I AM NOT ABLE TO SHOW OUTPUT AS JAVA IS NOT ALLOWING METO CAPTURE THE SCREENPLEASE RUN THIS THE RADIOBUTTON AND CHECKBOX SELECTIONBUG IS NOW FIXEDimport javaawtimport javaawtColorimport javaawtDesktopimport javaawtFontimport javaawteventimport javanetURLimport javaioBufferedReaderimport javaioBufferedWriterimport javaioFileReaderimport javaioFileWriterimport javaxswingJCheckBoximport javaxswingJColorChooserimport javaxswingJFileChooserimport javaxswingJFrameimport javaxswingJMenuimport javaxswingJMenuBarimport javaxswingJMenuItemimport javaxswingJOptionPaneimport javaxswingJRadioButtonimport javaxswingJScrollPaneimport javaxswingJTextAreaimport javaxswingKeyStrokeMyMenuFrame will use Jframe with actionlistenerclass MyMenuFrame extends JFrame implements ActionListenercreating the main menu itemsJMenu menuEdit new JMenuEditJMenu menuPrint new JMenuPrintJMenu mnFile new JMenuFileJMenu menuHelp new JMenuHelpcreating the submenu items here because we are gonna use theseacross the codeJRadioButton subMenuItem1 new JRadioButtonTimes NewRomanJRadioButton subMenuItem2 new JRadioButtonArialJRadioButton subMenuItem3 new JRadioButtonSerifJCheckBox subMenuItem4 new JCheckBoxBoldJCheckBox subMenuItem5 new JCheckBoxItalicprovide scrollable view of a componentJScrollPane scrollPanecreating notePadArea for notepad to input the textJTextArea notePadAreapublic MyMenuFrame setting the border layout for JFramethissetLayoutnew BorderLayout create menu bar named menuBarJMenuBar menuBar new JMenuBarthissetJMenuBarmenuBaradding the menubar to JFrame create File menumnFilesetMnemonicKeyEventVKFAltFmenuBaraddmnFileadding the menufile create Open menu itemJMenuItem mntmOpen new JMenuItemOpencreating the OpenmenumntmOpensetMnemonicKeyEventVKOAltO commandmntmOpensetActionCommandopenwhen the command equals toopen then the corresponding action will be performedmntmOpensetAcceleratorKeyStrokegetKeyStrokeOKeyEventCTRLDOWNMASKrespond when user clicks CtrlOmntmOpenaddActionListenerthisadding actionLister to theMenu Option Open create    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students