Having issues with my weather data java program in eclipse - java

I am trying to get the code to calculate the windchill, but it is not working. I want the calculations to appear on a separate window when they are done.
In addition I need the program to have a separate error dialog box appear when invalid data is entered or when a wind chill is not valid, and the text in the GUI should reflect the issue. And the file entry button when selected, should display a file selection window. File opening errors will be handled with exceptions and dialog boxes. If the file is valid and opened successfully, the program will read in the data, compute the results, and display the data and results in columns in a separate window created through a separate class and Java file, and plot the Temperature and Wind Chill values.
Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.Scanner;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class WindChillCalculations extends JFrame {
private JPanel contentPane;
private static JTextField Fahrenheit_textField;
private static JTextField Mph_textField;
private static JTextField DewPoint_textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WindChillCalculations frame = new WindChillCalculations();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String fahrenheit = Fahrenheit_textField.getText();
String speed = Mph_textField.getText();
String dewpoint = DewPoint_textField.getText();
double t = Double.parseDouble(fahrenheit);
double v = Double.parseDouble(speed);
double d = Double.parseDouble(dewpoint);
//Calculate windchill
double w = 35.74 + (0.6215 * t) - (35.75 * (Math.pow(v,0.16))) + (0.4275 * (t * (Math.pow(v,0.16))));
//Format to keep the windchill to 2 digits after decimal
w = (int)(w*100)/100.0;
}
/**
* Create the frame.
*/
public WindChillCalculations() {
setTitle("Weather Data Program - Wind Chill Calculations");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 491, 383);
contentPane = new JPanel();
contentPane.setForeground(Color.WHITE);
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setToolTipText("");
panel.setBorder(new LineBorder(Color.WHITE));
panel.setForeground(Color.BLACK);
panel.setBackground(Color.BLACK);
panel.setBounds(2, 4, 470, 338);
contentPane.add(panel);
panel.setLayout(null);
JLabel WindChillCalculationsLabel = new JLabel("Wind Chill Calculations");
WindChillCalculationsLabel.setBounds(146, 6, 137, 15);
WindChillCalculationsLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
panel.add(WindChillCalculationsLabel);
WindChillCalculationsLabel.setForeground(Color.WHITE);
JLabel Fahrenheit_Label = new JLabel("Enter the temperature in degrees Fahrenheit:");
Fahrenheit_Label.setForeground(new Color(255, 140, 0));
Fahrenheit_Label.setBounds(10, 67, 305, 14);
panel.add(Fahrenheit_Label);
Fahrenheit_textField = new JTextField();
Fahrenheit_textField.setBounds(338, 64, 86, 20);
panel.add(Fahrenheit_textField);
Fahrenheit_textField.setHorizontalAlignment(JTextField.RIGHT);
Fahrenheit_textField.setColumns(10);
JLabel Mph_Label = new JLabel("Enter the wind speed in mph:");
Mph_Label.setForeground(new Color(255, 140, 0));
Mph_Label.setBounds(10, 123, 305, 14);
panel.add(Mph_Label);
Mph_textField = new JTextField();
Mph_textField.setColumns(10);
Mph_textField.setBounds(338, 120, 86, 20);
Mph_textField.setHorizontalAlignment(JTextField.RIGHT);
panel.add(Mph_textField);
JLabel DewPoint_Label = new JLabel("Enter the dew point in degrees Fahrenheit:");
DewPoint_Label.setForeground(new Color(255, 140, 0));
DewPoint_Label.setBounds(10, 177, 305, 14);
panel.add(DewPoint_Label);
DewPoint_textField = new JTextField();
DewPoint_textField.setColumns(10);
DewPoint_textField.setBounds(338, 174, 86, 20);
DewPoint_textField.setHorizontalAlignment(JTextField.RIGHT);
panel.add(DewPoint_textField);
JButton FileEntry_btn = new JButton("File Entry");
FileEntry_btn.setBackground(Color.BLACK);
FileEntry_btn.setForeground(new Color(255, 140, 0));
FileEntry_btn.setBounds(39, 283, 89, 23);
panel.add(FileEntry_btn);
JButton Compute_btn = new JButton("Compute");
Compute_btn.setForeground(new Color(255, 140, 0));
Compute_btn.setBackground(Color.BLACK);
Compute_btn.setBounds(301, 283, 89, 23);
panel.add(Compute_btn);
Compute_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
WeatherOutput output = new WeatherOutput();
output.setVisible(true);
}
});
}
}

I don't think this answer will satisfy the OP. I hope others will learn from it.
Here are the changes I made to the code.
I used a JFrame. I didn't extend a JFrame. You only extend a Swing component, or any Java class, when you want to override one of the class methods.
I created the GUI and gave the user a chance to type values before I calculated the wind speed.
I eliminated all absolute positioning and used Swing layout managers. I created a master JPanel and two subordinate JPanels, one to hold the labels and text fields, and the other to hold the buttons. The master panel used a BorderLayout, the labels and text fields panel used a GridBagLayout, and the buttons panel used a GridBagLayout so the buttons would expand horizontally to fill the area.
I used camelCase variable names in the code.
Here's the GUI result.
I formatted the code so it would be easier to see the methods and classes.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class WindChillCalculations {
private JPanel contentPane;
private JTextField fahrenheit_textField;
private JTextField mph_textField;
private JTextField dewPoint_textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new WindChillCalculations();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WindChillCalculations() {
// top, left, bottom, right
Insets topInsets = new Insets(10, 10, 10, 10);
Insets topRightInsets = new Insets(10, 0, 10, 10);
Insets insets = new Insets(0, 10, 10, 10);
Insets rightInsets = new Insets(0, 0, 10, 10);
Color textColor = new Color(255, 140, 0);
JFrame frame = new JFrame();
frame.setTitle("Weather Data Program - "
+ "Wind Chill Calculations");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setForeground(Color.WHITE);
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout());
JLabel windChillCalculationsLabel = new JLabel(
"Wind Chill Calculations");
windChillCalculationsLabel.setFont(new Font(
"Tahoma", Font.BOLD, 12));
windChillCalculationsLabel.setForeground(Color.WHITE);
windChillCalculationsLabel.setHorizontalAlignment(
JLabel.CENTER);
contentPane.add(windChillCalculationsLabel,
BorderLayout.BEFORE_FIRST_LINE);
JPanel panel = new JPanel();
panel.setToolTipText("");
panel.setBorder(new LineBorder(Color.WHITE));
panel.setForeground(Color.BLACK);
panel.setBackground(Color.BLACK);
panel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel fahrenheit_Label = new JLabel("Enter the "
+ "temperature in degrees Fahrenheit:");
fahrenheit_Label.setForeground(textColor);
addComponent(panel, fahrenheit_Label, 0, gridy, 1, 1,
topInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
fahrenheit_textField = new JTextField(15);
fahrenheit_textField.setHorizontalAlignment(
JTextField.RIGHT);
addComponent(panel, fahrenheit_textField, 1, gridy++, 1, 1,
topRightInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JLabel mph_Label = new JLabel("Enter the wind "
+ "speed in mph:");
mph_Label.setForeground(textColor);
addComponent(panel, mph_Label, 0, gridy, 1, 1,
insets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
mph_textField = new JTextField(15);
mph_textField.setHorizontalAlignment(JTextField.RIGHT);
addComponent(panel, mph_textField, 1, gridy++, 1, 1,
rightInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JLabel dewPoint_Label = new JLabel("Enter the "
+ "dew point in degrees Fahrenheit:");
dewPoint_Label.setForeground(textColor);
addComponent(panel, dewPoint_Label, 0, gridy, 1, 1,
insets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
dewPoint_textField = new JTextField(15);
dewPoint_textField.setHorizontalAlignment(
JTextField.RIGHT);
addComponent(panel, dewPoint_textField, 1, gridy++, 1, 1,
rightInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
contentPane.add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.BLACK);
buttonPanel.setForeground(Color.BLACK);
buttonPanel.setLayout(new GridBagLayout());
JButton fileEntry_btn = new JButton("File Entry");
fileEntry_btn.setBackground(Color.BLACK);
fileEntry_btn.setForeground(textColor);
addComponent(buttonPanel, fileEntry_btn, 0, 0, 1, 1,
topInsets, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL);
JButton compute_btn = new JButton("Compute");
compute_btn.setForeground(textColor);
compute_btn.setBackground(Color.BLACK);
compute_btn.setBounds(301, 283, 89, 23);
addComponent(buttonPanel, compute_btn, 1, 0, 1, 1,
topRightInsets, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL);
compute_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String fahrenheit = fahrenheit_textField.getText();
String speed = mph_textField.getText();
String dewpoint = dewPoint_textField.getText();
try {
double f = Double.valueOf(fahrenheit);
double s = Double.valueOf(speed);
double d = Double.valueOf(dewpoint);
WindChill windChill = new WindChill(f, s, d);
double answer = windChill.calculateWindChill();
//TODO Create output display
System.out.println(answer);
} catch (NumberFormatException e1) {
e1.printStackTrace();
}
}
});
contentPane.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
frame.add(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComponent(Container container,
Component component, int gridx, int gridy,
int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(
gridx, gridy, gridwidth, gridheight,
1.0, 1.0, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
public class WindChill {
private final double temperature;
private final double windSpeed;
private final double dewPoint;
public WindChill(double temperature, double windSpeed,
double dewPoint) {
this.temperature = temperature;
this.windSpeed = windSpeed;
this.dewPoint = dewPoint;
}
public double calculateWindChill() {
double factor = Math.pow(windSpeed, 0.16);
return 35.74d + (0.6215d * temperature) -
(35.75d * (factor)) +
(0.4275 * (dewPoint * (factor)));
}
}
}

Related

Java JTable column header not showing using DefaultModel

Like the title said, the hearder name is just not showing up. i tried many options like using a JScrollPane. and fallowed many guide on this forum but no help. I really wanted to get resolve problem by myself but i have tried everything and out of option.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.ScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
public class Adminpage extends JPanel {
private JFrame frame;
static String ID[]={"name","Username","Password"};
static DefaultTableModel model;
private JTextField NametextField;
private JTextField UsertextField;
private JTextField PasstextField;
private JTable table;
private JScrollPane scroll;
/**
* Create the panel.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 497, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblAdminstratorPortal = new JLabel("Adminstrator Portal");
lblAdminstratorPortal.setFont(new Font("Tahoma", Font.BOLD, 20));
lblAdminstratorPortal.setBounds(109, 26, 218, 25);
frame.getContentPane().add(lblAdminstratorPortal);
JButton btnNewButton = new JButton("Add Librarian");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//model= (DefaultTableModel)table.getModel();
//model.addColumn("name");
//model.addColumn("Username");
//model.addColumn("Password");
model.addRow(new Object[]{NametextField.getText(),UsertextField.getText(),PasstextField.getText()});
}
});
btnNewButton.setBounds(10, 62, 108, 35);
frame.getContentPane().add(btnNewButton);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(130, 62, 108, 35);
frame.getContentPane().add(btnDelete);
JButton btnViewLibrarian = new JButton("View Librarian");
btnViewLibrarian.setBounds(245, 62, 108, 35);
frame.getContentPane().add(btnViewLibrarian);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnLogout.setBounds(363, 62, 108, 35);
frame.getContentPane().add(btnLogout);
//model= (DefaultTableModel)table.getModel();
JLabel lblName = new JLabel("Name");
lblName.setBounds(21, 144, 60, 14);
frame.getContentPane().add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(21, 195, 60, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(21, 250, 60, 14);
frame.getContentPane().add(lblPassword);
NametextField = new JTextField();
NametextField.setBounds(119, 141, 119, 20);
frame.getContentPane().add(NametextField);
NametextField.setColumns(10);
UsertextField = new JTextField();
UsertextField.setColumns(10);
UsertextField.setBounds(119, 192, 119, 20);
frame.getContentPane().add(UsertextField);
PasstextField = new JTextField();
PasstextField.setColumns(10);
PasstextField.setBounds(119, 247, 119, 20);
frame.getContentPane().add(PasstextField);
table = new JTable();
table.setBounds(10, 304, 461, 189);
frame.getContentPane().add(table);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Adminpage() {
database();
setLayout(null);
initialize();
model= (DefaultTableModel)table.getModel();
model.addColumn("name");
model.addColumn("Username");
model.addColumn("Password");
}
public void database(){
try {
Class.forName("sun.jdbc.odbc.JdbsOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Games");
Statement st = con.createStatement();
String getquery = ("Select* from Games");
ResultSet rs= st.executeQuery(getquery);
while(rs.next()){
System.out.println(rs.getString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
You're adding the JTable directly to the GUI. Instead, yes you need to embed the JTable into the viewport of a JScrollPane and then add the JScrollPane to the GUI.
For example:
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
// table.setBounds(10, 304, 461, 189);
scrollPane.setBounds(10, 304, 461, 189); // This is bad, but will leave for now
// frame.getContentPane().add(table);
frame.getContentPane().add(scrollPane);
Also, you're harming your GUI by using null layouts and absolute positioning, as this can interfere with a component's ability to show itself fully and correctly, to achieve its own preferred size. Much better is to learn and use the layout managers.
For instance, when I run your program on my platform, I see:
Note how the buttons do not show their full texts due to their not being allowed to achieve their preferred sizes.
For example, using BoxLayout with some nested JPanels, one using GridLayout(1, 0, 5, 0) for one row, variable number of columns, and a 5 point horizontal gap between components, and another nested JPanel using GridBagLayout, for placement of JTextFields and JLabels, and some "wrapper" JPanels using default FlowLayout to center components within them...
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AdminPage2 extends JPanel {
private static final long serialVersionUID = 1L;
public static final String TITLE = "Administrator Portal";
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 20);
private static final String[] COL_NAMES = {"Name", "User Name", "Password"};
private int txtFieldCols = 20;
private JTextField nameField = new JTextField(txtFieldCols);
private JTextField userNameField = new JTextField(txtFieldCols);
private JPasswordField passwordField = new JPasswordField(txtFieldCols);
private DefaultTableModel tableModel = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(tableModel);
private JScrollPane tableScrollPane = new JScrollPane(table);
public AdminPage2() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(TITLE_FONT);
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
// of course you'd add ActionListeners or Actions to your buttons
buttonPanel.add(new JButton("Add Library"));
buttonPanel.add(new JButton("Delete"));
buttonPanel.add(new JButton("View Library"));
buttonPanel.add(new JButton("Logout"));
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
JPanel wrapTfPanel = new JPanel();
wrapTfPanel.add(textFieldPanel);
Dimension scrollPanePrefSz = tableScrollPane.getPreferredSize();
int w = scrollPanePrefSz.width;
int h = scrollPanePrefSz.height / 2;
scrollPanePrefSz = new Dimension(w, h);
tableScrollPane.setPreferredSize(scrollPanePrefSz);
// put together main JPanel components
int ebGap = 4;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(Box.createVerticalStrut(5));
add(titlePanel);
add(Box.createVerticalStrut(5));
add(buttonPanel);
add(Box.createVerticalStrut(5));
add(wrapTfPanel);
add(Box.createVerticalStrut(5));
add(tableScrollPane);
}
// create constraints to use when adding component to GridBagLayout
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
int in = 10;
int leftIn = x == 0 ? 4 * in : in;
gbc.insets = new Insets(in, leftIn, in, in);
return gbc;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
AdminPage2 mainPanel = new AdminPage2();
JFrame frame = new JFrame("Administrator Page");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Which displays as:
Regarding your questions:
but new question why give the scrollpane a bound instead of the table itself
The JScrollPane holds the JTable within it, and so if you use null layouts (which you shouldn't), and you're adding this JTable-containing JScrollPane to the GUI, you must set its bounds. Much better though is to use layout managers as I've outlined above. It makes it much easier to modify the GUI later and to debug it now.
and why adding the scrollpane into the panel instead of the table.
Because that's how JScrollPanes work. They don't add scrollbars to a component but rather nest the component itself, here the JTable, within the JScrollPane's viewport. Please read the JScrollPane Tutorial (see link) to see the details on this.
A further note on the power of layout managers. Say you want to add a new JLabel / JTextField combination, one that accepts a password hint, and say the JTextField's name is passwordHint. If you were using null layouts and absolute positioning, you'd have to set the bounds of your new JLabel and JTextField, but you'd also have to change the bounds of all components below and to the right of it, and would have to re-set the size of the GUI manually. If your GUI is very complex, this can lead to bugs and a lot of frustration.
If you used the layout managers above however, all you'd need to do would be to add two lines of code to the textFieldPanel JPanel creational code as shown below with the obvious comments:
// original textFieldPanel creational code
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
// !! ****** these lines added ******
textFieldPanel.add(new JLabel("Password Hint:"), createGbc(0, 3));
textFieldPanel.add(passwordHint, createGbc(1, 3));
This results in a perfect placement of the new components without adversely affecting the old:

CardLayout not rendering properly on windows

I've been working on a login screen for a new project and came across a weird rendering "error" while using CardLayout on windows.
SignUp screen on Mac:SignUp Screen Mac
The screens load up correctly on my Mac computer, but on windows they look like these after you click "Register" or after you click "Back".
The same screens on windows:SignUp Screen Windows
As you can see, on windows the SignUp "card" from the CardLayout is rendered over the Login "card" without hiding the other one and vise versa, not like on mac.
Now my question is, could this be caused because of the transparent background and therefore windows thinks that the one behind should still be visible, or could it be creating a brand new "card" each time i switch, or just be forgetting to hide the one in the back all together?
Why does this work on Mac but not on Windows?
And also, how could i go about fixing this?
I will put the whole Class so you can test it for yourself.
(Side note: you may also notice that the button "Register" shows the white button shape on windows even though it has btnRegister.setBorder(null); set (works on Mac))
The complete one Class code:
package testing;
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;
import utilities.ComponentMover;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;
import javax.swing.JSeparator;
import javax.swing.JPasswordField;
#SuppressWarnings("serial")
public class ClientStarter extends JFrame implements ActionListener {
JPanel cards;
private int height = 450;
private int width = 700;
private int trasparancy = 90;
private int labelWidth = 400;
final static String BACK = "Back";
final static String REGISTER = "Register";
private Color textLine = Color.GRAY;
private Color textColor = Color.WHITE;
private Color tipColor = Color.GRAY;
private Color disabledTipColor = new Color(90, 90, 90);
// LOGIN //
JPanel loginCard;
public static JTextField usernameIn = new JTextField();
private JLabel userLabel = new JLabel("Username :");
public static JPasswordField passwordIn = new JPasswordField();
private JLabel passLabel = new JLabel("Password :");
private JButton btnLogin = new JButton("Login");
private JButton btnRegister = new JButton(REGISTER);
private JLabel registerLabel = new JLabel("Don't own an Account? ");
private JSeparator separatorUser = new JSeparator();
private JSeparator separatorPass = new JSeparator();
// SIGNUP //
JPanel joinCard;
public static JTextField emailNew = new JTextField();
public static JLabel newEmailLabel = new JLabel("Email : (Not Available)");
public static JTextField usernameNew = new JTextField();
public static JLabel newUserLabel = new JLabel("Username :");
public static JTextField passwordNew = new JTextField();
public static JLabel newPassLabel = new JLabel("Password :");
public static JTextField passwordNew2 = new JTextField();
public static JLabel newPassLabel2 = new JLabel("Re-enter password :");
private JButton btnSignUp = new JButton("Signup");
private JButton btnBack = new JButton(BACK);
private JSeparator separatorMailNew = new JSeparator();
private JSeparator separatorUserNew = new JSeparator();
private JSeparator separatorPassNew = new JSeparator();
private JSeparator separatorPassNew2 = new JSeparator();
public ClientStarter() {
getContentPane().setBackground(Color.GRAY);
setUndecorated(true);
setBackground(new Color(0, 0, 0, trasparancy));
setTitle("EnChant");
setSize(width, height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
//Create the cards
// LOGIN //
Font avenir = new Font("Avenir", Font.PLAIN, 18);
loginCard = new JPanel();
loginCard.setLayout(null);
usernameIn.setBounds(348, 150, 327, 35);
usernameIn.setColumns(10);
usernameIn.setFont(avenir);
usernameIn.setBorder(null);
passwordIn.setBounds(348, usernameIn.getY() + 74, 327, 35);
passwordIn.setColumns(10);
passwordIn.setFont(avenir);
passwordIn.setBorder(null);
userLabel.setBounds(usernameIn.getX(), usernameIn.getY() - 20, labelWidth, 16);
userLabel.setFont(avenir);
passLabel.setBounds(passwordIn.getX(), passwordIn.getY() - 20, labelWidth, 16);
passLabel.setFont(avenir);
btnLogin.setBounds(348, passwordIn.getY() + 81, 327, 45);
btnLogin.addActionListener(this);
registerLabel.setBounds(btnLogin.getX(), btnLogin.getY() + btnLogin.getHeight() + 5, labelWidth, 16);
registerLabel.setFont(new Font("Avenir", Font.PLAIN, 13));
btnRegister.setBounds(btnLogin.getX() + 130, registerLabel.getY() - 1, 70, 16);
btnRegister.addActionListener(this);
btnRegister.setBorder(null);
loginCard.setBackground(new Color(0, 0, 0, trasparancy));
usernameIn.setBackground(new Color(0, 0, 0, 0));
usernameIn.setForeground(textColor);
passwordIn.setBackground(new Color(0, 0, 0, 0));
passwordIn.setForeground(textColor);
userLabel.setForeground(tipColor);
passLabel.setForeground(tipColor);
btnLogin.setForeground(new Color(70, 130, 180));
btnLogin.setBackground(Color.WHITE);
btnRegister.setForeground(new Color(70, 130, 180));
registerLabel.setForeground(tipColor);
separatorUser.setForeground(textLine);
separatorUser.setBounds(usernameIn.getX(), usernameIn.getY()+usernameIn.getHeight()-8, usernameIn.getWidth(), 6);
separatorPass.setForeground(textLine);
separatorPass.setBounds(passwordIn.getX(), passwordIn.getY()+passwordIn.getHeight()-8, passwordIn.getWidth(), 6);
loginCard.add(usernameIn);
loginCard.add(separatorUser);
loginCard.add(userLabel);
loginCard.add(passwordIn);
loginCard.add(separatorPass);
loginCard.add(passLabel);
loginCard.add(btnLogin);
loginCard.add(btnRegister);
loginCard.add(registerLabel);
// SIGNUP //
joinCard = new JPanel();
joinCard.setLayout(null);
emailNew.setBounds(348, 62, 327, 35);
emailNew.setColumns(10);
emailNew.setFont(avenir);
emailNew.setBorder(null);
emailNew.setEditable(false);
usernameNew.setBounds(348, emailNew.getY() + 74, 327, 35);
usernameNew.setColumns(10);
usernameNew.setFont(avenir);
usernameNew.setBorder(null);
passwordNew.setBounds(348, usernameNew.getY() + 74, 327, 35);
passwordNew.setColumns(10);
passwordNew.setFont(avenir);
passwordNew.setBorder(null);
passwordNew2.setBounds(348, passwordNew.getY() + 74, 327, 35);
passwordNew2.setColumns(10);
passwordNew2.setFont(avenir);
passwordNew2.setBorder(null);
//32, 106, 180, 254 : 2, 76, 150, 224
newEmailLabel.setBounds(emailNew.getX(), emailNew.getY() - 20, labelWidth, 16);
newEmailLabel.setFont(avenir);
newUserLabel.setBounds(usernameNew.getX(), usernameNew.getY() - 20, labelWidth, 16);
newUserLabel.setFont(avenir);
newPassLabel.setBounds(passwordNew.getX(), passwordNew.getY() - 20, labelWidth, 16);
newPassLabel.setFont(avenir);
newPassLabel2.setBounds(passwordNew2.getX(), passwordNew2.getY() - 20, labelWidth, 16);
newPassLabel2.setFont(avenir);
btnSignUp.setBounds(348, passwordNew2.getY() + 71, 327, 45); //335 // +81
btnSignUp.addActionListener(this);
btnBack.setBounds(btnSignUp.getX()-70, btnSignUp.getY(), 70, 45); //380
btnBack.addActionListener(this);
joinCard.setBackground(new Color(0, 0, 0, trasparancy));
emailNew.setBackground(new Color(0, 0, 0, 0));
emailNew.setForeground(textColor);
usernameNew.setBackground(new Color(0, 0, 0, 0));
usernameNew.setForeground(textColor);
passwordNew.setBackground(new Color(0, 0, 0, 0));
passwordNew.setForeground(textColor);
passwordNew2.setBackground(new Color(0, 0, 0, 0));
passwordNew2.setForeground(textColor);
newEmailLabel.setForeground(disabledTipColor);
newUserLabel.setForeground(tipColor);
newPassLabel.setForeground(tipColor);
newPassLabel2.setForeground(tipColor);
btnSignUp.setForeground(new Color(70, 130, 180));
btnBack.setBackground(Color.WHITE);
separatorMailNew.setBounds(emailNew.getX(), emailNew.getY()+emailNew.getHeight()-8, emailNew.getWidth(), 6);
separatorMailNew.setForeground(textLine);
separatorUserNew.setBounds(usernameNew.getX(), usernameNew.getY()+usernameNew.getHeight()-8, usernameNew.getWidth(), 6);
separatorUserNew.setForeground(textLine);
separatorPassNew.setBounds(passwordNew.getX(), passwordNew.getY()+passwordNew.getHeight()-8, passwordNew.getWidth(), 6);
separatorPassNew.setForeground(textLine);
separatorPassNew2.setBounds(passwordNew2.getX(), passwordNew2.getY()+passwordNew2.getHeight()-8, passwordNew2.getWidth(), 6);
separatorPassNew2.setForeground(textLine);
joinCard.add(emailNew);
joinCard.add(newEmailLabel);
joinCard.add(usernameNew);
joinCard.add(newUserLabel);
joinCard.add(passwordNew);
joinCard.add(newPassLabel);
joinCard.add(passwordNew2);
joinCard.add(newPassLabel2);
joinCard.add(btnSignUp);
joinCard.add(btnBack);
joinCard.add(separatorMailNew);
joinCard.add(separatorUserNew);
joinCard.add(separatorPassNew);
joinCard.add(separatorPassNew2);
// End //
JPanel whiteRectLogin = new JPanel();
whiteRectLogin.setBackground( Color.WHITE );
whiteRectLogin.setBounds(0, 0, 250, height);
loginCard.add(whiteRectLogin);
JPanel whiteRectJoin = new JPanel();
whiteRectJoin.setBackground( Color.WHITE );
whiteRectJoin.setBounds(0, 0, 250, height);
joinCard.add(whiteRectJoin);
cards = new JPanel(new CardLayout());
cards.setBackground(new Color(0, 0, 0, trasparancy));
cards.add(loginCard, BACK);
cards.add(joinCard, REGISTER);
getContentPane().add(cards);
//Top, Left, bottom, right
ComponentMover cm = new ComponentMover(this, this);
cm.setEdgeInsets(new Insets(-50, 1, 0, -50));
validate();
repaint();
getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRegister) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, REGISTER);
loginCard.setVisible(false);
}
if(e.getSource() == btnBack) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, BACK);
loginCard.setVisible(false);
}
if(e.getSource() == btnSignUp) {
//new SignUpCheck();
}
}
public static void main(String[] args) {
new ClientStarter();
}
}
could this be caused because of the transparent background
Probably. Swing does not renderer transparent backgrounds correctly. Swing expects a component to be either fully opaque or fully transparent.
Check out Backgrounds With Transparency for a complete description of the problem and a couple of solutions.
You can either do custom painting of every component with code something like:
JPanel panel = new JPanel()
{
protected void paintComponent(Graphics g)
{
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
panel.setOpaque(false); // background of parent will be painted first
panel.setBackground( new Color(255, 0, 0, 20) );
frame.add(panel);
Or you can use the AlphaContainer class to do the painting for you.
Also, you have several other problems:
Don't use static variables for your Swing components. That is no the proper usage of the static keyword.
Don't use a null layout and setBounds(). Swing was designed to be used with layout managers. Layout managers work well on multiple platforms.
Don't use an alpha value of 0. The 0 means fully transparent, so just use the setOpaque(false) method on the component.
Don't keep creating new Color objects. The same Color object can be used for every component. It save resources and makes it easier to change all Color for all components all at once.
Don't use validate() and repaint() in the constructor of your class. All the components should be added to the frame BEFORE you invoke setVisible(true) so those methods are not required.

JLabel and JButton

Basiclly I got 2 calsses, SSPUserInput and SSPViewer.
I want to press a button in SSPUserInput class and change a JLabel name in SSPViewer. It's basically a rock paper scissor game. This is my first time posting here, I'm sorry if I've done something wrong.
package p3;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SSPUserInput extends JPanel implements ActionListener {
private JPanel panel = new JPanel();
private JButton btnRock = new JButton ("Rock");
private JButton btnScissor = new JButton ("Scissor");
private JButton btnPaper = new JButton ("Paper");
private JButton btnNewGame = new JButton ("New game");
private JButton btnQuit = new JButton ("Quit");
private Font plainSS14 = new Font("SansSerif", Font.PLAIN, 14);
private SSPViewer lblHumanChoice;
private String rock;
private int scissor;
private int paper;
public SSPUserInput(SSPViewer lblHumanChoice) {
this.lblHumanChoice = lblHumanChoice;
}
public SSPUserInput(){
setPreferredSize (new Dimension(400, 200));
setLayout( null);
btnRock.setBounds(20, 50, 100, 35);
btnRock.setFont(plainSS14);
btnRock.addActionListener(this);
btnScissor.setBounds(155, 50, 100, 35);
btnScissor.setFont(plainSS14);
btnScissor.addActionListener(this);
btnPaper.setBounds(290, 50, 100, 35);
btnPaper.setFont(plainSS14);
btnPaper.addActionListener(this);
btnNewGame.setBounds(20, 100, 370, 35);
btnNewGame.setFont(plainSS14);
btnNewGame.addActionListener(this);
btnQuit.setBounds(20, 150, 370, 35);
btnQuit.setFont(plainSS14);
btnQuit.addActionListener(this);
add(btnRock);
add(btnScissor);
add(btnPaper);
add(btnNewGame);
add(btnQuit);
}
// public String getRock() {
// return rock;
// }
public void actionPerformed(ActionEvent e) {
if( e.getSource() == btnRock ) {
JOptionPane.showMessageDialog(null, "Hello world!");
}
else if( e.getSource() == btnScissor){
}
else if( e.getSource() == btnPaper){
}
else if( e.getSource() == btnNewGame){
}
}
}
package p3;
import java.awt.*;
import javax.swing.*;
public class SSPViewer extends JPanel {
private JLabel lblFirst = new JLabel("First to 3!");
private JLabel lblHuman = new JLabel("Human");
private JLabel lblComputer = new JLabel("Computer");
private JLabel lblHumanChoice = new JLabel();
private JLabel lblComputerChoice = new JLabel();
private JLabel lblHumanPoints = new JLabel("0");
private JLabel lblComputerPoints = new JLabel("0");
private SSPUserInput rock;
private SSPUserInput scissor;
private SSPUserInput paper;
public SSPViewer(SSPUserInput rock, SSPUserInput scissor, SSPUserInput paper) {
this.rock = rock;
this.scissor = scissor;
this.paper = paper;
}
public SSPViewer() {
setLayout(null);
setPreferredSize(new Dimension(400, 200));
lblFirst.setBounds(140, 10, 210, 24);
lblFirst.setFont(new Font("Arial", 2, 24));
lblHuman.setBounds(100, 75, 210, 17);
lblHuman.setFont(new Font("Arial", 2, 17));
lblComputer.setBounds(250, 75, 210, 17);
lblComputer.setFont(new Font("Arial", 2, 17));
lblHumanPoints.setBounds(120, 95, 210, 17);
lblHumanPoints.setFont(new Font("Arial", 2, 17));
lblComputerPoints.setBounds(280, 95, 210, 17);
lblComputerPoints.setFont(new Font("Arial", 2, 17));
lblHumanChoice.setBounds(100, 115, 210, 17);
lblHumanChoice.setFont(new Font("Arial", 2, 17));
// lblHuman.setText(rock.getRock());
lblComputerChoice.setBounds(260, 115, 210, 17);
lblComputerChoice.setFont(new Font("Arial", 2, 17));
add(lblFirst);
add(lblHuman);
add(lblComputer);
add(lblHumanPoints);
add(lblComputerPoints);
add(lblHumanChoice);
add(lblComputerChoice);
}
public JLabel getLblHumanChoice() {
return lblHumanChoice;
}
}
package p3;
import javax.swing.*;
public class SSPApp {
public static void main( String[] args ) {
SSPPlayer player = new SSPPlayer();
SSPViewer viewer = new SSPViewer();
SSPController controller = new SSPController();
SSPUserInput userInput = new SSPUserInput();
JFrame frame1 = new JFrame( "SSPViewer" );
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.add( viewer );
frame1.pack();
frame1.setVisible( true );
JFrame frame2 = new JFrame( "SSPUserInput" );
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.add( userInput );
frame2.pack();
frame2.setVisible( true );
}
}
Basically you need to hold a reference to the 'view' on the 'userInput'. And you already have it.
public ExampleFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridLayout(2, 1));
setContentPane(contentPane);
// create a view
SSPViewer sspViewer = new SSPViewer();
contentPane.add(sspViewer);
// pass a reference to the userInput
contentPane.add(new SSPUserInput(sspViewer));
}
on the viewer class, you need to add a method to access the local private components, for example im going to change a text of JLabel :
public class SSPViewer extends JPanel {
// code ...
// setter. lblHuman is a reference here in that class
// to the view class, so all public members are available
public void setTextExample (String s){
this.lblHuman.setText(s);
}
}
Then on the userInput class, you can 'refer' to that property on the other JPanel :
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRock) {
JOptionPane.showMessageDialog(null, "Hello world!");
// accessible now
lblHumanChoice.setTextExample("changed from other panel");
} else ...
}
NOTE: I edited the answer.
I've added the codes here. This way when you press ROCK button(for example), it shows its name in the other window. I used JFrame and called the SSPViewer class inside of SSPUserInput class. NOTE: I think you want to call some other classes inside SSPApp(that's why I wrote it) but even if you run SSPUserInput, it still pops up two windows.Now they are somethings like that: enter image description here and like this
SSPUserInput class
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SSPUserInput extends JFrame {
private JPanel contentPane;
JButton PaperButton;
JButton ScissorButton;
JButton rockButton;
SSPViewer viewer = new SSPViewer();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSPUserInput frame = new SSPUserInput();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SSPUserInput() {
viewer.frame.setVisible(true); //this code is important
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 93, 9, 19, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
rockButton = new JButton("ROCK");
GridBagConstraints gbc_rockButton = new GridBagConstraints();
gbc_rockButton.fill = GridBagConstraints.HORIZONTAL;
gbc_rockButton.insets = new Insets(0, 0, 5, 5);
gbc_rockButton.gridx = 1;
gbc_rockButton.gridy = 3;
panel.add(rockButton, gbc_rockButton);
ScissorButton = new JButton("Scissor");
GridBagConstraints gbc_ScissorButton = new GridBagConstraints();
gbc_ScissorButton.fill = GridBagConstraints.BOTH;
gbc_ScissorButton.insets = new Insets(0, 0, 5, 5);
gbc_ScissorButton.gridx = 3;
gbc_ScissorButton.gridy = 3;
panel.add(ScissorButton, gbc_ScissorButton);
PaperButton = new JButton("PAPER");
GridBagConstraints gbc_PaperButton = new GridBagConstraints();
gbc_PaperButton.fill = GridBagConstraints.HORIZONTAL;
gbc_PaperButton.insets = new Insets(0, 0, 5, 0);
gbc_PaperButton.gridx = 5;
gbc_PaperButton.gridy = 3;
panel.add(PaperButton, gbc_PaperButton);
JButton btnNewGame = new JButton("New Game");
GridBagConstraints gbc_btnNewGame = new GridBagConstraints();
gbc_btnNewGame.fill = GridBagConstraints.HORIZONTAL;
gbc_btnNewGame.insets = new Insets(0, 0, 5, 5);
gbc_btnNewGame.gridx = 3;
gbc_btnNewGame.gridy = 5;
panel.add(btnNewGame, gbc_btnNewGame);
JButton btnQuit = new JButton("Quit");
GridBagConstraints gbc_btnQuit = new GridBagConstraints();
gbc_btnQuit.fill = GridBagConstraints.HORIZONTAL;
gbc_btnQuit.insets = new Insets(0, 0, 0, 5);
gbc_btnQuit.gridx = 3;
gbc_btnQuit.gridy = 6;
panel.add(btnQuit, gbc_btnQuit);
MyListener2 listener = new MyListener2();
rockButton.addActionListener(listener);
ScissorButton.addActionListener(listener);
PaperButton.addActionListener(listener);
}
private class MyListener2 implements ActionListener {
public void mousePressed(ActionEvent e) {
//System.out.println(((JButton) e.getSource()).getText());
//String name = ((JButton) e.getSource()).getText();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println(((JButton) arg0.getSource()).getText());
String name = ((JButton) arg0.getSource()).getText();
viewer.humanWin.setText(name);
}
}
}
SSPViewer class
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class SSPViewer {
JFrame frame;
JLabel humanWin;
JLabel computerWin;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSPViewer window = new SSPViewer();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SSPViewer() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 4, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblFirstTo = new JLabel("First to 3!");
GridBagConstraints gbc_lblFirstTo = new GridBagConstraints();
gbc_lblFirstTo.insets = new Insets(0, 0, 5, 5);
gbc_lblFirstTo.gridx = 5;
gbc_lblFirstTo.gridy = 2;
panel.add(lblFirstTo, gbc_lblFirstTo);
JLabel lblHuman = new JLabel("Human");
GridBagConstraints gbc_lblHuman = new GridBagConstraints();
gbc_lblHuman.gridwidth = 3;
gbc_lblHuman.insets = new Insets(0, 0, 5, 5);
gbc_lblHuman.gridx = 2;
gbc_lblHuman.gridy = 4;
panel.add(lblHuman, gbc_lblHuman);
JLabel lblComputer = new JLabel("Computer");
GridBagConstraints gbc_lblComputer = new GridBagConstraints();
gbc_lblComputer.insets = new Insets(0, 0, 5, 0);
gbc_lblComputer.gridx = 7;
gbc_lblComputer.gridy = 4;
panel.add(lblComputer, gbc_lblComputer);
humanWin = new JLabel("");
GridBagConstraints gbc_humanWin = new GridBagConstraints();
gbc_humanWin.insets = new Insets(0, 0, 0, 5);
gbc_humanWin.gridx = 3;
gbc_humanWin.gridy = 6;
panel.add(humanWin, gbc_humanWin);
computerWin = new JLabel("");
GridBagConstraints gbc_computerWin = new GridBagConstraints();
gbc_computerWin.gridx = 7;
gbc_computerWin.gridy = 6;
panel.add(computerWin, gbc_computerWin);
}
}
SSPApp class
public class SSPApp {
SSPUserInput s = new SSPUserInput();
}

Trouble creating JLabel inside JPanel

I don't understand why the last part doesn't add to my interface. I tried different approaches, but none of them seems to work. I can't add 1024 labels to my panel this way. Did I do something wrong, or is there an alternative to this?
Can tell me what could be wrong with the code? Thanks!
Full code here:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.border.LineBorder;
public class CacheGUI extends JFrame {
private static final int LEN = 1024;
private static final long serialVersionUID = 1L;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CacheGUI frame = new CacheGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public CacheGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 500);
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Lista de referinte", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(6, 16, 124, 364);
getContentPane().add(panel);
panel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 16, 108, 340);
panel.add(scrollPane);
JTextPane txtpnDasd = new JTextPane();
txtpnDasd.setToolTipText("Lista curenta de adrese");
txtpnDasd.setEnabled(false);
txtpnDasd.setEditable(false);
scrollPane.setViewportView(txtpnDasd);
txtpnDasd.setText("<generate first>");
JButton btnGenerate = new JButton("GENERATE");
btnGenerate.setToolTipText("Incepe generarea listei de adrese.");
btnGenerate.setBounds(6, 422, 124, 23);
getContentPane().add(btnGenerate);
JButton btnStart = new JButton("START");
btnStart.setToolTipText("Ruleaza simularea");
btnStart.setBounds(550, 422, 124, 23);
getContentPane().add(btnStart);
JLabel lblBlockSize = new JLabel("Block size:");
lblBlockSize.setFont(new Font("Tahoma", Font.BOLD, 12));
lblBlockSize.setBounds(6, 394, 85, 14);
getContentPane().add(lblBlockSize);
textField = new JTextField();
textField.setToolTipText("");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setText("4");
textField.setBounds(79, 391, 51, 20);
getContentPane().add(textField);
textField.setColumns(10);
int blocksize = Integer.parseInt(textField.getText());
int nrofblocks = LEN/blocksize; // LEN is 1024
JPanel block_panel = new JPanel();
block_panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
block_panel.setBounds(140, 16, 534, 398);
getContentPane().add(block_panel);
block_panel.setLayout(new GridLayout(blocksize,nrofblocks,2,0));
// THIS IS THE PART THAT DOES NOT ADD TO THE PANEL I CREATED BEFORE --->
JLabel[] lbl=new JLabel[LEN];
for(int i=0;i<LEN;i++)
{
lbl[i]=new JLabel("TEST");
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
block_panel.add(lbl[i]); // i want to create yellow blocks inside my panel as labels to modyfy the color afterwards
}//<----
}
}
The issue is the ridiculous number of labels you have; they're there.
Set the bounds of the block panel to something larger, reduce LEN, etc. and you'll see them.
First things first: Your labels won't have a yellow background color. JLabels are not opaque by default. Setting it to true will show the yellow background as before:
lbl[i].setOpaque(true);
The second thing is the sheer number of labels you have. Reduce the number to 100 say, and you'll see you labels.
for(int i=0;i<100;i++)
{
lbl[i]=new JLabel("TEST");
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
lbl[i].setOpaque(true);
block_panel.add(lbl[i]);
}
Use a JScrollPane, set opaque, grid layout 1.rows, 2.columns, set fixed size for label,
use BorderFactory.
JPanel block_panel = new JPanel();
block_panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
block_panel.setBounds(140, 16, 534, 398);
JScrollPane block_scrollpane = new JScrollPane(block_panel);
block_scrollpane.setBounds(140, 16, 534, 398);
getContentPane().add(block_scrollpane);
//block_panel.setLayout(new GridLayout(blocksize, nrofblocks, 2, 0));
block_panel.setLayout(new GridLayout(nrofblocks, blocksize, 2, 0));
// THIS IS THE PART THAT DOES NOT ADD TO THE PANEL I CREATED BEFORE --->
JLabel[] lbl = new JLabel[LEN];
Dimension lblSize = new Dimension(85, 16);
for (int i = 0; i < LEN; i++) {
lbl[i] = new JLabel("TEST" + i);
lbl[i].setOpaque(true);
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1, true));
lbl[i].setPreferredSize(lblSize);
lbl[i].setMinimumSize(lblSize);
block_panel.add(lbl[i]); // i want to create yellow blocks
// inside my panel as labels to modyfy the color afterwards
}//<----

Why is my Java swing application misbehaving?

When I try to maximize the window, the orinigal window rendering remains while another maximized window appears making it messy.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import javax.swing.table.TableColumnModel;
/**
* #author ad *
*/
public class Blotter {
private JFrame topFrame;
private JPanel mainContentPanel;
private JList unsubscribedFields;
private JList subscribedFields;
private JButton butSubscribe;
private JButton butUnsubscribe;
private JButton butApply;
private JButton butOk;
private JButton butCancel;
private JPanel panConfirm;
private JPanel panToggle;
private JPanel panBottom;
private JPanel panLeftList;
private JPanel panRightList;
private JPanel panSubcribe;
private JPanel panUnsubscribe;
/**
* #param args
*/
public Blotter(){
topFrame = new JFrame("Subscription Fields");
mainContentPanel = new JPanel(new BorderLayout());
/*
butSubscribe = new JButton("-->");
butUnsubscribe= new JButton("<--");
butApply = new JButton("Apply");
butOk = new JButton("OK");
butCancel = new JButton("Cancel");*/
createAndBuildGui();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Blotter b = new Blotter();
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
b.createAndBuildGui();
b.fillGUI();
}
private void fillGUI() {
String[] someRow = {"S110","200","100","42","32"};
}
public void createAndBuildGui()
{
panConfirm = new JPanel(new GridLayout(1,3,5,5));
panToggle = new JPanel(new GridBagLayout());
panBottom = new JPanel(new FlowLayout());
butApply = new JButton("Apply");
butOk = new JButton("OK");
butCancel = new JButton("Cancel");
unsubscribedFields = new JList();
subscribedFields = new JList();
butSubscribe = new JButton(">>>");
butUnsubscribe = new JButton("<<<");
panSubcribe = new JPanel(new BorderLayout());
panUnsubscribe = new JPanel(new BorderLayout());
panLeftList = new JPanel(new BorderLayout());
panRightList = new JPanel(new BorderLayout());
// GridBagConstraints(int gridx, int gridy, int gridwidth,
// int gridheight, double weightx, double weighty,
// int anchor, int fill, Insets insets, int ipadx, int ipady)
panLeftList.add(unsubscribedFields, BorderLayout.CENTER);
panRightList.add(subscribedFields, BorderLayout.CENTER);
panSubcribe.add(butSubscribe, BorderLayout.SOUTH);
panUnsubscribe.add(butUnsubscribe, BorderLayout.NORTH);
panToggle.add(panLeftList,
new GridBagConstraints(0, 0, 1, 2, 0.5, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
panToggle.add(panRightList,
new GridBagConstraints(2, 0, 1, 2, 0.5, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
panToggle.add(panSubcribe,
new GridBagConstraints(1, 0, 1, 1, 0, 0.5, GridBagConstraints.SOUTH,
GridBagConstraints.NONE, new Insets(0, 2, 4, 4), 0, 0));
panToggle.add(panUnsubscribe,
new GridBagConstraints(1, 1, 1, 1, 0, 0.5, GridBagConstraints.NORTH,
GridBagConstraints.NONE, new Insets(0, 2, 4, 4), 0, 0));
// Building bottom OK Apply Cancel panel.
panConfirm.add(butApply, 0);
panConfirm.add(butOk, 1);
panConfirm.add(butCancel, 2);
panBottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panBottom.add(panConfirm, BorderLayout.EAST);
// building main content panel
mainContentPanel.add(panToggle,BorderLayout.CENTER);
mainContentPanel.add(panBottom, BorderLayout.SOUTH);
topFrame.add(mainContentPanel);
topFrame.pack();
topFrame.setVisible(true);
topFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
protected void createPriceTable() {
// More fields : "Quantity Done","Quantity Open","PInst","State","Cancel State","Executing System","WaveID","Source System","TraderID","Average Price","LastExecutionPrice","ClientOrderTag","OldQuantityDone"
String[] columnNames = {"OrderId","Account","Symbol","Side","Quantity",};
Object[][] o = new Object[0][columnNames.length];
}
}
You're calling createAndBuildGui() twice: once in main and once in the constructor.
public Blotter(){
topFrame = new JFrame("Subscription Fields");
mainContentPanel = new JPanel(new BorderLayout());
// ...
createAndBuildGui(); <--------
}
public static void main(String[] args) {
Blotter b = new Blotter();
// ...
b.createAndBuildGui(); <--------
b.fillGUI();
}
If you remove one of them, it works just fine.
It depends on layout manager you are using. For example BorderLayout knows to re-render elements when frame size is changed. Unfortunately you did not mention which window works for you and which does not but I saw GridBagLayout in your code. Probably this layout (better to say usage of this layout) prevents similar behavior.

Categories