Why won't this JAVA GUI process past the first entry? - java

In class today we put together a basic GUI for calculating the distance between two points. Neither the instructor nor my classmates could figure out why this GUI won't process. The code given to us was a framework and we just edited the old code to develop this. I compared my work to that of two other students and theirs worked while mine didn't.
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.awt.Color;
import java.awt.Font;
import java.lang.Math;
public class D2 extends JFrame
{
//****************************************
//** GUI Structure
//** Title: Holston Middle School
//** Weight prompt (jlabel, jtext)
//** planet pulldown
//** Weight on planet (jlabel, jtext)
//** calculate button
//****************************************
public JTextField entry1, entry2, entry3, entry4, output1;
public JLabel label1, label2, label3, label4, label5;
public JButton CalculateButton;
public String mtitle, cmessage;
public D2()
{
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
add(label1);
entry1 = new JTextField(8);
add(entry1);
setEnabled(true);
setVisible(true);
label2 = new JLabel("x2");
add(label2);
entry2 = new JTextField(8);
add(entry2);
setEnabled(true);
setVisible(true);
label3 = new JLabel("y1");
add(label3);
entry3 = new JTextField(8);
add(entry3);
setEnabled(true);
setVisible(true);
label4 = new JLabel("y2");
add(label4);
entry4 = new JTextField(8);
add(entry4);
setEnabled(true);
setVisible(true);
label5 = new JLabel("Distance");
add(label5);
output1 = new JTextField(8);
add(output1);
setEnabled(false);
setVisible(true);
CalculateButton = new JButton("Calculate");
add(CalculateButton);
CalculateButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String entry1string = entry1.getText();
Double e1value = Double.valueOf(entry1string);
String entry2string = entry2.getText();
Double e2value = Double.valueOf(entry2string);
String entry3string = entry3.getText();
Double e3value = Double.valueOf(entry3string);
String entry4string = entry4.getText();
Double e4value = Double.valueOf(entry4string);
String wmessage = "You selected ";
String wtitle = "Pop Up Box";
if (true) JOptionPane.showMessageDialog(null, wmessage, wtitle, JOptionPane.PLAIN_MESSAGE);
double distance = (Math.pow((e1value - e2value), 2) + Math.pow((e3value - e4value), 2));
DecimalFormat fmt = new DecimalFormat("####.##");
String outstring = fmt.format(distance);
output1.setText("");
output1.setText(outstring);
}//** actionPerformed
}); //** Action Listener
} //** D2 constructor
public static void main(String[] args)
{
D2 frame = new D2();
frame.setTitle("Distance Calculator");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
frame.setBackground(Color.CYAN);
frame.getContentPane().setBackground(Color.lightGray);
frame.setVisible(true);
} //** main
} //** class
Inserting print statements and setting the value of label1 to another value results in no change in the GUI. Any help?

During creation of output1 you wrote setEnabled(false);. Possibly you meant that output1 controll should be disabled. But instead of that you disabled the whole container, thus all elements are not editable\clickable. To fix the behaviour set this property directly to control:
output1 = new JTextField(8);
add(output1);
output1.setEnabled(false);
output1.setVisible(true);
Hope this will help.
P.S. It seems that you also need to improve calculation itself by adding Math.sqrt (if I understood your idea correctly):
double distance = Math.sqrt(Math.pow((e1value - e2value), 2) + Math.pow((e3value - e4value), 2));

#Mikita is right. You could also consider adding a JPanel in your JFrame or at least add all your components (JButtons, JTextfields etc) into the ContentPane of the JFrame.
See the Using Top-Level Containers tutorial and this FlowLayout sample.
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
getContentPane().add(label1);
entry1 = new JTextField(8);
getContentPane().add(entry1);
or
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
panel.add(label1);
entry1 = new JTextField(8);
panel.add(entry1);
getContentPane().add(panel);

Related

How do I get the textfields and the labels to sit in a 7x3 grid?

The first column in my grid always comes out right but then the rest begin replacing the other cells. Also the border layout does not seem to be functioning. I do not know what the problem is. It should have the title on top, a 7x3 grid in the center and the buttons on the bottom. Please help! Thank you!
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JPanel mainPanel,titlePanel, fieldPanel, buttonPanel;
private JLabel title, teams, totalP, wlt;
private JTextField team1, team2, team3, team4, team5, team6, total1, total2, total3, total4, total5, total6, wlt1, wlt2, wlt3, wlt4, wlt5, wlt6;
private JButton read, calc, champWin, earthCW, exit;
final private int WINDOW_HEIGHT = 400;
final private int WINDOW_WIDTH = 900;
public GUI(){
buildtitlePanel();
buildfieldPanel();
buildbuttonPanel();
buildmainPanel();
setTitle("Desert Soccer League");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buildmainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void buildtitlePanel() {
titlePanel = new JPanel();
title = new JLabel();
title.setText("2014 Desert Soccer League Totals");
titlePanel.add(title);
}
private void buildfieldPanel() {
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(7, 3));
teams = new JLabel();
teams.setText("Teams");
totalP = new JLabel();
totalP.setText("Total Points");
wlt = new JLabel();
wlt.setText("Win-Loss-Tie");
team1 = new JTextField(10);
team2 = new JTextField(10);
team3 = new JTextField(10);
team4 = new JTextField(10);
team5 = new JTextField(10);
team6 = new JTextField(10);
total1 = new JTextField(10);
total2 = new JTextField(10);
total3 = new JTextField(10);
total4 = new JTextField(10);
total5 = new JTextField(10);
total6 = new JTextField(10);
wlt1 = new JTextField(10);
wlt2 = new JTextField(10);
wlt3 = new JTextField(10);
wlt4 = new JTextField(10);
wlt5 = new JTextField(10);
wlt6 = new JTextField(10);
team1.setEditable(false);
team2.setEditable(false);
team3.setEditable(false);
team4.setEditable(false);
team5.setEditable(false);
team6.setEditable(false);
total1.setEditable(false);
total2.setEditable(false);
total3.setEditable(false);
total4.setEditable(false);
total5.setEditable(false);
total6.setEditable(false);
wlt1.setEditable(false);
wlt2.setEditable(false);
wlt3.setEditable(false);
wlt4.setEditable(false);
wlt5.setEditable(false);
wlt6.setEditable(false);
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
fieldPanel.add(totalP);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
fieldPanel.add(wlt);
fieldPanel.add(wlt1);
fieldPanel.add(wlt2);
fieldPanel.add(wlt3);
fieldPanel.add(wlt4);
fieldPanel.add(wlt5);
fieldPanel.add(wlt6);
}
private void buildbuttonPanel() {
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 5));
read = new JButton();
calc = new JButton();
champWin = new JButton();
earthCW = new JButton();
exit = new JButton();
read.setText("Read Input File");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
calc.setText("Calculate Points");
calc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
champWin.setText("Championship Winner");
champWin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
earthCW.setText("Earth Cup Winner");
earthCW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exit.setText("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonPanel.add(read);
buttonPanel.add(calc);
buttonPanel.add(champWin);
buttonPanel.add(earthCW);
buttonPanel.add(exit);
}
}
mainPanel = new JPanel();
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
By default a JPanel uses a FlowLayout. If you want to use a BorderLayout, then you need to set the layout on the panel:
mainPanel = new JPanel( new BorderLayout() );
The GridLayout fills out the rows first so the code should be:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
...
Also note that in your code you are adding the total? fields twice (which won't do anything), instead of the team? fields.
Another way to specify the grid is to just use:
fieldPanel.setLayout(new GridLayout(0, 3));
This tells the grid to add 3 components to each row then move on to the next row. This way you don't have to worry about the exact number of rows.
To add to camickr answer you're also adding the same total fields multiple times, so change this:
fieldPanel.add(teams);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
to
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
This is what is causing your display issue.
Your code should look like:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
fieldPanel.add(team2);
fieldPanel.add(total2);
fieldPanel.add(wlt2);
// etc.

Swing Number Format Exception

For some reason the AddListener class below doesn't work, and I keep getting a number format exception. Could anyone please tell me the reason for this. It seems to me as if it should work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculator extends JFrame {
JFrame theFrame = this;
JTextField addField; // Declaring this here so that you can access the variable from other places. MAKE SURE TO NOT DECLARE THIS AGAIN IN THE CONSTRUCTOR
JTextField totalField;
public BabyCalculator() {
//You set this up so that you can refer to the frame using the inner class below.
setDefaultCloseOperation(EXIT_ON_CLOSE);
setName("Baby Calculator");
setLayout(new GridLayout(3, 0));
//add
JLabel addLabel = new JLabel("Amount to add:");
addField = new JTextField(10);
JButton addButton = new JButton("add");
addButton.addActionListener(new AddListener());
//multiply
JLabel multiplyLabel = new JLabel("Amount to multiply:");
JTextField multiplyField = new JTextField(10);
JButton multiplyButton = new JButton("multiply");
//total
JLabel totalLabel = new JLabel("Total");
totalField = new JTextField(10);
totalField.setEditable(false);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
//Create Panels
JPanel topRow = new JPanel(new BorderLayout());
JPanel middleRow = new JPanel(new BorderLayout());
JPanel bottomRow = new JPanel(new FlowLayout());
//Add the top Row
topRow.add(addLabel, BorderLayout.WEST);
topRow.add(addField, BorderLayout.CENTER);
topRow.add(addButton, BorderLayout.EAST);
add(topRow);
middleRow.add(multiplyLabel, BorderLayout.WEST);
middleRow.add(multiplyField, BorderLayout.CENTER);
middleRow.add(multiplyButton, BorderLayout.EAST);
add(middleRow);
bottomRow.add(totalLabel);
bottomRow.add(totalField);
bottomRow.add(stopButton);
add(bottomRow);
pack();
setVisible(true);
}
public class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String addFieldText = addField.getText();
String totalFieldText = totalField.getText();
double addAmount = Double.parseDouble(addFieldText);
double total = Double.parseDouble(totalFieldText);
total += addAmount;
totalField.setText(total + "");
}
}
//end class AddListener
public class StopListener implements ActionListener {//this is an inner class
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(theFrame, "You Clicked the stop button");
}//end class StopListener
}
public static void main(String[] args) {
JFrame newFrame = new BabyCalculator();
}
}
Note: The problem in the code is definitely related to the AddListener. Whenever I click the add button in the GUI I get an exception.
The problem is with the totalFieldText, it's default value is blank, meaning that when you try and convert to a double value, it causes a NumberFormatException
Try giving it a default value of 0, for example
totalField = new JTextField("0", 10);
You might also like to take a look at How to Use Spinners and How to Use Formatted Text Fields which will make your life easier

JTextField Does not show up initially, only when clicking on it?

So this problem is really giving me a headache because for some reason last night when i was working on it, my code ran perfectly and my textfields would show up without a problem...
Go to bed, wake up, time to work on it again aaaaaand bam. Now my JtextFields only show up when i highlight them or click them or something...I was wondering what could be wrong?
My code is really just messy and crappy at this point while i figure out a better way to design my program...
I thought it was just eclipse but netbeans is giving me the same issue.
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.awt.*;
import javax.swing.border.*;
public class DiffuserCalc {
//create the class data fields
private double Qts;
private double Qes;
private double Vas;
JFrame ProgramBounds = new JFrame();
JLabel label1= new JLabel("Qts");
JLabel label2= new JLabel("Qes");
JLabel label3= new JLabel("Fs");
JLabel label4= new JLabel("BL");
JLabel label5= new JLabel("Xmax");
JLabel label6= new JLabel("Fs");
JLabel label7= new JLabel("Vas");
JLabel label8= new JLabel("Diameter");
JLabel label9= new JLabel("Pmax (RMS)");
JTextField QtsParam = new JTextField("Value");
JTextField QesParam = new JTextField("Value");
JTextField FsParam = new JTextField(" ");
JTextField BLParam = new JTextField(" ");
JTextField XmaxParam = new JTextField(" ");
Font myFont = new Font("Tahoma", Font.BOLD, 20);
DiffuserCalc()
{
ProgramBounds.setTitle("Box Designer");
JPanel ParameterMenu = new JPanel();
JPanel FieldInputs = new JPanel();
ParameterMenu.setBounds(30, 0, 1180, 120);
FieldInputs.setBounds(0,0, 1280, 720);
ProgramBounds.add(ParameterMenu);
ProgramBounds.add(FieldInputs);
ProgramBounds.setSize(1280,720);
// LAYOUT
ParameterMenu.setLayout(new FlowLayout(FlowLayout.CENTER, 60, 10));
FieldInputs.setLayout(null);
Border lineBdr = BorderFactory.createLineBorder(Color.BLACK);
Border BlackBorder = BorderFactory.createTitledBorder(lineBdr, " T/S Parameters ", TitledBorder.CENTER, TitledBorder.TOP, myFont, Color.black);
//FIELD PROPERTIES
label1.setFont(myFont);
label2.setFont(myFont);
label3.setFont(myFont);
label4.setFont(myFont);
label5.setFont(myFont);
label6.setFont(myFont);
label7.setFont(myFont);
label8.setFont(myFont);
label9.setFont(myFont);
// PARAMETER BOUNDS
int XLoc = 150;
int YLoc = 70;
QtsParam.setBounds(XLoc, YLoc, 40, 20);
QesParam.setBounds(XLoc+95, YLoc, 40, 20);
FsParam.setBounds(XLoc+190, YLoc, 40, 20);
// ADD FIELDS
ParameterMenu.add(label1);
ParameterMenu.add(label2);
ParameterMenu.add(label3);
ParameterMenu.add(label4);
ParameterMenu.add(label5);
ParameterMenu.add(label6);
ParameterMenu.add(label7);
ParameterMenu.add(label8);
ParameterMenu.add(label9);
ParameterMenu.setBorder(BlackBorder);
FieldInputs.add(QtsParam);
FieldInputs.add(QesParam);
FieldInputs.add(FsParam);
FieldInputs.add(BLParam);
FieldInputs.add(XmaxParam);
// set everything proper
QtsParam.requestFocus();
ParameterMenu.setVisible(true);
FieldInputs.setVisible(true);
ProgramBounds.setVisible(true);
}
public double BoxDimension(int x, int y)
{
return x;
}
public static void main(String[] args) {
DiffuserCalc MainProgram = new DiffuserCalc();
}
}
Your code only sets the bounds for 3 text fields but you add 5 text fields to the panel.
Don't use a null layout!!!
Use a proper layout manager and then you don't have to worry about making mistakes like this.
Also, follow Java naming conventions. Variable names do NOT start with an upper case character.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class DiffuserCalc {
//create the class data fields
private double qts;
private double qes;
private double vas;
private JFrame programBounds = new JFrame();
private JLabel label1= new JLabel("Qts");
private JLabel label2= new JLabel("Qes");
private JLabel label3= new JLabel("Fs");
private JLabel label4= new JLabel("BL");
private JLabel label5= new JLabel("Xmax");
private JLabel label6= new JLabel("Fs");
private JLabel label7= new JLabel("Vas");
private JLabel label8= new JLabel("Diameter");
private JLabel label9= new JLabel("Pmax (RMS)");
private JTextField qtsParam = new JTextField("Value");
private JTextField qesParam = new JTextField("Value");
private JTextField fsParam = new JTextField("");
private JTextField bLParam = new JTextField("");
private JTextField xmaxParam = new JTextField("");
private Font myFont = new Font("Tahoma", Font.BOLD, 20);
DiffuserCalc()
{
programBounds.setTitle("Box Designer");
JPanel parameterMenu = new JPanel();
JPanel labelPanel = new JPanel();
JPanel fieldInputs = new JPanel();
// LAYOUT
programBounds.setLayout(new BorderLayout());
parameterMenu.setLayout(new BorderLayout());
fieldInputs.setLayout(new FlowLayout(FlowLayout.LEFT));
fieldInputs.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
labelPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
programBounds.add(parameterMenu, BorderLayout.NORTH);
parameterMenu.add(labelPanel, BorderLayout.NORTH);
parameterMenu.add(fieldInputs, BorderLayout.SOUTH);
// programBounds.add(fieldInputs);
programBounds.setSize(1280,720);
Border lineBdr = BorderFactory.createLineBorder(Color.BLACK);
Border BlackBorder = BorderFactory.createTitledBorder(lineBdr, " T/S Parameters ", TitledBorder.CENTER, TitledBorder.TOP, myFont, Color.black);
//FIELD PROPERTIES
label1.setFont(myFont);
label2.setFont(myFont);
label3.setFont(myFont);
label4.setFont(myFont);
label5.setFont(myFont);
label6.setFont(myFont);
label7.setFont(myFont);
label8.setFont(myFont);
label9.setFont(myFont);
// ADD FIELDS
labelPanel.add(label1);
labelPanel.add(label2);
labelPanel.add(label3);
labelPanel.add(label4);
labelPanel.add(label5);
labelPanel.add(label6);
labelPanel.add(label7);
labelPanel.add(label8);
labelPanel.add(label9);
parameterMenu.setBorder(BlackBorder);
qtsParam.setColumns(3);
fieldInputs.add(qtsParam);
qesParam.setColumns(3);
fieldInputs.add(qesParam);
fsParam.setColumns(2);
fieldInputs.add(fsParam);
bLParam.setColumns(2);
fieldInputs.add(bLParam);
xmaxParam.setColumns(2);
fieldInputs.add(xmaxParam);
// set everything proper
qtsParam.requestFocus();
programBounds.pack();
programBounds.setVisible(true);
}
public double BoxDimension(int x, int y)
{
return x;
}
public static void main(String[] args) {
DiffuserCalc MainProgram = new DiffuserCalc();
}
}
So I rewrote the class for you to be more according to the Java style standard. Next not using a Layout manager is asking for trouble. And even though your requirements are like you say it's still better to put the effort to use a Layout manager as you'll keep running into problems like these. Read more about layout managers here. Furthermore don't call setVisible on JPanels that you added to a frame. When you call setVisible on the JFrame it will call setVisible on all of it child components.
Next call the method setColumns on the JTextField instead of initializing it with spaces for more consistent and predictable behaviour.

How do I force my text to be right justified in JTextFrame?

I'm trying to make my text fields to be right aligned, but I'm not quite sure how to make them right aligned in the JTextField. I read that you can make the Jtextfield right jusitified, but I just can't find the correct syntax.
currently, they're left justified.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class RecursivePowerCalculator extends JFrame {
//text fields for base, exponent, and power.
private JTextField jtfBase = new JTextField();
private JTextField jtfExponent = new JTextField();
private JTextField jtfPower = new JTextField();
//button to press called calcuate
private JButton jbtCalculate = new JButton("Calculate");
//constructor
public RecursivePowerCalculator(){
jtfPower.setEditable(false);
JPanel p1 = new JPanel(new GridLayout(3,2));
p1.add(new JLabel("Base"));
p1.add(jtfBase);
p1.add(new JLabel("Exponent"));
p1.add(jtfExponent);
p1.add(new JLabel("Power"));
p1.add(jtfPower);
JPanel p2 =new JPanel(new FlowLayout(FlowLayout.CENTER));
p2.add(jbtCalculate);
//add the panels to the frame
add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
jbtCalculate.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
//get values from text fields
double base = Double.parseDouble(jtfBase.getText());
double exponent = Double.parseDouble(jtfExponent.getText());
String pNum = "" + (power(base, exponent));
jtfPower.setText(pNum);
}
private double power(double x, double y){
if ( y == 0)
return 1.0;
else
return power(x,y - 1) * x;
}
}
}
Use jtfPower.setHorizontalAlignment(JTextField.RIGHT);
See javadoc.

JScrollPane in Jlist

hello goodevening to all i have a problem on my program with the ScrollPane in my JList i cant put an JScrollPane in my list because i am using a panel instead of Container this is my code so far its all runnable the problem is if you enter a high number in the number of times the some output will not be able to see because of the size of my list . so this is the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultCen extends JFrame implements ActionListener
{
public static void main(String args [])
{
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.setSize(300,450);
}
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JList list = new JList();
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen()
{
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
l.setBounds(10,10,130,30);
l1.setBounds(10,40,130,30);
t1.setBounds(140,10,130,25);
t2.setBounds(140,40,130,25);
b.setBounds(60,90,75,30);
c.setBounds(150,90,75,30);
list.setBounds(30,140,220,220);
panel.add(t1);
panel.add(t2);
panel.add(l);
panel.add(l1);
panel.add(list);
panel.add(b);
panel.add(c);
getContentPane().add(panel);
b.addActionListener(this);
c.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
int t3 = Integer.parseInt(t1.getText());
int t4 = Integer.parseInt(t2.getText());
m.addElement("The multiplication Table of "+t3);
for (int cc =1 ; cc <=t4; cc++ )
{
lab.setText(t3+"*"+cc+" = "+(t3*cc));
m.addElement(lab.getText());
list.setModel(m);
}
}
if(e.getSource() == c)
{
t1.setText("");
t2.setText("");
m.removeAllElements();
}
}
}
JScrollPane does not work with null Layout. Use BoxLayout or any other resizeable layout instead. This is the limitation of setLayout(null).
Use Layout managers. You've asked a lot of questions here and I'm sure a few you have been advised not to use null layout. Again here is the tutorial Laying out components Within a container. Learn to use them so you don't run into the million possible problems on the road ahead. This kind of problem being one of them.
here's an example of how you could achieve the same thing with layout managers, and some empty borders for white space.
With Layout Manager
Without Layout Manger
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MultCen extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.pack();
}
});
}
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen() {
JPanel topPanel = new JPanel(new GridLayout(2, 2, 0, 5));
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
topPanel.add(l);
topPanel.add(t1);
topPanel.add(l1);
topPanel.add(t2);
JPanel buttonPanel = new JPanel();
buttonPanel.add(b);
buttonPanel.add(c);
buttonPanel.setBorder(new EmptyBorder(10, 0, 10, 0));
JList list = new JList();
JScrollPane scroll = new JScrollPane(list);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(300, 300));
JPanel panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(buttonPanel, BorderLayout.CENTER);
panel.add(scroll, BorderLayout.SOUTH);
panel.setBorder(new EmptyBorder(10, 15, 10, 15));
getContentPane().add(panel);
}
}
Side Notes
Run Swing apps from the Event Dispatch Thread. See Initial Threads
When you do decide to use layout managers, just pack() your frame instead of setSize()
Use better variable names.
See Extends JFrame vs. creating it inside the the program

Categories