Cannot change font & font size in JTextArea using JComboBoxes - java

I have created a JFrame where the user can edit text in a JTextArea. There is a JComboBox to change font type, a JComboBox to change font size, and 2 JCheckBoxes to make the text Bold and Italic. I have finished the JCheckBoxes, but I cannot figure out how to allow change font and font size by using the JComoboBoxes. Any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SetFontModified extends JFrame
{
private JPanel p1, p2;
private JLabel jlblFontName, jlblFontSize;
private JComboBox jcbFonts, jcbSizes;
private JTextArea jtxtWelcome;
private JCheckBox jckbBold, jckbItalic;
public SetFontModified()
{
p1 = new JPanel();
jlblFontName = new JLabel("Font Name");
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = e.getAvailableFontFamilyNames();
jcbFonts = new JComboBox(fontNames);
jlblFontSize = new JLabel("Font Size");// add 2nd JLabel
jcbSizes = new JComboBox(); // create 2nd JComboBox
for(int i = 1; i < 101; i ++) // populate JComboBox with array of font sizes 1-100
{
jcbSizes.addItem(i);
}
p1.add(jlblFontName); // add all 4 components to p1
p1.add(jcbFonts);
p1.add(jlblFontSize);
p1.add(jcbSizes);
jtxtWelcome = new JTextArea("Welcome to Java", 3, 20);// add a JTextArea
add(jtxtWelcome);
p2 = new JPanel(); // create p2 & add JCheckBoxes
p2.add(jckbBold = new JCheckBox("Bold"));
jckbBold.setMnemonic('B');
p2.add(jckbItalic = new JCheckBox("Italic"));
jckbItalic.setMnemonic('I');
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
ListenerClass listener = new ListenerClass();
jcbFonts.addActionListener(listener);
jcbSizes.addActionListener(listener);
jckbBold.addActionListener(listener);
jckbItalic.addActionListener(listener);
}
public static void main(String[] args)
{
SetFontModified frame = new SetFontModified();
frame.setTitle("Set Font Details");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jcbSizes.getFontSize();
Font plainFont = new Font("serif", Font.PLAIN, size);
Font boldFont = new Font("serif", Font.BOLD, 14);
Font italicFont = new Font("serif", Font.ITALIC, 14);
Font boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);
if (jckbBold.isSelected() && jckbItalic.isSelected())
jtxtWelcome.setFont(boldItalicFont);
else if (jckbBold.isSelected())
jtxtWelcome.setFont(boldFont);
else if (jckbItalic.isSelected())
jtxtWelcome.setFont(italicFont);
else jtxtWelcome.setFont(plainFont);
}
}
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame
{
private JPanel p1, p2;
private JLabel jlblFontName, jlblFontSize;
private JComboBox jcbFonts, jcbSizes;
private JTextArea jtxtWelcome;
private JCheckBox jckbBold, jckbItalic;
public Test()
{
p1 = new JPanel();
jlblFontName = new JLabel("Font Name");
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = e.getAvailableFontFamilyNames();
jcbFonts = new JComboBox(fontNames);
jlblFontSize = new JLabel("Font Size"); // add 2nd JLabel
jcbSizes = new JComboBox(); // create 2nd JComboBox
for(int i = 1; i < 101; i ++) // populate JComboBox with array of font sizes 1-100
{
jcbSizes.addItem(i);
}
p1.add(jlblFontName); // add all 4 components to p1
p1.add(jcbFonts);
p1.add(jlblFontSize);
p1.add(jcbSizes);
jtxtWelcome = new JTextArea("Welcome to Java", 3, 20); // add a JTextArea
add(jtxtWelcome);
p2 = new JPanel(); // create p2 & add JCheckBoxes
p2.add(jckbBold = new JCheckBox("Bold"));
jckbBold.setMnemonic('B');
p2.add(jckbItalic = new JCheckBox("Italic"));
jckbItalic.setMnemonic('I');
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
ListenerClass listener = new ListenerClass();
jcbFonts.addActionListener(listener);
jcbSizes.addActionListener(listener);
jckbBold.addActionListener(listener);
jckbItalic.addActionListener(listener);
}
public static void main(String[] args)
{
Test frame = new Test();
frame.setTitle("Set Font Details");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//jcbSizes.getFontSize();
Font plainFont = new Font("serif", Font.PLAIN, Integer.parseInt(jcbSizes.getSelectedItem().toString()));
Font boldFont = new Font("serif", Font.BOLD, 14);
Font italicFont = new Font("serif", Font.ITALIC, 14);
Font boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);
if (jckbBold.isSelected() && jckbItalic.isSelected())
jtxtWelcome.setFont(boldItalicFont);
else if (jckbBold.isSelected())
jtxtWelcome.setFont(boldFont);
else if (jckbItalic.isSelected())
jtxtWelcome.setFont(italicFont);
else jtxtWelcome.setFont(plainFont);
}
}
}

You need the correct method for jcbSizes:
int size = (Integer) jcbSizes.getSelectedItem();

The compiler is complaining about an undefined variable size. You can add this declaration to your ActionListener:
int size = (Integer)jcbSizes.getSelectedItem();

but I cannot figure out how to allow change font and font size by
using the JComoboBoxes.
For this to happen you have to change your else block like follows.
else {
// jcbFonts.getSelectedItem().toString()
// gets font string selected in font combobox
// -------------------------------------
// jcbSizes.getSelectedIndex())
// get font size selected in size combobox
jtxtWelcome.setFont(new Font(jcbFonts.getSelectedItem()
.toString(), Font.PLAIN, jcbSizes.getSelectedIndex()));
System.out.println("Font Name: " + jcbFonts.getSelectedItem()
+ " Font Size:" + jcbSizes.getSelectedIndex());
}
Class Font API

Related

java gui background color doesn't cover entire page

When i created my gui in java, i set the background color to blackish and there seems to be a pixel line of white at the right most and bottom most sections of my gui. However when i resize this gui, that like goes away and the gui is completely black. Does anyone know why this is happening? I need my gui to set resizeable to false so resizing the gui to fix this problem will not work.
package JavaQuizGameTut;
import java.awt.ActiveEvent.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class Quiz implements ActionListener{
String[] questions = {
"Which company created Java?",
"What year was Java created?",
"What was java originally called?",
"Who was credited for making java?"
};
String[][] options = {{"Sun Microsystems", "Starbucks", "Microsoft", "Alphabet"},
{"1989", "1996", "1972", "1492"},
{"Apple", "Latte", "Oak", "Koffing"},
{"Steve Jobs", "Bill Gates", "James Gosling", "Mark Zuckerburg"}
};
char[] answers = {'A', 'B', 'C', 'C'};
char guess;
char answer;
int index;
int correct_guesses = 0;
int total_questions = questions.length;
int result;
int seconds;
JFrame frame = new JFrame();
JTextField textfield = new JTextField();
JTextArea textarea = new JTextArea();
JButton buttonA = new JButton();
JButton buttonB = new JButton();
JButton buttonC = new JButton();
JButton buttonD = new JButton();
JLabel answer_labelA = new JLabel();
JLabel answer_labelB = new JLabel();
JLabel answer_labelC = new JLabel();
JLabel answer_labelD = new JLabel();
JLabel time_label = new JLabel();
JLabel seconds_left = new JLabel();
JTextField number_right = new JTextField();
JTextField percentage = new JTextField();
public Quiz() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 650);
frame.getContentPane().setBackground(new Color(50, 50, 50));
frame.setLayout(null);
// frame.setResizable(false);
textfield.setBounds(0, 0, 650, 50);
textfield.setBackground(new Color(25,25, 25));
textfield.setForeground(new Color(25, 255, 0));
textfield.setFont(new Font("Ink Free", Font.PLAIN, 30));
textfield.setBorder(BorderFactory.createBevelBorder(1));
textfield.setHorizontalAlignment(JTextField.CENTER);
textfield.setEditable(false);
frame.add(textfield);
frame.setVisible(true);
}
public void nextQuestion() {
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void displayAnswer() {
}
public void results() {
}
}
The background color does cover the entire frame only the reason you are seeing a grey bar above it is that you have placed a textfield on top of it and you have set its background colour to be grey.
As in here:
textfield.setBounds(0, 0, 650, 50);
textfield.setBackground(new Color(25,25, 25));
Try changing textfield's color or temporarily commenting it and you'll see whole frame black.
If nothing fixes it then there's something wrong with your system as it is running fine in my system.
You can try running it in another system.

Setting the font of a JTextArea

I want to create a Text Editor in Java. Here is what I've written so far:
package com.thundercrust.applications;
import java.awt.BorderLayout;
public class TextEditor implements ActionListener{
private static String[] fontOptions = {"Serif", "Agency FB", "Arial", "Calibri", "Cambrian", "Century Gothic", "Comic Sans MS", "Courier New", "Forte", "Garamond", "Monospaced", "Segoe UI", "Times New Roman", "Trebuchet MS", "Serif"};
private static String[] sizeOptions = {"8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28"};
ImageIcon newIcon = new ImageIcon("res/NewIcon.png");
ImageIcon saveIcon = new ImageIcon("res/SaveIcon.png");
ImageIcon openIcon = new ImageIcon("res/OpenIcon.png");
ImageIcon fontIcon = new ImageIcon("res/FontIcon.png");
ImageIcon changeFontIcon = new ImageIcon("res/ChangeFontIcon.png");
JButton New = new JButton(newIcon);
JButton Save = new JButton(saveIcon);
JButton Open = new JButton(openIcon);
JButton changeFont = new JButton(changeFontIcon);
JLabel fontLabel = new JLabel(fontIcon);
JLabel fontLabelText = new JLabel("Font: ");
JLabel fontSizeLabel = new JLabel("Size: ");
JComboBox <String> fontName = new JComboBox<>(fontOptions);
JComboBox <String> fontSize = new JComboBox<>(sizeOptions);
JToolBar tool = new JToolBar();
JTextArea texty = new JTextArea();
JScrollPane scroll = new JScrollPane(texty);
private static final int WIDTH = 1366;
private static final int HEIGHT = WIDTH / 16 * 9;
private static String name = "Text Editor";
private static JFrame frame = new JFrame();
public void Display() {
frame.setTitle(name);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
New.addActionListener(this);
New.setToolTipText("Creates a new File");
Save.addActionListener(this);
Save.setToolTipText("Saves the current File");
Open.addActionListener(this);
Open.setToolTipText("Opens a file");
changeFont.addActionListener(this);
changeFont.setToolTipText("Change the Font");
fontLabel.setToolTipText("Font");
fontLabelText.setToolTipText("Set the kind of Font");
fontSizeLabel.setToolTipText("Set the size of the Font");
tool.add(New);
tool.addSeparator();
tool.add(Save);
tool.addSeparator();
tool.add(Open);
tool.addSeparator();
tool.addSeparator();
tool.addSeparator();
tool.add(fontLabel);
tool.addSeparator();
tool.add(fontLabelText);
tool.add(fontName);
tool.addSeparator();
tool.add(fontSizeLabel);
tool.add(fontSize);
tool.addSeparator();
tool.add(changeFont);
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(tool, "North");
pane.add(scroll, "Center");
frame.setContentPane(pane);
}
public static void main(String args[]) {
TextEditor editor = new TextEditor();
editor.Display();
}
public void actionPerformed(ActionEvent evt) {
String fontNameSet;
String fontSizeSetTemp;
int fontSizeSet;
Object source = evt.getSource();
if(source == New) {
texty.setText("");
}
else if(source == changeFont) {
fontNameSet = (String) fontName.getSelectedItem();
fontSizeSetTemp = (String) fontSize.getSelectedItem();
fontSizeSet = Integer.parseInt(fontSizeSetTemp);
System.out.println(fontNameSet + fontSizeSet);
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
}
}
}
My problem is with setting fonts for the JTextArea. When I click the changeFont button on my actual program, nothing happens. What do I do?
new Font(fontNameSet, fontSizeSet, Font.PLAIN)
This has the arguments in the wrong order. It should be:
new Font(fontNameSet, Font.PLAIN, fontSizeSet)
Also, as mentioned in a comment:
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
Should be:
texty.setFont(new Font(fontNameSet, Font.PLAIN, fontSizeSet));

Nothing Displayed On Screen Java Swing Application

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimultaneousSolver extends JFrame implements ActionListener
{
JTextField tfEQ1X = new JTextField (20);
JTextField tfEQ1Y = new JTextField (20);
JTextField tfEQ1Num = new JTextField (20);
JTextField tfEQ2X = new JTextField (20);
JTextField tfEQ2Y = new JTextField (20);
JTextField tfEQ2Num = new JTextField (20);
JLabel lblX1 = new JLabel ("X₁");
JLabel lblY1 = new JLabel ("Y₁");
JLabel lblNum1 = new JLabel ("Number₁");
JLabel lblEqual1 = new JLabel ("=");
JLabel lblX2 = new JLabel ("X₂");
JLabel lblY2 = new JLabel ("Y₂");
JLabel lblNum2 = new JLabel ("Number₂");
JLabel lblEqual2 = new JLabel ("=");
JTextArea Empty = new JTextArea ("",1,20);
double X1, X2, Y1, Y2, Num1, Num2;
double SolX, SolY;
Font font = new Font("Comic Sans MS", Font.BOLD, 14);
SimultaneousSolver()
{
super ("Simultaneous Equation Solver");
setDesign();
setSize(700,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panelEquation1 = new JPanel(new GridLayout(1,7));
{
panelEquation1.add(lblX1);
panelEquation1.add(tfEQ1X);
panelEquation1.add(lblY1);
panelEquation1.add(tfEQ1Y);
panelEquation1.add(lblEqual1);
panelEquation1.add(lblNum1);
panelEquation1.add(tfEQ1Num);
}
JPanel panelEquation2 = new JPanel(new GridLayout(1,7));
{
panelEquation2.add(lblX2);
panelEquation2.add(tfEQ2X);
panelEquation2.add(lblY2);
panelEquation2.add(tfEQ2Y);
panelEquation2.add(lblEqual2);
panelEquation2.add(lblNum2);
panelEquation2.add(tfEQ2Num);
}
setVisible(true);
}
public final void setDesign()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e)
{
}
}
public static void main(String[] args)
{
new SimultaneousSolver();
}
}
Ok, So I am starting a new application development using pure swing if possible, so i set up my objects and stuff and when I try to run the application to see if it looks good, Nothing Shows up except an empty container.
Add these two lines at the end of constructor.
setLayout(new GridLayout()); // sets layout for frame - you can choose any one suitable layout
add(panelEquation1); // adds 1st panel
add(panelEquation2); // adds 2nd panel

How Do I get the buttons to work? Java Programming

I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}

Java - pass value of one radio button that selected to another frame

Is there any code that I can use to pass value of selected radio button to another frame?
This is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class bookBatman extends JFrame implements ActionListener {
private JLabel jlbName, jlbTime, jlbPic, jlbDate, jlbDescription, jlbAuthor, jlbDateProduce, jlbDirector, jlbActor, jlbRate, jlbNoOfTicket, jlbPrice, jlbTotal;
private JTextField jtfNoOfTicket;
private JRadioButton jr1, jr2, jr3, jr4, jr5, jr6, jr7, jr8, jr9, jr10;
private JButton jTotal, jBook, jCancel;
Font f = new Font("Times",Font.BOLD,30);
public bookBatman () {
setLayout(null); //set LayoutManager
// initialized the label
jlbName = new JLabel ("Batman The Dark Knight");
jlbTime = new JLabel ("Time :");
jlbPrice = new JLabel ("RM 9.00");
jlbPic = new JLabel ();
jlbPic.setIcon(new ImageIcon("C:\\Users\\User\\Desktop\\OOP project\\img\\icon\\Batman.jpg"));
jlbTotal = new JLabel (" Total : RM 9.00");
// add all the label on the frame
add(jlbName);
add(jlbPic);
add(jlbTime);
add(jlbPrice);
add(jlbTotal);
// set all the label positions
jlbName.setBounds(85, 78, 300, 18); //(int x, int y, int width, int height)
jlbPic.setBounds(74, 101, 180, 288);
jlbTime.setBounds(74, 400, 60, 18);
jlbPrice.setBounds (270, 477, 60, 18);
jlbTotal.setBounds (339, 475, 300, 22);
// initialized the textfield
jlbAuthor = new JLabel ("Directed by Christopher Nolan");
jlbDateProduce = new JLabel ("Date : 17 July 2008");
jlbDirector = new JLabel ("Author : Jonathan Nolan, Christopher Nolan");
jlbActor = new JLabel ("Main Actor : Christian Bale");
jlbRate = new JLabel ("Movie Rate : 13 PG (Parental Guidance)");
jlbNoOfTicket = new JLabel ("Number of Ticket :");
// add all the textfield on the frame
add(jlbAuthor);
add(jlbDateProduce);
add(jlbDirector);
add(jlbActor);
add(jlbRate);
add(jlbNoOfTicket);
// set the textfield position
jlbAuthor.setBounds (273, 102, 300, 18);
jlbDateProduce.setBounds (273, 132, 300, 18);
jlbDirector.setBounds (273, 162, 300, 18);
jlbActor.setBounds (273, 192, 300, 18);
jlbRate.setBounds (273, 222, 300, 18);
jlbNoOfTicket.setBounds (77, 478, 150, 18);
// initialize the Radio Button
jr1 = new JRadioButton ("11.40 AM");
jr2 = new JRadioButton ("12.00 PM");
jr3 = new JRadioButton ("1.40 PM");
jr4 = new JRadioButton ("3.40 PM");
jr5 = new JRadioButton ("5.40 PM");
jr6 = new JRadioButton ("7.00 PM");
jr7 = new JRadioButton ("9.00 PM");
jr8 = new JRadioButton ("10.40 PM");
jr9 = new JRadioButton ("11.40 PM");
jr10 = new JRadioButton ("12.40 AM");
// add all the radion button
add(jr1);
add(jr2);
add(jr3);
add(jr4);
add(jr5);
add(jr6);
add(jr7);
add(jr8);
add(jr9);
add(jr10);
// set the radion button positions
jr1.setBounds (75, 423, 100, 24);
jr2.setBounds (172, 423, 100, 24);
jr3.setBounds (269, 423, 100, 24);
jr4.setBounds (366, 423, 100, 24);
jr5.setBounds (463, 423, 100, 24);
jr6.setBounds (75, 447, 100, 24);
jr7.setBounds (172, 447, 100, 24);
jr8.setBounds (269, 447, 100, 24);
jr9.setBounds (366, 447, 100, 24);
jr10.setBounds (463, 447, 100, 24);
// group the button
ButtonGroup group = new ButtonGroup ();
group.add(jr1);
group.add(jr2);
group.add(jr3);
group.add(jr4);
group.add(jr5);
group.add(jr6);
group.add(jr7);
group.add(jr8);
group.add(jr9);
group.add(jr10);
jr1.setActionCommand("radio1"); // for ButtonGroup
String sel = group.getSelection().getActionCommand();
// initialize all the button
jTotal = new JButton ("Total");
jBook = new JButton ("Book Now");
jCancel = new JButton ("Cancel");
// add all the button
add (jTotal);
add (jBook);
add (jCancel);
// set the button positions
jTotal.setBounds (191, 519, 83, 28);
jBook.setBounds (285, 519, 93, 28);
jCancel.setBounds (389, 519, 83, 28);
// add actionlistener
jTotal.addActionListener (this);
jBook.addActionListener (this);
jCancel.addActionListener (this);
// initialize all text field
jtfNoOfTicket = new JTextField (15);
// add all the text field
add (jtfNoOfTicket);
// set the text field positions
jtfNoOfTicket.setBounds (200, 477, 56, 22);
}
public void actionPerformed(ActionEvent e){
if((e.getSource() == jTotal)) {
double price = 12.00;
double number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
double total = 0.0;
total = price * number;
jlbTotal.setText(" Total : RM" + total +"0");
}
if((e.getSource() == jBook)) {
String name = jlbName.getText ();
String date = jlbDateProduce.getText ();
String time = jr1.getText ();
int number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
String total = jlbTotal.getText ();
String price = jlbPrice.getText ();
//Passing
ticketReservation frame = new ticketReservation(name, date, time, price, total, String.valueOf(number));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Ticket Reservation"); //set title of the window
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
if((e.getSource() == jCancel)) {
listOfMovies frame = new listOfMovies ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("List of Movies"); //set title of thewindow
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
}
public static void main (String [] args) {
bookBatman frame = new bookBatman ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Book Batman : The Dark Knight"); //set title of thewindow
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
}
Don't think of it as passing information from one GUI to another, but rather think of it in its most basic OOP form: as passing object state from one object to another. Often we use public accessor methods (i.e., "getter" methods) for this purpose and this can work here too.
Your ButtonGroup object will hold the ButtonModel of the selected JRadioButton (or null if none are selected) and so you can get the information from the model and return it from your getter method.
As an aside, your code has a lot of redundancies that can be reduced by using arrays and by using appropriate layout managers.
edit 1:
For Example
Say we create a JPanel that holds a bunch of JRadioButtons:
import java.awt.GridLayout;
import javax.swing.*;
class RadioBtnDialogPanel extends JPanel {
private static final String[] BUTTON_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
public RadioBtnDialogPanel() {
setLayout(new GridLayout(0, 1)); // give JPanel a decent layout
// create radio buttons, add to button group and to JPanel
for (String buttonText : BUTTON_TEXTS) {
JRadioButton radioBtn = new JRadioButton(buttonText);
radioBtn.setActionCommand(buttonText); // set the actionCommand here
buttonGroup.add(radioBtn);
add(radioBtn);
}
}
// getter or accessor method to get selected JRadioButton's actionCommand text
public String getSelectedButtonText() {
ButtonModel model = buttonGroup.getSelection();
if (model == null) { // no radiobutton selected
return "";
} else {
return model.getActionCommand();
}
}
}
We also give it a public getter method that queries the state of the ButtonGroup to find out which button model has been selected and then return its actionCommand, a String that holds the text that describes the radio button (here it's the same as the text of the radio button).
We can then show this JPanel in a JOptionPane in our main GUI and after the JOptionPane is done, query the object above by calling its getSelectedButtonText() method:
import java.awt.event.*;
import javax.swing.*;
public class RadioButtonInfo extends JPanel {
private RadioBtnDialogPanel radioBtnDlgPanel = new RadioBtnDialogPanel();
private JTextField textfield = new JTextField(10);
public RadioButtonInfo() {
JButton getDayOfWeekBtn = new JButton("Get Day Of Week");
getDayOfWeekBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getDayOfWeekActionPerformed();
}
});
textfield.setFocusable(false);
add(getDayOfWeekBtn);
add(textfield);
}
private void getDayOfWeekActionPerformed() {
// display a JOptionPane that holds the radioBtnDlgPanel
int result = JOptionPane.showConfirmDialog(this, radioBtnDlgPanel, "Select Day Of Week", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) { // if use presses "OK" get the selected radio button text
// here we call the getter method to get the selected button text
String selectedButtonText = radioBtnDlgPanel.getSelectedButtonText();
textfield.setText(selectedButtonText); // and put it into a JTextField
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("RadioButtonInfo");
frame.getContentPane().add(new RadioButtonInfo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories

Resources