My JButton wouldn't show if there's JTextArea - java

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

Related

How do I make a JButton hit the enter key when pressed?

So in my code, I have 2 JTextField inputs that need input for the rest of the program to work. Both of them contain variables that cannot be left empty for the rest of the program to work. The problem is that whenever you enter something into the text field, you have to press enter in the end and that process is not that straightforward in the program as you are not able to see whether or not you have already pressed enter without looking into the console.
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame2.setTitle("Multiplayer");
frame2.setVisible(true);
JLabel labelM = new JLabel("Geben sie eine Höhstzahl ein:");
JTextField hZahl = new JTextField();
JLabel labelN= new JLabel("Mit wie vielen Rateversuchen wollen sie spielen?");
JTextField rVers = new JTextField();
JButton b = new JButton("Submit");
Now I want the JButton b to press enter for both text field hZahl and rVers when pushed. How do I achieve that?
This is what button bdoes so far:
ActionListener buttonlistener3 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if((arr[0] > 0) && (arr[1] > 0)){
frame3.setTitle("1 Player Game");
frame3.setVisible(true);
JLabel labelB = new JLabel("Erraten sie die Zahl:");
JTextField rVers1 = new JTextField();
labelB.setBounds(50, 105, 400, 70);
rVers1.setBounds(45, 150, 100, 30);
frame3.add(labelB);
frame3.add(rVers1);
rVers1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("Rateversuch: " + rVers1.getText());
int r = Integer.parseInt(rVers1.getText());
arr[2] = r;
System.out.println("werte " + arr[1] +" " + arr[3] +" " + r);
if(arr[1] == 1){
JLabel lv = new JLabel("Letzer Versuch!");
lv.setBounds(50, 50, 400, 70);
lv.setForeground(Color.red);
frame4.add(lv);
}
tru = arr[3] == arr[2];
if(r < arr[3]){
labelB.setText("Die Gesuchte Zahl ist größer.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(r > arr[3]){
labelB.setText("Die Gesuchte Zahl ist kleiner.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(tru){
frame4.setVisible(true);
JLabel cor = new JLabel("Richtig!");
JLabel win = new JLabel("Sie haben Gewonnen");
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.red);
frame4.add(cor);
frame4.add(win);
}
System.out.println("werte neu " + arr[1] +" " + arr[3] +" " + r);
}
});
}
}
};
b.addActionListener(buttonlistener3);
}
};

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.

Outputting database data to a JTable

I've been trying to follow the information here and and the code here and I'm having some difficulty.
The database query works and I've outputted it successfully to console. Following the above guides I've since added some code that puts the ResultSet data into the required Vectors. This is my code:
public class Reports extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField dateFromYYYY;
private JTextField dateFromMM;
private JTextField dateFromDD;
private JTextField dateToYYYY;
private JTextField dateToMM;
private JTextField dateToDD;
private JTextField ownerNameInput;
private JTextField petNameInput;
private JTextField doctorNameInput;
private JCheckBox isPaid = new JCheckBox("Is Paid");
public static JTable table;
public static boolean printTable = true;
private String printHeader;
// Static Variables
private final static String BOOKINGS_TABLES = "FROM Doctor, Pet, Treatment, Visit ";
/**
* Create the frame.
*/
private void SearchFrame() {
setTitle("Generate a Report");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 981, 551);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblWhatWouldYou = new JLabel("What would you like a report for?");
lblWhatWouldYou.setBounds(36, 10, 200, 50);
contentPane.add(lblWhatWouldYou);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(260, 60, 690, 370);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
private void DateFields(){
// From Date
//Year
JLabel lblFromDate = new JLabel("From dd:");
lblFromDate.setBounds(20, 180, 165, 25);
contentPane.add(lblFromDate);
JLabel lblFromYear = new JLabel("yyyy:");
lblFromYear.setBounds(180, 180, 165, 25);
contentPane.add(lblFromYear);
dateFromYYYY = new JTextField();
dateFromYYYY.setBounds(210, 180, 40, 25);
contentPane.add(dateFromYYYY);
//Month
JLabel lblFromMonth = new JLabel("mm:");
lblFromMonth.setBounds(128, 180, 165, 25);
contentPane.add(lblFromMonth);
dateFromMM = new JTextField();
dateFromMM.setBounds(155, 180, 20, 25);
contentPane.add(dateFromMM);
dateFromDD = new JTextField();
dateFromDD.setBounds(100, 180, 20, 25);
contentPane.add(dateFromDD);
// To Date
//Year
JLabel lblToDate = new JLabel("To dd:");
lblToDate.setBounds(20, 210, 165, 25);
contentPane.add(lblToDate);
JLabel lblToYear = new JLabel("yyyy:");
lblToYear.setBounds(180, 210, 165, 25);
contentPane.add(lblToYear);
dateToYYYY = new JTextField();
dateToYYYY.setBounds(210, 210, 40, 25);
contentPane.add(dateToYYYY);
//Month
JLabel lblToMonth = new JLabel("mm:");
lblToMonth.setBounds(128, 210, 165, 25);
contentPane.add(lblToMonth);
dateToMM = new JTextField();
dateToMM.setBounds(155, 210, 20, 25);
contentPane.add(dateToMM);
dateToDD = new JTextField();
dateToDD.setBounds(100, 210, 20, 25);
contentPane.add(dateToDD);
}
private void PetName(){
JLabel lblPetName = new JLabel("Pet Name:");
lblPetName.setBounds(20, 90, 165, 25);
contentPane.add(lblPetName);
petNameInput = new JTextField();
petNameInput.setBounds(100, 90, 150, 25);
contentPane.add(petNameInput);
}
private void OwnerName(){
JLabel lblOwnerName = new JLabel("Owner Name:");
lblOwnerName.setBounds(20, 120, 165, 25);
contentPane.add(lblOwnerName);
ownerNameInput = new JTextField();
ownerNameInput.setBounds(100, 120, 150, 25);
contentPane.add(ownerNameInput);
}
private void DoctorName(){
JLabel lblDoctorName = new JLabel("Doctor Name:");
lblDoctorName.setBounds(20, 150, 165, 25);
contentPane.add(lblDoctorName);
doctorNameInput = new JTextField();
doctorNameInput.setBounds(100, 150, 150, 25);
contentPane.add(doctorNameInput);
}
private void IsPaidCheckBox(){
isPaid.setBounds(155, 250, 97, 25);
contentPane.add(isPaid);
}
public void Bookings() {
// Local variables
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
// Instantiate the frame
SearchFrame();
// Set search fields
PetName();
OwnerName();
DoctorName();
IsPaidCheckBox();
DateFields();
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String queryString00 = "";
String queryString01 = "SELECT pet.petname AS [Pet Name], pet.ownerName AS [Owner Name], doctor.doctorName AS [Doctor Name], visit.visitDate AS [Visit Date], treatment.treatmentName AS [Treatment Name], visit.ispaid AS [Is Paid] ";
String queryString03 = "WHERE Visit.petID = Pet.petID ";
String queryString02 = " GROUP BY visitID;";
// build the query
if(!(petNameInput.getText().equals("")))
queryString00 = queryString01 + BOOKINGS_TABLES + queryString03 + "AND petname LIKE " + "'%" + petNameInput.getText() + "%'";
else queryString00 = queryString01 + BOOKINGS_TABLES + queryString03;
if(!(ownerNameInput.getText().equals("")))
queryString00 = queryString00 + "AND ownername LIKE " + "'%" + ownerNameInput.getText() + "%'";
if(!(doctorNameInput.getText().equals("")))
queryString00 = queryString00 + "AND doctorname LIKE " + "'%" + doctorNameInput.getText() + "%'";
if(!(dateFromYYYY.getText().equals(""))){
String fromString = dateFromYYYY.getText() + "-" + dateFromMM.getText() + "-" + dateFromDD.getText();
queryString00 = queryString00 + " AND visitdate >= '" + fromString + "'";
}
if(!(dateToYYYY.getText().equals(""))){
String toString = dateToYYYY.getText() + "-" + dateToMM.getText() + "-" + dateToDD.getText();
queryString00 = queryString00 + " AND visitdate <= '" + toString + "'";
}
if(isPaid.isSelected())
queryString00 = queryString00 + " AND ispaid = 'Y'";
queryString00 = queryString00 + queryString02;
// System.out.println(queryString00);
DatabaseConnection db = new DatabaseConnection();
db.openConn();
// Get query
ResultSet rs = db.getSearch(queryString00);
ResultSetMetaData md = null;
// Set up vectors for table output
// Output query to screen (Much of the following code is adapted from http://www.camick.com/java/source/TableFromDatabase.java)
try{
md = rs.getMetaData();
int columnCount = md.getColumnCount();
// Get column names
for(int i = 1; i <= columnCount; i++)
columnNames.addElement(md.getColumnName(i));
while(rs.next()){
// System.out.printf("%-15s%-15s%-15s%-15s%-15s%-15s\n", rs.getString("Pet Name"), rs.getString("Owner Name"), rs.getString("Doctor Name"), rs.getString("Visit Date"), rs.getString("Treatment Name"), rs.getString("Is Paid"));
Vector<Object> row = new Vector<Object>(columnCount);
for(int i = 1; i <= columnCount; i++)
row.addElement(rs.getObject(i));
data.addElement(row);
}
}
catch (SQLException e) {
e.printStackTrace();
}
db.closeConn();
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
/**
*
*/
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
});
btnSearch.setBounds(36, 460, 165, 25);
contentPane.add(btnSearch);
JLabel resultLabel = new JLabel("Reports will be printed below");
resultLabel.setBounds(515, 10, 312, 50);
contentPane.add(resultLabel);
JButton printReport = new JButton("Print Report");
printReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String resultLabelPrint = resultLabel.getText();
MessageFormat footer = new MessageFormat(resultLabelPrint);
MessageFormat header = new MessageFormat(printHeader);
boolean complete =table.print(JTable.PrintMode.FIT_WIDTH, header , footer );
if (complete) {
/* show a success message */
} else {
/*show a message indicating that printing was cancelled */
}
} catch (PrinterException pe) {
/* Printing failed, report to the user */
}
}
});
printReport.setBounds(473, 460, 227, 25);
contentPane.add(printReport);
}
}
The final part of the code, which I believe out puts to the table, gives me some weird errors.
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
The first line gives me a syntax error on the semi-colon (;), specifically, Syntax error on token ";", invalid AssignmentOperator. I get the same when I try the 'model' variable.
When I uncomment the last two lines I get 'Syntax error on token ".", { expected' and the Eclipse demands another closing { despite there not being a corresponding opening }. If I add it then I get more errors.
I suspect this has something to do with the class structure of the code that I'm trying to follow but I'm having no luck in following those either.
All I want to do is to take the information that I have and output it in the table which is already there. How do I do this?
You're not showing all the error messages nor the complete error messages (please fix this). The most important one is the, Cannot refer to the non-final local variable data defined in an enclosing scope message. So make the variables final -- one problem solved.
public void Bookings() {
// Local variables
final Vector<Object> columnNames = new Vector<Object>(); //!! made final
final Vector<Object> data = new Vector<Object>();
The other problem is that this code:
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
Is being called outside of any and all methods. You need to match up your curly braces carefully.
Question that confuses me about your code though -- why create a TableModel and not use it as a model for your JTable?
scrollPane is not a global instance.
Move JScrollPane scrollPane out of your method SearchFrame() and place it into your list of instance variables for the class.
That is only your immediate and first issue, your other issue is that your are attempting to access instance variables defined in Reports within the scope of 2x nested anonymous classes.
You should parametarize your GUI methods to accept the components for injection into the panels.
public class Reports extends JFrame {
JScrollPane scrollPane;
...
private void SearchFrame() {
scrollPane = new JScrollPane ();
}
...
public void Bookings() {
scrollPane...
...
}
...
}

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!

Why is my JFrame not showing?

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);
}
}

Categories