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
}//<----
Related
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)));
}
}
}
This question already has answers here:
how to change UI depending on combo box selection
(1 answer)
Positioning component inside card layout
(1 answer)
Closed 5 years ago.
I am trying to change between card panels using the Jcombobox "Expenses". Can someone tell me what I'm doing wrong? I get the panels to appear properly, but when I see the Expenses j tabbed pane, the first card is shown. Once I try to switch between them, the console gets filled with errors. I noticed that all cards are showing at the same time, but they are overlapping.
1)How do I get only one card (panels) showing at once?
2)How do I get the JComboBox to switch between cards(panels)?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
public class LanaFrame extends JFrame implements ItemListener{
private JPanel contentPane, cards;
private JList driverlist;
private JComboBox expenses;
final static String FUEL= "Fuel";
final static String TOLL= "Toll";
final static String REPAIR="Repair";
private static String[] comboboxitems= {FUEL,TOLL,REPAIR};
private JTextField textFieldFirstName;
private JTextField textFieldLastName;
private JTextField textFieldTruckNumber;
private JTextField textFieldTrailerNumber;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LanaFrame frame = new LanaFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LanaFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 500);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(5, 5, 775, 480);
contentPane.add(tabbedPane);
//Drivers Panel
JPanel Drivers = new JPanel();
tabbedPane.addTab("Drivers", null, Drivers, null);
Drivers.setLayout(null);
driverlist= new JList(comboboxitems);
driverlist.setBackground(Color.WHITE);
driverlist.setVisibleRowCount(4);
driverlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Drivers.add(driverlist);
driverlist.setBounds(482,6,266,211);
JButton btnAddDriver = new JButton("Add Driver");
btnAddDriver.setBounds(5, 285, 117, 29);
Drivers.add(btnAddDriver);
JTextArea driverArea = new JTextArea();
driverArea.setBackground(Color.LIGHT_GRAY);
driverArea.setBounds(482, 217, 266, 211);
Drivers.add(driverArea);
driverArea.setEditable(false);
JTextPane txtpnFirstName = new JTextPane();
txtpnFirstName.setText("First name");
txtpnFirstName.setBounds(5, 20, 140, 15);
Drivers.add(txtpnFirstName);
txtpnFirstName.setEditable(false);
textFieldFirstName = new JTextField();
textFieldFirstName.setBounds(5, 40, 140, 30);
Drivers.add(textFieldFirstName);
textFieldFirstName.setColumns(10);
JTextPane txtpnLastName = new JTextPane();
txtpnLastName.setText("Last Name");
txtpnLastName.setBounds(5, 75, 140, 15);
Drivers.add(txtpnLastName);
txtpnLastName.setEditable(false);
textFieldLastName = new JTextField();
textFieldLastName.setBounds(5, 95, 140, 30);
Drivers.add(textFieldLastName);
textFieldLastName.setColumns(10);
JTextPane txtpnTruckNumber = new JTextPane();
txtpnTruckNumber.setText("Truck Number");
txtpnTruckNumber.setBounds(5, 130, 140, 15);
Drivers.add(txtpnTruckNumber);
txtpnTruckNumber.setEditable(false);
textFieldTruckNumber = new JTextField();
textFieldTruckNumber.setBounds(5, 150, 140, 30);
Drivers.add(textFieldTruckNumber);
textFieldTruckNumber.setColumns(10);
JTextPane txtpnTrailerNumber = new JTextPane();
txtpnTrailerNumber.setText("Trailer Number");
txtpnTrailerNumber.setBounds(5, 185, 140, 15);
Drivers.add(txtpnTrailerNumber);
txtpnTrailerNumber.setEditable(false);
textFieldTrailerNumber = new JTextField();
textFieldTrailerNumber.setBounds(5, 205, 140, 30);
Drivers.add(textFieldTrailerNumber);
textFieldTrailerNumber.setColumns(10);
JButton btnDeleteDriver = new JButton("Delete Driver");
btnDeleteDriver.setBounds(359, 185, 117, 29);
Drivers.add(btnDeleteDriver);
//New Expenses Panel
JPanel NewExpense = new JPanel();
tabbedPane.addTab("New Expense", null, NewExpense, null);
//adds types of expenses to jcombo
expenses = new JComboBox(comboboxitems);
expenses.setBounds(257, 5, 236, 30);
expenses.setEditable(false);
expenses.addItemListener(this);
NewExpense.setLayout(null);
NewExpense.add(expenses);
//create panels for each combo option
JPanel fuel = new JPanel();
fuel.setBounds(0, 0, 743, 399);
fuel.setBackground(Color.BLUE);
JPanel toll = new JPanel();
toll.setBounds(0, 0, 743, 399);
toll.setBackground(Color.RED);
JPanel repair = new JPanel();
repair.setBounds(0, 0, 743, 399);
repair.setBackground(Color.BLACK);
//Assigns Panels to combo options
cards = new JPanel(new CardLayout());
cards.setBounds(5, 29, 743, 399);
cards.setLayout(null);
cards.add(fuel, FUEL);
cards.add(toll, TOLL);
cards.add(repair, REPAIR);
NewExpense.add(cards);
JPanel Income = new JPanel();
tabbedPane.addTab("Income", null, Income, null);
Income.setLayout(null);
JPanel Results = new JPanel();
tabbedPane.addTab("Result", null, Results, null);
Results.setLayout(null);
}
#Override
public void itemStateChanged(ItemEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)e.getItem());
}
}
cards = new JPanel(new CardLayout());
cards.setBounds(5, 29, 743, 399);
cards.setLayout(null); // ???!!!
Seriously? You're setting the cards layout to CardLayout, and then immediatly setting it again to null. And then you get a NullPointerException when you try to use the cards "layout" -- no surprise!
Hi I'm trying to display an ArrayList of Objects on a Jlist. While displaying the ArrayList, I'm trying to be able to add or delete objects to the ArrayList through the GUI.
1) How can I display the ArrayList objects on the Jlist? 2)How can I delete an object by selecting it on the JList?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
public class DriverFrame extends JFrame implements ItemListener{
private JPanel contentPane;
private JList driverlist;
private ArrayList drivers= new ArrayList<Driver>();
JTextField textFieldFirstName;
JTextField textFieldLastName;
JTextField textFieldTruckNumber;
JTextField textFieldTrailerNumber;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DriverFrame frame = new DriverFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DriverFrame() {
Driver guy1= new Driver("Jeff","Blank","4125","1234",1400);
Driver guy2= new Driver("Marcus","Geralds","0093","1203",1800);
Driver guy3= new Driver("Steve","Wemmings","2010","2046",2100);
Driver guy4= new Driver("Kyle","Patricks","8427","5625",900);
Driver guy5= new Driver("Ficel","Metter","9124","4536",5500);
setBackground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
setResizable(false);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBackground(Color.WHITE);
tabbedPane.setBounds(5, 5, 495, 480);
contentPane.add(tabbedPane);
//Drivers TabbedPan ********
JPanel Drivers = new JPanel();
Drivers.setBackground(Color.WHITE);
tabbedPane.addTab("Drivers", null, Drivers, null);
Drivers.setLayout(null);
//List to display drivers
JList<Object> driverlist = new JList<>(drivers.toArray(new String[0]));
driverlist.setBackground(Color.WHITE);
driverlist.setVisibleRowCount(8);
driverlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Drivers.add(driverlist);
driverlist.setBounds(221,6,247,234);
JTextPane txtpnFirstName = new JTextPane();
txtpnFirstName.setText("First name");
txtpnFirstName.setBounds(5, 20, 140, 15);
Drivers.add(txtpnFirstName);
txtpnFirstName.setEditable(false);
textFieldFirstName = new JTextField();
textFieldFirstName.setBounds(5, 40, 140, 30);
Drivers.add(textFieldFirstName);
textFieldFirstName.setColumns(10);
JTextPane txtpnLastName = new JTextPane();
txtpnLastName.setText("Last Name");
txtpnLastName.setBounds(5, 75, 140, 15);
Drivers.add(txtpnLastName);
txtpnLastName.setEditable(false);
textFieldLastName = new JTextField();
textFieldLastName.setBounds(5, 95, 140, 30);
Drivers.add(textFieldLastName);
textFieldLastName.setColumns(10);
JTextPane txtpnTruckNumber = new JTextPane();
txtpnTruckNumber.setText("Truck Number");
txtpnTruckNumber.setBounds(5, 130, 140, 15);
Drivers.add(txtpnTruckNumber);
txtpnTruckNumber.setEditable(false);
textFieldTruckNumber = new JTextField();
textFieldTruckNumber.setBounds(5, 150, 140, 30);
Drivers.add(textFieldTruckNumber);
textFieldTruckNumber.setColumns(10);
JTextPane txtpnTrailerNumber = new JTextPane();
txtpnTrailerNumber.setText("Trailer Number");
txtpnTrailerNumber.setBounds(5, 185, 140, 15);
Drivers.add(txtpnTrailerNumber);
txtpnTrailerNumber.setEditable(false);
textFieldTrailerNumber = new JTextField();
textFieldTrailerNumber.setBounds(5, 205, 140, 30);
Drivers.add(textFieldTrailerNumber);
textFieldTrailerNumber.setColumns(10);
JButton btnAddDriver = new JButton("Add Driver");
btnAddDriver.setBounds(5, 285, 117, 29);
Drivers.add(btnAddDriver);
JButton btnNewButton = new JButton("Delete Driver");
btnNewButton.setBounds(302, 285, 117, 29);
Drivers.add(btnNewButton);
btnAddDriver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Driver blah = new Driver();
blah.setFirst(textFieldFirstName.getText());
blah.setLast(textFieldLastName.getText());
blah.setTnum(textFieldTruckNumber.getText());
blah.setTrailer(textFieldTrailerNumber.getText());
drivers.add(blah);
System.out.println(blah.printDriver());
System.out.println(drivers.size());
//drivers.remove(example);
}
});
//End of DriversPane******
//New Expenses Tab*****
JPanel NewExpense = new JPanel();
tabbedPane.addTab("New Expense", null, NewExpense, null);
JButton buttontest = new JButton();
NewExpense.add(buttontest);
//End of New Expense Tab****
//Income Tab****
JPanel Income = new JPanel();
Income.setBackground(Color.WHITE);
tabbedPane.addTab("Income", null, Income, null);
Income.setLayout(null);
JComboBox comboBox_3 = new JComboBox();
comboBox_3.setBounds(6, 70, 138, 27);
Income.add(comboBox_3);
JTextPane txtpnDriver_3 = new JTextPane();
txtpnDriver_3.setText("Driver:");
txtpnDriver_3.setBounds(6, 42, 42, 16);
Income.add(txtpnDriver_3);
JTextPane txtpnLoadLocationstate = new JTextPane();
txtpnLoadLocationstate.setText("Load Location(State): ");
txtpnLoadLocationstate.setBounds(6, 161, 138, 16);
Income.add(txtpnLoadLocationstate);
textField_6 = new JTextField();
textField_6.setBounds(6, 205, 130, 26);
Income.add(textField_6);
textField_6.setColumns(10);
JTextPane txtpnLoadAmount = new JTextPane();
txtpnLoadAmount.setText("Load Amount $$:");
txtpnLoadAmount.setBounds(6, 299, 108, 16);
Income.add(txtpnLoadAmount);
textField_7 = new JTextField();
textField_7.setBounds(6, 339, 130, 26);
Income.add(textField_7);
textField_7.setColumns(10);
//End of Income Tab****
//Results Tab***
JPanel Results = new JPanel();
Results.setBackground(Color.WHITE);
tabbedPane.addTab("Result", null, Results, null);
Results.setLayout(null);
JComboBox comboBox_4 = new JComboBox();
comboBox_4.setBounds(6, 69, 140, 27);
Results.add(comboBox_4);
JTextPane txtpnDriver_4 = new JTextPane();
txtpnDriver_4.setText("Driver:");
txtpnDriver_4.setBounds(6, 42, 140, 16);
Results.add(txtpnDriver_4);
JTextArea txtrHowMuchTo = new JTextArea();
txtrHowMuchTo.setText("How much to pay driver. How much are the expenses of the driver");
txtrHowMuchTo.setBounds(6, 124, 234, 304);
Results.add(txtrHowMuchTo);
JTextPane txtpnDriverInformation = new JTextPane();
txtpnDriverInformation.setText("Driver Information");
txtpnDriverInformation.setBounds(16, 108, 140, 16);
Results.add(txtpnDriverInformation);
JTextPane txtpnCompanyInfo = new JTextPane();
txtpnCompanyInfo.setText("Company Info:");
txtpnCompanyInfo.setBounds(414, 80, 178, 16);
Results.add(txtpnCompanyInfo);
JTextArea txtrIncome = new JTextArea();
txtrIncome.setText("Income Expenses");
txtrIncome.setBounds(390, 124, 294, 304);
Results.add(txtrIncome);
//End of Results Tab****
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
}
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:
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.