Why is my JFrame not showing? - java

I'm pretty sure I've done it this way before, but for some reason, the JFrame won't show up when I run it.
JLabel originalString = new JLabel("Original String: "
+ str.getMutator());
JLabel currentString = new JLabel("Current String: "
+ str.getMutator());
JLabel finalString = new JLabel("Final String: " + str.getTarget());
JPanel panel = new JPanel();
panel.add(originalString);
panel.add(currentString);
panel.add(finalString);
JFrame frame = new JFrame("Mutating String!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}

Try to set size or check with the preferred size of your components probably because you call pack().
frame.setSize(x, y);

Your problem must be somewhere else (is the method called does it throw an exception ?) because your code works (I commented the str calls) :
http://img217.imageshack.us/img217/902/screenvlg.png
import javax.swing.*;
public class Test{
public static void main(String... args){
JLabel originalString = new JLabel("Original String: " /*+ str.getMutator()*/);
JLabel currentString = new JLabel("Current String: "/* + str.getMutator()*/);
JLabel finalString = new JLabel("Final String: " /* + str.getTarget()*/);
JPanel panel = new JPanel();
panel.add(originalString);
panel.add(currentString);
panel.add(finalString);
JFrame frame = new JFrame("Mutating String!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

Related

My JButton wouldn't show if there's JTextArea

I have problem showing JButton when there's a JTextField.
I tried switching places of the JButton and JTextField like this:
From this:
TriangleSolution.add(SolutionTextArea);
TriangleSolution.add(SolutionExitButton);
To this:
TriangleSolution.add(SolutionExitButton);
TriangleSolution.add(SolutionTextArea);
But when I do that, the other components wouldn't show
Blockquote
Here's the code:
JScrollPane ScrollPane = new JScrollPane();
JTextArea SolutionTextArea;
TriangleSolution = new JFrame();
Base = ("Base = " +ValueOfBase.getText());
Height = ("Height =" + ValueOfHeight.getText());
String AreaOfTriangle = ("△ = Base * Height / 2");
SolutionTextArea = new JTextArea();
SolutionTextArea.setLineWrap(true);
SolutionTextArea.setBounds(0, 0, 400, 400);
SolutionTextArea.setWrapStyleWord(true);
SolutionTextArea.setEditable(false);
SolutionTextArea.setText(AreaOfTriangle + "\n" + "\n" + Base + "\n" + Height);
SolutionExitButton = new JButton("Exit");
SolutionExitButton.setBounds(500, 500, 100, 100);
SolutionExitButton.setFocusable(false);
SolutionExitButton.addActionListener(this);
TriangleSolution.add(SolutionExitButton);
TriangleSolution.add(SolutionTextArea);
TriangleSolution.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TriangleSolution.setVisible(true);
TriangleSolution.setResizable(false);
// TriangleSolution.setLocation(1200,100);
TriangleSolution.setSize(1000,1000);
TriangleSolution.setLayout(null);
Please help, I'm also learning this all by myself

can JTextField resizable in a gridlayout?

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.

Adding Components to Frame using Absolute Positioning

I am creating a simple Tic Tac Toe Application in Swing using setBounds (null Layout).
My problem is that whichever component i add in the end, is not visible in the frame, or distorts the complete GUI.
My code would better explain this
import java.awt.*;
import javax.swing.*;
class ZeroKata
{
ButtonGroup p1group,p2group;
Font f;
JButton begin,b1,b2,b3,b4,b5,b6,b7,b8,b9;
JCheckBox p1K,p2K,p1Z,p2Z;
JFrame frame;
JLabel player1,player2,p1Name,p2Name,p1Symbol,p2Symbol,status,dummy; // dummy label for my problem
JPanel buttons;
JTextField name1,name2;
private void addComponents(Container parent,JComponent...c)
{
for(JComponent C:c)
parent.add(C);
}
public ZeroKata()
{
frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setResizable(true);
frame.setVisible(true);
buttons = new JPanel();
buttons.setLayout(new GridLayout(3,3,10,10));
begin = new JButton("START GAME");
b1 = new JButton(" ");
b2 = new JButton(" ");
b3 = new JButton(" ");
b4 = new JButton(" ");
b5 = new JButton(" ");
b6 = new JButton(" ");
b7 = new JButton(" ");
b8 = new JButton(" ");
b9 = new JButton(" ");
p1K = new JCheckBox("X");
p1Z = new JCheckBox("O");
p2K = new JCheckBox("X");
p2Z = new JCheckBox("O");
p1group = new ButtonGroup();
p2group = new ButtonGroup();
p1group.add(p1K);
p1group.add(p1Z);
p2group.add(p2K);
p2group.add(p2Z);
name1 = new JTextField(30);
name2 = new JTextField(30);
f = new Font("Georgia",Font.PLAIN,38);
player1 = new JLabel (" << PLAYER 1 >>");
p1Name = new JLabel ("NAME : ");
p1Symbol = new JLabel ("SYMBOL : ");
player2 = new JLabel ("<< PLAYER 2 >>");
p2Name = new JLabel ("NAME : ");
p2Symbol = new JLabel ("SYMBOL : ");
status = new JLabel ("GAME STATUS -->> ");
dummy = new JLabel (" ");
addComponents(buttons,b1,b2,b3,b4,b5,b6,b7,b8,b9);
player1.setBounds(100,100,100,30);
p1Name.setBounds(120,150,100,30);
p1Symbol.setBounds(120,200,60,30);
player2.setBounds(100,250,100,30);
p2Name.setBounds(120,300,100,30);
p2Symbol.setBounds(120,350,50,30);
name1.setBounds(200,150,150,30);
p1K.setBounds(200,200,50,30);
p1Z.setBounds(250,200,50,30);
name2.setBounds(200,300,150,30);
p2K.setBounds(200,350,50,30);
p2Z.setBounds(250,350,50,30);
buttons.setBounds(500,100,250,250);
dummy.setBounds(20,20,30,30);
begin.setBounds(200,500,150,30);
frame.add(player1);
frame.add(p1Name);
frame.add(p1Symbol);
frame.add(player2);
frame.add(p2Name);
frame.add(p2Symbol);
frame.add(name1);
frame.add(name2);
frame.add(begin);
frame.add(buttons);
frame.add(p1K);
frame.add(p1Z);
frame.add(p2K);
frame.add(p2Z);
/* u need to add a dummy label also to let GUI work correctly, dont know whyx !
frame.add(dummy); */
}
public static void main(String...args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ZeroKata();
}
});
}
}
It is a simple code, I just don't know where I am going wrong .
Thanks in advance !
The default layout manager is a BorderLayout (see JFrame overview), set it to null to allow for absolute positioning:
frame.setLayout(null);
My problem is that whichever component i add in the end, is not
visible in the frame, or distorts the complete GUI. My code would
better explain this
you added JComponents to the already visible JFrame,
move frame.setVisible(true); as last code line, after all JComponents are added
Swing GUI should be started on Initial Threads

Unable to getText the value of string

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

Swing sample form application

I have come up with the below code:
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
JFrame frame = new JFrame("SpringDemo1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
for (int i = 0; i < numPairs; i++)
{
JLabel lable = new JLabel(labels[i]);
contentPane.add(lable);
contentPane.add(new JTextField(15));
}
//Display the window.
frame.pack();
frame.setVisible(true);
Expectation:
What I am getting:
Default:
when resized:
The result is noway related to how code actually/normally looks like!
I also tried copy pasting and running the ready-made code: downloaded from here:
and this is how the result looks :
To put the components in the right place using SpringLayout, you should use the ( SpringUtilities class ), download it then include it in your project.
your code should be:
private static void createAndShowGUI() {
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
//Create and populate the panel.
JPanel p = new JPanel(new SpringLayout());
for (int i = 0; i < numPairs; i++) {
JLabel l = new JLabel(labels[i], JLabel.TRAILING);
p.add(l);
JTextField textField = new JTextField(10);
l.setLabelFor(textField);
p.add(textField);
}
//Lay out the panel.
SpringUtilities.makeCompactGrid(p,
numPairs, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
//Create and set up the window.
JFrame frame = new JFrame("SpringForm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
p.setOpaque(true); //content panes must be opaque
frame.setContentPane(p);
//Display the window.
frame.pack();
frame.setVisible(true);
}
i hope that helps you!

Categories