Below is my code for testing BorderLayout and GridLayout, but I found that the JTextField in the JPanel using GridLayout is not resizable, no matter how many times I change the JTextField.setPreferredSize, it still remains the same.
public class Boderlayout implements ActionListener {
JButton bCalculate;
JLabel lPrinAmount,lInterestRate,lPayPerYear,lResult;
JTextField tPrinAmount,tInterestRate,tPayPerYear,tResult;
public static void main (String[] args) {
new Boderlayout();
}
public Boderlayout() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel p2 = new JPanel();
p2.setBackground(Color.BLUE);
p2.setPreferredSize(new Dimension(600,100));
frame.add(p2,BorderLayout.SOUTH);
bCalculate = new JButton("Calculate");
bCalculate.setPreferredSize(new Dimension(550,85));
p2.add(bCalculate);
bCalculate.addActionListener(this);
JPanel p3 = new JPanel();
p3.setBackground(Color.GREEN);
p3.setLayout(new GridLayout(6,1));
p3.setPreferredSize(new Dimension(300,300));
frame.add(p3,BorderLayout.CENTER);
lPrinAmount = new JLabel("Principle Amount: ");
lPrinAmount.setPreferredSize(new Dimension(200,40));
p3.add(lPrinAmount);
tPrinAmount = new JTextField(20);
tPrinAmount.setPreferredSize(new Dimension(170,40));
p3.add(tPrinAmount);
tPrinAmount.addActionListener(this);
lInterestRate = new JLabel("Interest Rate: ");
lInterestRate.setPreferredSize(new Dimension(200,40));
p3.add(lInterestRate);
tInterestRate = new JTextField(20);
tInterestRate.setPreferredSize(new Dimension(100,40));
p3.add(tInterestRate);
tInterestRate.addActionListener(this);
lPayPerYear = new JLabel("Payment Period (Year): ");
lPayPerYear.setPreferredSize(new Dimension(200,40));
p3.add(lPayPerYear);
tPayPerYear = new JTextField(20);
tPayPerYear.setPreferredSize(new Dimension(170,40));
p3.add(tPayPerYear);
tPayPerYear.addActionListener(this);
JPanel p5 = new JPanel();
p5.setLayout(new GridLayout(2,1));
p5.setBackground(Color.WHITE);
p5.setPreferredSize(new Dimension(300,300));
frame.add(p5,BorderLayout.EAST);
lResult = new JLabel("Result");
lResult.setPreferredSize(new Dimension(170,40));
p5.add(lResult);
tResult = new JTextField(50);
tResult.setPreferredSize(new Dimension(170,200));
tResult.setEditable(false);
p5.add(tResult);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == bCalculate) {
double prinAmount = Double.parseDouble(tPrinAmount.getText());
double interestRate = Integer.parseInt(tInterestRate.getText());
double paymentYear = Integer.parseInt(tPayPerYear.getText());
double interestRatePercentage = interestRate / 100;
double loanInterest = prinAmount * interestRatePercentage;
double year = 12 * paymentYear;
double mortgageResult = (loanInterest * (Math.pow((1 + (interestRatePercentage / 12)), year)) / (Math.pow((1 + (interestRatePercentage) / 12), year) - 1)) / 12;
String stringmortgageResult = Double.toString(mortgageResult);
String newline = System.getProperty("line.separator");
String finalResult = "Principle Amount: " + tPrinAmount.getText() + newline + "Interest Rate: " + tInterestRate.getText() + "%" + newline + "Payment Period: " + tPayPerYear.getText()
+ newline + "Mortgage: " + stringmortgageResult;
tResult.setText(finalResult);
}
}
}
Refer to How to Use GridLayout.
Here is a quote from that Web page:
A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size.
In other words, GridLayout does not consider the preferred size of the components it contains.
A layout manager that does consider its contained components' preferred size is GridBagLayout.
BorderLayout only respects part of its contained components' preferred size. For the EAST component, BorderLayout uses its preferred width but not its preferred height. BorderLayout will initially use its CENTER component's preferred width and height.
This is the window I get when I run your code.
Here is your modified code using GridBagLayout instead of GridLayout.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Boderlayout implements ActionListener {
JButton bCalculate;
JLabel lPrinAmount, lInterestRate, lPayPerYear, lResult;
JTextArea tResult;
JTextField tPrinAmount, tInterestRate, tPayPerYear;
public static void main(String[] args) {
new Boderlayout();
}
public Boderlayout() {
JFrame frame = new JFrame();
JPanel p2 = new JPanel();
p2.setBackground(Color.BLUE);
p2.setPreferredSize(new Dimension(600, 100));
frame.add(p2, BorderLayout.SOUTH);
bCalculate = new JButton("Calculate");
bCalculate.setPreferredSize(new Dimension(550, 85));
p2.add(bCalculate);
bCalculate.addActionListener(this);
JPanel p3 = new JPanel();
p3.setBackground(Color.GREEN);
p3.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
p3.setPreferredSize(new Dimension(300, 300));
frame.add(p3, BorderLayout.CENTER);
lPrinAmount = new JLabel("Principle Amount: ");
lPrinAmount.setPreferredSize(new Dimension(200, 40));
gbc.gridx = 0;
gbc.gridy = 0;
p3.add(lPrinAmount, gbc);
tPrinAmount = new JTextField(20);
tPrinAmount.setPreferredSize(new Dimension(170, 40));
gbc.gridy = 1;
p3.add(tPrinAmount, gbc);
tPrinAmount.addActionListener(this);
lInterestRate = new JLabel("Interest Rate: ");
lInterestRate.setPreferredSize(new Dimension(200, 40));
gbc.gridy = 2;
p3.add(lInterestRate, gbc);
tInterestRate = new JTextField(20);
tInterestRate.setPreferredSize(new Dimension(100, 40));
gbc.gridy = 3;
p3.add(tInterestRate, gbc);
tInterestRate.addActionListener(this);
lPayPerYear = new JLabel("Payment Period (Year): ");
lPayPerYear.setPreferredSize(new Dimension(200, 40));
gbc.gridy = 4;
p3.add(lPayPerYear, gbc);
tPayPerYear = new JTextField(20);
tPayPerYear.setPreferredSize(new Dimension(170, 40));
gbc.gridy = 5;
p3.add(tPayPerYear, gbc);
tPayPerYear.addActionListener(this);
JPanel p5 = new JPanel();
p5.setLayout(new BoxLayout(p5, BoxLayout.PAGE_AXIS));
p5.setBackground(Color.WHITE);
p5.setPreferredSize(new Dimension(300, 300));
frame.add(p5, BorderLayout.EAST);
lResult = new JLabel("Result");
lResult.setPreferredSize(new Dimension(170, 40));
p5.add(lResult);
tResult = new JTextArea();
tResult.setPreferredSize(new Dimension(170, 200));
tResult.setEditable(false);
tResult.setBorder(BorderFactory.createLineBorder(Color.darkGray));
p5.add(tResult);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bCalculate) {
double prinAmount = Double.parseDouble(tPrinAmount.getText());
double interestRate = Integer.parseInt(tInterestRate.getText());
double paymentYear = Integer.parseInt(tPayPerYear.getText());
double interestRatePercentage = interestRate / 100;
double loanInterest = prinAmount * interestRatePercentage;
double year = 12 * paymentYear;
double mortgageResult = (loanInterest
* (Math.pow((1 + (interestRatePercentage / 12)), year))
/ (Math.pow((1 + (interestRatePercentage) / 12), year) - 1)) / 12;
String stringmortgageResult = Double.toString(mortgageResult);
String newline = System.getProperty("line.separator");
String finalResult = "Principle Amount: " + tPrinAmount.getText() + newline
+ "Interest Rate: " + tInterestRate.getText() + "%" + newline
+ "Payment Period: " + tPayPerYear.getText() + newline + "Mortgage: "
+ stringmortgageResult;
tResult.setText(finalResult);
}
}
}
This is the window I get when I run the above code.
Note that I changed tResult to JTextArea rather than JTextField.
Related
I created a table out of JLabels. I made it so that when the Jpanel the labels are in are resized, the text will scale accordingly. I initially forgot to set the default close operation on the JFrame so I ended up having a ton of instances of them running in the background, until eclipse said the stack/ heap was full. I added that so now it closes correctly, however it got me wondering how much one instance of it takes up. When it launches to its default size, it only takes up about 24000K. If you move it around a lot it peeks at about 200000K and sits at 180000 K if you leave it alone. Why is my program taking up so much memory?
/**
* Class to create the specified table
* #author CGordo01
*
*/
public class WordDocumentTable extends JPanel{
Font f;
// Holds all the label, is used for resizing
ArrayList<JLabel> allLabels= new ArrayList<JLabel>();
/**
* Creates the table
*/
public WordDocumentTable(){
// Sets the layout to a gridBagLayout
this.setLayout(new GridBagLayout());
//Adds a component listener
this.addComponentListener(new ComponentAdapter() {
#Override
/**
* If the component is resized makes the text fit the dimensions
*/
public void componentResized(ComponentEvent e) {
// Boolean used to see if the text width fits the component.
Boolean fits= false;
// value used to divide the components height by.
int divider = 16;
// Makes the font size scale according to the width and height.
while(fits == false){
f = new Font("SansSerif", Font.PLAIN, e.getComponent().getHeight()/divider);
for (int i = 0; i<allLabels.size();i++){
allLabels.get(i).setFont(f);
//System.out.println(divider);
if(allLabels.get(i).getGraphics().getFontMetrics().stringWidth(allLabels.get(i).getText())>allLabels.get(i).getWidth()){
fits = false;
divider++;
break;
}
else{
fits = true;
}
}
}
}
});
makeLeftCells();
makeMidCells();
makeLongCells();
makeTopCells();
}
/**
* Creates the cells that are in between widths of the other cells
*/
private void makeMidCells() {
GridBagConstraints midCells = new GridBagConstraints();
midCells.fill= GridBagConstraints.BOTH;
midCells.weightx=1;
midCells.weighty=1;
midCells.gridwidth=4;
midCells.gridy=9;
midCells.gridx=1;
JLabel b = new JLabel();
b.setText(".Batch Total " + " 985124 " + " Patches ");
b.setName("Previous Batch Total");
b.setBackground(Color.white);
b.setBorder(new LineBorder(Color.black));
b.setOpaque(true);
b.setFont(f);
this.add(b,midCells);
midCells.gridx=5;
JLabel b2 = new JLabel();
b2.setText(".Shift Total " + " 985124 " + " Patches ");
b2.setName("Previous Shift Total");
b2.setBackground(Color.white);
b2.setBorder(new LineBorder(Color.black));
b2.setOpaque(true);
b2.setFont(f);
this.add(b2,midCells);
midCells.gridy=12;
midCells.gridx=1;
JLabel c = new JLabel();
c.setText(".Batch Total " + " 985124 " + " Patches ");
c.setName("Batch Total");
c.setBackground(Color.white);
c.setBorder(new LineBorder(Color.black));
c.setOpaque(true);
c.setFont(f);
this.add(c,midCells);
midCells.gridx=5;
JLabel c2 = new JLabel();
c2.setText(".Shift Total " + " 985124 " + " Patches ");
c2.setName("Shift Total");
c2.setBackground(Color.white);
c2.setBorder(new LineBorder(Color.black));
c2.setOpaque(true);
c2.setFont(f);
this.add(c2,midCells);
allLabels.add(b);
allLabels.add(b2);
allLabels.add(c);
allLabels.add(c2);
}
/**
* Creates the cells which span much of the grid
*/
private void makeLongCells() {
GridBagConstraints longCells = new GridBagConstraints();
longCells.fill= GridBagConstraints.BOTH;
longCells.weightx=1;
longCells.weighty=1;
longCells.gridwidth=8;
longCells.gridx=1;
longCells.gridy=7;
JLabel b = new JLabel();
b.setText("Finish the Batch");
b.setName("Previous Shift Goal");
b.setBackground(Color.white);
b.setBorder(new LineBorder(Color.black));
b.setOpaque(true);
b.setFont(f);
this.add(b,longCells);
longCells.gridy=8;
JLabel c = new JLabel();
c.setText("<html><p> blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah</p></html>");
c.setName("Previous Shift Notes");
c.setBackground(Color.white);
c.setBorder(new LineBorder(Color.black));
c.setOpaque(true);
c.setFont(f);
this.add(c,longCells);
longCells.gridy=10;
JLabel d = new JLabel();
d.setText("Shift Goal");
d.setName("Shift Goal");
d.setBackground(Color.white);
d.setBorder(new LineBorder(Color.black));
d.setOpaque(true);
d.setFont(f);
this.add(d,longCells);
longCells.gridy=11;
JLabel e = new JLabel();
e.setText("Shift Notes");
e.setName("Shift Goal");
e.setBackground(Color.white);
e.setBorder(new LineBorder(Color.black));
e.setOpaque(true);
e.setFont(f);
this.add(e,longCells);
longCells.gridy=13;
JLabel f2 = new JLabel();
f2.setText("");
f2.setName("WO Schedule Note");
f2.setBackground(Color.white);
f2.setBorder(new LineBorder(Color.black));
f2.setOpaque(true);
f2.setFont(f);
this.add(f2,longCells);
longCells.gridy=14;
JLabel g = new JLabel();
g.setText("");
g.setName("Supervisor");
g.setBackground(Color.white);
g.setBorder(new LineBorder(Color.black));
g.setOpaque(true);
g.setFont(f);
this.add(g,longCells);
allLabels.add(b);
allLabels.add(c);
allLabels.add(d);
allLabels.add(e);
allLabels.add(f2);
allLabels.add(g);
}
/**
* Creates a 8x7 grid of small cells
*/
private void makeTopCells() {
GridBagConstraints topCells = new GridBagConstraints();
topCells.fill= GridBagConstraints.BOTH;
topCells.weighty=1;
topCells.weightx=1;
for (int i = 0; i < 8; i++)
{
topCells.gridx=i+1;
for (int j = 0; j < 7; j++)
{
topCells.gridy=j;
JLabel b = new JLabel();
b.setText("" + i + j);
b.setName("" + i + j);
b.setOpaque(true);
b.setFont(f);
if(j==0){
b.setBackground(new Color(242,242,242));
}
else{
b.setBackground(Color.white);
}
b.setBorder(new LineBorder(Color.black));
allLabels.add(b);
this.add(b,topCells);
}
}
}
private void makeLeftCells() {
GridBagConstraints leftCells = new GridBagConstraints();
leftCells.fill = GridBagConstraints.BOTH;
leftCells.gridx = 0;
leftCells.gridy = 0;
leftCells.weightx=2;
leftCells.weighty=1;
JLabel titleBlock = new JLabel();
titleBlock.setOpaque(true);
titleBlock.setText("Delta Hydrogel A");
titleBlock.setForeground(Color.white);
titleBlock.setBackground(new Color(79,129,189));
titleBlock.setBorder(new LineBorder(Color.black));
titleBlock.setFont(f);
this.add(titleBlock, leftCells);
leftCells.gridy = 1;
leftCells.gridheight=3;
JLabel tallBlock1 = new JLabel();
tallBlock1.setOpaque(true);
tallBlock1.setText(".Day Shift");
tallBlock1.setForeground(Color.black);
tallBlock1.setBackground(new Color(242,242,242));
tallBlock1.setBorder(new LineBorder(Color.black));
tallBlock1.setFont(f);
this.add(tallBlock1, leftCells);
JLabel tallBlock2 = new JLabel();
tallBlock2.setOpaque(true);
tallBlock2.setText(".Night Shift");
tallBlock2.setForeground(Color.black);
tallBlock2.setBackground(new Color(242,242,242));
tallBlock2.setBorder(new LineBorder(Color.black));
tallBlock2.setFont(f);
leftCells.gridy = 4;
this.add(tallBlock2, leftCells);
JLabel shortBlock1 = new JLabel();
shortBlock1.setOpaque(true);
shortBlock1.setText(".Previous Shift Goal");
shortBlock1.setForeground(Color.black);
shortBlock1.setBackground(new Color(242,242,242));
shortBlock1.setBorder(new LineBorder(Color.black));
shortBlock1.setFont(f);
leftCells.gridy = 7;
leftCells.gridheight=1;
this.add(shortBlock1, leftCells);
JLabel shortBlockTall = new JLabel();
shortBlockTall.setOpaque(true);
shortBlockTall.setText(".Previous Shift Notes");
shortBlockTall.setForeground(Color.black);
shortBlockTall.setBackground(new Color(242,242,242));
shortBlockTall.setBorder(new LineBorder(Color.black));
shortBlockTall.setFont(f);
leftCells.gridy = 8;
leftCells.ipady=50;
this.add(shortBlockTall, leftCells);
JLabel shortBlock2 = new JLabel();
shortBlock2.setOpaque(true);
shortBlock2.setText(".Previous Shift Output");
shortBlock2.setForeground(Color.black);
shortBlock2.setBackground(new Color(242,242,242));
shortBlock2.setBorder(new LineBorder(Color.black));
shortBlock2.setFont(f);
leftCells.gridy = 9;
leftCells.ipady=0;
this.add(shortBlock2, leftCells);
JLabel shortBlock3 = new JLabel();
shortBlock3.setOpaque(true);
shortBlock3.setText(".Shift Goals");
shortBlock3.setForeground(Color.black);
shortBlock3.setBackground(new Color(184,204,228));
shortBlock3.setBorder(new LineBorder(Color.black));
shortBlock3.setFont(f);
leftCells.gridy = 10;
leftCells.ipady=0;
this.add(shortBlock3, leftCells);
JLabel shortBlock4 = new JLabel();
shortBlock4.setOpaque(true);
shortBlock4.setText(".Shift Notes");
shortBlock4.setForeground(Color.black);
shortBlock4.setBackground(new Color(184,204,228));
shortBlock4.setBorder(new LineBorder(Color.black));
shortBlock4.setFont(f);
leftCells.gridy = 11;
leftCells.ipady=0;
this.add(shortBlock4, leftCells);
JLabel shortBlock5 = new JLabel();
shortBlock5.setOpaque(true);
shortBlock5.setText(".Output");
shortBlock5.setForeground(Color.black);
shortBlock5.setBackground(new Color(184,204,228));
shortBlock5.setBorder(new LineBorder(Color.black));
shortBlock5.setFont(f);
leftCells.gridy = 12;
this.add(shortBlock5, leftCells);
JLabel shortBlock6 = new JLabel();
shortBlock6.setOpaque(true);
shortBlock6.setText(".WO Schedule Note");
shortBlock6.setForeground(Color.black);
shortBlock6.setBackground(new Color(184,204,228));
shortBlock6.setBorder(new LineBorder(Color.black));
shortBlock6 .setFont(f);
leftCells.gridy = 13;
this.add(shortBlock6, leftCells);
JLabel shortBlock7 = new JLabel();
shortBlock7.setOpaque(true);
shortBlock7.setText(".Supervisor");
shortBlock7.setForeground(Color.black);
shortBlock7.setBackground(new Color(184,204,228));
shortBlock7.setBorder(new LineBorder(Color.black));
shortBlock7.setFont(f);
leftCells.gridy = 14;
this.add(shortBlock7, leftCells);
allLabels.add(titleBlock);
allLabels.add(tallBlock1);
allLabels.add(tallBlock2);
allLabels.add(shortBlock1);
allLabels.add(shortBlockTall);
allLabels.add(shortBlock2);
allLabels.add(shortBlock3);
allLabels.add(shortBlock4);
allLabels.add(shortBlock5);
allLabels.add(shortBlock6);
allLabels.add(shortBlock7);
}
public static void main (String[] args)
{
JFrame J = new JFrame();
J.setSize(600,400);
J.setVisible(true);
WordDocumentTable wdc= new WordDocumentTable();
J.setContentPane(wdc);
J.setVisible(true);
J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You'll want to profile to be sure, but it may help to focus on your implementation of componentResized(). As the enclosing container is resized, the method will be invoked repeatedly. In the handler, you're continually instantiating a new Font inside a while loop. At a minimum, consider using deriveFont(). Note especially that the size parameter is a float, while your present calculation appears to use a truncating integer division.
I have this program that reads questions with multiple choice answers from a text file and then displays a random set of them in a JOptionPane (very question in a new Pane). In my text file the questions and the 4 options of answers are all in one line and then I divide them into new lines. Now I want to try to add JRadioButtons before every single answer. Is there someone who can help me. Thank you very much in advance. Here is my code:
Random random = new Random();
for (int i = 0; i < newRanQues; i++) {
int randIndex = random.nextInt(32) + 0;
String randomQuestion = questions.get(randIndex);
randomQuestions.add(randomQuestion);
String different = randomQuestion.replaceAll(";", "\n");
{
JOptionPane.showMessageDialog(null, different, "Question", JOptionPane.INFORMATION_MESSAGE);
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
ButtonGroup group = new ButtonGroup();
group.add(optionA);
group.add(optionB);
group.add(optionC);
group.add(optionD);
return;
}
This should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class RadioButtonExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("Question");
// create the answers
String[] answer = { "red", "green", "yellow", "blue, no, red, no... arrrrrg" };
// create the radio buttons
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
// create the button group
ButtonGroup group = new ButtonGroup();
group.add(answerA);
group.add(answerB);
group.add(answerC);
group.add(answerD);
// add the question to the jframe
jframe.add(new JLabel("What is your favorite colour?"), BorderLayout.NORTH);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.gridwidth = 1;
cons.fill = GridBagConstraints.HORIZONTAL;
// answer 1
cons.gridx = 0;
cons.gridy = 1;
pan.add(answerA, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 2;
pan.add(answerB, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 3;
pan.add(answerC, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 4;
pan.add(answerD, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 400);
jframe.setVisible(true);
}
}
I'm preparing a simple system as my assignment, And I'm facing a problem where I dont know how to getText the value of String. I know how to do it with integer, but not with string.
I use Integer.parseInt(t2.getText()); in my code if i want to get an integer value
I have added my code into this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tollRate extends JFrame implements ActionListener {
JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;
tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}
public static void main(String[] args) {
tollRate a = new tollRate();
}
}
First of all String i, j, k;
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
This is wrong. You are assigning String for int. Correct them first. and if you want int values it is better to use
int i, j, k; and use trim() to avoid additional spaces.
i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());
In your case use as follows
i = t1.getText();
j = t2.getText();
k = t3.getText();
to assign a string to a string all you need to do is
i = t1.getText();
j = t2.getText();
k = t3.getText();
as you have created them as strings already
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class NICCode extends JFrame {
NICCode() {
setSize(600, 250);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
// JPanel
JPanel labelPanel = new JPanel(new FlowLayout(1));
JPanel leftBodyPanel = new JPanel(new GridLayout(3, 1));
JPanel bodyPanel = new JPanel(new GridLayout(3, 1));
JPanel buttonPanel = new JPanel(new FlowLayout(2));
JPanel textFieldPanel = new JPanel(new FlowLayout(0));
// JLabel
JLabel titleLabel = new JLabel("Find Your Birthday By NIC");
titleLabel.setFont(new Font("", 1, 25));
JLabel myLabel = new JLabel("CSG");
myLabel.setFont(new Font("", 1, 10));
JLabel enterNicLabel = new JLabel("Enter Your NIC :");
JLabel yourBirthDayLabel = new JLabel("Your Birth Day :");
JLabel yourGenderLabel = new JLabel("Gender :");
JLabel printBirthDayLabel = new JLabel("Your Birth Day");
JLabel printGenderLabel = new JLabel("Your Gender");
// JTextField
JTextField nicText = new JTextField(25);
nicText.setText("920000000V");
// JButton
JButton searchAgainButton = new JButton("Search Again");
JButton exitButton = new JButton("Exit");
// adds
add("North", labelPanel);
add("West", leftBodyPanel);
add("South", buttonPanel);
add(bodyPanel);
labelPanel.add(titleLabel);
leftBodyPanel.add(enterNicLabel);
leftBodyPanel.add(yourBirthDayLabel);
leftBodyPanel.add(yourGenderLabel);
textFieldPanel.add(nicText);
bodyPanel.add(textFieldPanel);
bodyPanel.add(printBirthDayLabel);
bodyPanel.add(printGenderLabel);
buttonPanel.add(myLabel);
buttonPanel.add(searchAgainButton);
buttonPanel.add(exitButton);
setVisible(true);
// pack();
String yearText = nicText.substring(0, 2);
String dateText = nicText.substring(2, 5);
String sex = "";
int year = Integer.parseInt(yearText);
int date = Integer.parseInt(dateText);
int month = 0;
if (date > 500) {
sex = "Feamale";
date -= 500;
} else {
sex = "Male";
}
int datesOfMonths[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int i = 0; i < 12; i++) {
date = date - datesOfMonths[i];
month = i;
if (date < datesOfMonths[i + 1]) {
break;
}
}
if (month > 0) {
month += 1;
}
}
}
I just created a program for find birthday from nic. I couldn't fix this compile error.
I created a JTextField to get Nic, then I added substring methods to get the needed numbers to find nic. Unfortunately the substring methods can't find textField. It shows error as 'cannot find symbol'. It's a TextField. Why can't the method find that TextField.?
The message:
cannot find symbol
Is not referring to the text field, but the method substring(..) which does not exist for JTextField. But something like..
textField.getText().substring(...);
..probably will work, since getText() returns a String and String has that method.
Change
String yearText = nicText.substring(0, 2);
String dateText = nicText.substring(2, 5);
to
String yearText = nicText.getText().substring(0, 2);
String dateText = nicText.getText().substring(2, 5);
I'm having trouble with my radio buttons. I can click on all three at the same time. It should be when you click on one the other one turns off?
I'm using a grid layout. So when I try group.add it doesn't work.
Example:
I have the buttons declared like this
JRadioButton seven = new JRadioButton("7 years at 5.35%", false);
JRadioButton fifteen = new JRadioButton("15 years at 5.5%", false);
JRadioButton thirty = new JRadioButton("30 years at 5.75%", false);
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
This is my code:
/*Change Request #6
Write the program in Java (with a graphical user interface)
so that it will allow the user to select which way
they want to calculate a mortgage:
by input of the amount of the mortgage,
the term of the mortgage,
and the interest rate of the mortgage payment
or by input of the amount of a mortgage and
then select from a menu of mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5 %
- 30 year at 5.75%
In either case, display the mortgage payment amount
and then, list the loan balance and interest paid
for each payment over the term of the loan.
Allow the user to loop back and enter a new amount
and make a new selection, or quit.
Insert comments in the program to document the program.
*/
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WK4 extends JFrame implements ActionListener
{
int loanTerms[] = { 7, 15, 30 };
double annualRates[] = { 5.35, 5.5, 5.75 };
// Labels
JLabel AmountLabel = new JLabel(" Loan Amount $ ");
JLabel PaymentLabel = new JLabel(" Monthly Payment ");
JLabel InterestLabel = new JLabel(" Interest Rate % ");
JLabel TermLabel = new JLabel(" Years of Loan ");
// Text Fields
JTextField mortgageAmount = new JTextField(6);
JTextField Payment = new JTextField(6);
JTextField InterestRate = new JTextField(3);
JTextField Term = new JTextField(3);
// Radio Buttons
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton seven = new JRadioButton("7 years at 5.35%");
JRadioButton fifteen = new JRadioButton("15 years at 5.5%");
JRadioButton thirty = new JRadioButton("30 years at 5.75%");
// Buttons
JButton exitButton = new JButton("Exit");
JButton resetButton = new JButton("Reset");
JButton calculateButton = new JButton("Calculate ");
// Text Area
JTextArea LoanPayments = new JTextArea(20, 50);
JTextArea GraphArea = new JTextArea(20, 50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public WK4(){
super("Mortgage Calculator");
//Window
setSize(700, 400);
setLocation(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(2, 2));
Container grid = getContentPane();
grid.setLayout(new GridLayout(4, 10, 0, 12)); //rows, cols, hgap, vgap
pane.add(grid);
pane.add(scroll);
grid.add(AmountLabel);
grid.add(mortgageAmount);
grid.add(InterestLabel);
grid.add(InterestRate);
grid.add(TermLabel);
grid.add(Term);
grid.add(PaymentLabel);
grid.add(Payment);
grid.add(Box.createHorizontalStrut(15));
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
grid.add(calculateButton);
grid.add(resetButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
// Action Listeners
mortgageAmount.addActionListener(this);
InterestRate.addActionListener(this);
Term.addActionListener(this);
Payment.addActionListener(this);
seven.addActionListener(this);
fifteen.addActionListener(this);
thirty.addActionListener(this);
calculateButton.addActionListener(this);
exitButton.addActionListener(this);
resetButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object command = e.getSource();
if (command == exitButton) {
System.exit(0);
}
else if (command == seven) {
calcLoan(loanTerms[0], annualRates[0]);
}
else if (command == fifteen) {
calcLoan(loanTerms[1], annualRates[1]);
}
else if (command == thirty) {
calcLoan(loanTerms[2], annualRates[2]);
}
else if (command == calculateButton) {
double years = 0;
double rates = 0;
try {
years = Double.parseDouble(Term.getText());
rates = Double.parseDouble(InterestRate.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
calcLoan(years, rates);
}
else if (command == resetButton) {
mortgageAmount.setText("");
Payment.setText("");
InterestRate.setText("");
Term.setText("");
LoanPayments.setText("");
}
}
private void calcLoan(double years, double rates) {
Term.setText(String.valueOf(years));
InterestRate.setText(String.valueOf(rates));
double amount = 0;
try {
amount = Double.parseDouble(mortgageAmount.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
double interestRate = rates;
double intRate = (interestRate / 100) / 12;
int months = (int) years * 12;
double rate = (intRate / 12);
double payment = amount * intRate
/ (1 - (Math.pow(1 / (1 + intRate), months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
NumberFormat CurrencyFormatter = NumberFormat.getCurrencyInstance();
Payment.setText(CurrencyFormatter.format(payment));
LoanPayments.setText(" Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while (currentMonth < months) {
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t"
+ CurrencyFormatter.format(MonthlyAmt) + "\t"
+ CurrencyFormatter.format(MonthlyInterest) + "\t"
+ CurrencyFormatter.format(remainingPrincipal) + "\n");
GraphArea.append("" + remainingPrincipal);
}
}
public static void main(String[] args) {
new WK4();
}
}
You're adding the radio buttons to the grid but you also need to add them to the button group that you defined.
Maybe this:
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
Should be this: ??? (Copy/paste bug?)
ButtonGroup group = new ButtonGroup();
group.add(seven);
group.add(fifteen);
group.add(thirty);
Or maybe you need to do both. The radio buttons have to belong to a container as well as a button group to be displayed and to behave properly.