I'm pretty new to Java, but have been using JPanels, JButtons, JLabels and JTextFields successfully in other parts of my program, but I'm running into trouble when trying to have a JPanel with a couple JButtons, JLabels, and JTextFields inside of it overtop of a painted background.
Here is all of the relevant code for this portion of the program. Currently, when the program runs the only thing that will display is the p1_fireButton, player1PowerField, and player1AngleField overtop of the background (Even though I have the components created for player 2, I purposely commented out adding the p2_Panel so that I could concentrate on p1_Panel.
The weird thing is that those JComponents will only display if I hit the TAB key after the program is running for whatever reason, which I'm also hoping someone could help me fix. My goal will be to have the p1_panel occupy the left orange box and the p2_panel occupy the right orange box. Help would be greatly appreciated!
public class GameFrame extends JFrame
{ //start class GameFrame
ImageIcon background = new ImageIcon("background.jpg");
ImageIcon terrain1 = new ImageIcon("terrain1.png");
//ImageIcon tank_red = new ImageIcon("tank_red.png");
//ImageIcon tank_red = new ImageIcon(player1Tank);
private int x_rectangle = 50;
private int y_rectangle = 50;
private JButton p1_fireButton;
private JButton p2_fireButton;
private JPanel p1_Panel;
private JPanel p2_Panel;
private JLabel player1PowerLabel;
private static JTextField player1PowerField;
private JLabel player1AngleLabel;
private static JTextField player1AngleField;
private JLabel player2PowerLabel;
private static JTextField player2PowerField;
private JLabel player2AngleLabel;
private static JTextField player2AngleField;
String player1Name;
String player2Name;
final Timer gameTimer = new Timer(8, new timer());
Projectile projectile = new Projectile(200, 300);
public GameFrame(String title)
{ //start GameFrame constructor
super(title);
Dimension size = getPreferredSize();
size.width = 1000;
setPreferredSize(size);
setResizable(false);
setLayout(null);
Color trans = new Color(0, 0, 0, 0);
//player1 panel
p1_Panel = new JPanel();
p1_Panel.setLayout(null);
p1_Panel.setBounds(0, 0, 500, 300);
p1_Panel.setBackground(trans);
p2_Panel = new JPanel();
p2_Panel.setLayout(null);
p2_Panel.setBounds(500, 0, 500, 300);
p2_Panel.setBackground(trans);
//player2 panel
/*p2_fireButtonPanel = new JPanel();
p2_fireButtonPanel.setBounds(400, 85, 100, 100);
p2_fireButtonPanel.setBackground(trans);*/
//player1 angle/power fields
player1PowerLabel = new JLabel("Power");
player1PowerLabel.setLayout(null);
player1PowerLabel.setBounds(400, 20, 50, 50);
player1PowerField = new JTextField(3);
player1PowerField.setLayout(null);
player1PowerField.setBounds(400, 10, 50, 25);
player1AngleLabel = new JLabel("Angle");
player1AngleLabel.setLayout(null);
player1AngleLabel.setBounds(30, 10, 50, 50);
player1AngleField = new JTextField(3);
player1AngleField.setLayout(null);
player1AngleField.setBounds(300, 10, 50, 25);
//player2 angle/power fields
player2PowerLabel = new JLabel("Power");
player2PowerLabel.setLayout(null);
player2PowerLabel.setBounds(0, 0, 10, 10);
player2PowerField = new JTextField(3);
player2PowerField.setLayout(null);
player2PowerField.setBounds(10, 10, 10, 10);
player2AngleLabel = new JLabel("Angle");
player2AngleLabel.setLayout(null);
player2AngleLabel.setBounds(30, 10, 10, 10);
player2AngleField = new JTextField(3);
player2AngleField.setLayout(null);
player2AngleField.setBounds(60, 10, 10, 10);
//player1 fire button
p1_fireButton = new JButton("Fire!");
p1_fireButton.setLayout(null);
p1_fireButton.setBounds(430, 70, 50, 50);
ActionListener fireListener = new fireButtonListener();
p1_fireButton.addActionListener(fireListener);
//player2 fire button
p2_fireButton = new JButton("Fire AGAIN!");
p2_fireButton.setLayout(null);
p2_fireButton.setBounds(530, 70, 50, 50);
//add components to player1 panel
p1_Panel.add(p1_fireButton);
p1_Panel.add(player1PowerLabel);
p1_Panel.add(player1PowerField);
p1_Panel.add(player1AngleLabel);
p1_Panel.add(player1AngleField);
//add components to player2 panel
p2_Panel.add(p2_fireButton);
p2_Panel.add(player2PowerLabel);
p2_Panel.add(player2PowerField);
p2_Panel.add(player2AngleLabel);
p2_Panel.add(player2AngleField);
//add components to GameFrame
add(p1_Panel);
//add(p2_Panel);
projectile.fireProjectile(60, -60 * Math.PI / 180.0);
} //end GameFrame constructor
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Image bg = background.getImage();
Image t1 = terrain1.getImage();
Image p1tank = StartPanel.getPlayer1Tank();
Image p2tank = StartPanel.getPlayer2Tank();
//Image tank1 = tank_red.getImage();
g2.drawImage(bg, 0, 0, 1000, 800, this);
g2.drawImage(t1, 0, 420, 1000, 380, this);
g2.drawImage(p1tank, 50, 300, 66, 50, null);
g2.drawImage(p2tank, 500, 300, 66, 50, null);
player1Name = new String(StartPanel.getPlayer1Name());
player2Name = new String(StartPanel.getPlayer2Name());
g.drawString(player1Name, 50, 50);
g.drawString(player2Name, 525, 50);
g2.setColor(Color.green);
g2.fillOval((int)projectile.getXPosition(), (int)projectile.getYPosition(), 15, 15);
}
public class timer implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//TanksGUI.gameFrame.moveRectangle(1, 1);
projectile.advanceProjectile(0.05);
if (projectile.getYPosition() > 400)
{
gameTimer.stop();
}
repaint();
}
}
public class fireButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
gameTimer.start();
}
}
} //end class GameFrame
Check out BackgroundPanel to help you with this. The basic code would be:
JPanel north = new JPanel();
north.add( new JLabel(...) );
north.add( new JTextField(10) );
JPanel gamePanel = new GamePanel();
BackgroundPanel background = new BackgroundPanel(...);
background.add(north, BorderLayout.North);
background.add(gamePanel);
frame.add(background);
The GamePanel is the panel where you do all the custom painting for your game characters. As noted by MadProgrammer, this painting should never be done in the paint() method of the frame.
Don't extend from JFrame you're not adding any functionality to it that creating an instance couldn't achieve. It also makes you're project unportable.
Don't override paint of top level containers. If for no other reason they are not double buffered, which will cause you problems if you want to perform animation. The paint chain for a top level container is rather complex and you've just circumvent the whole process.
Instead, create a custom component (from something like JPanel) and use it as you primary canvas. Override it's paintComponent method and render your background to it, making sure you call super.paintComponent first.
Make sure that any containers you are placing on this "canvas" are transparent, otherwise your background won't show up.
Have a look at Performing Custom Painting and Painting in AWT and Swing for more information
Related
I am solving an activity with the following statement: Create an application to display in a JDialog window eight JPanel components. Each panel should be colored in one of the eight colors in figure 1.
Figure 1
On each panel should be written the word that translates the meaning of the color. Use font size 18. Each panel should be colored using a color from Table 1, specifying the amount of each RGB (Red, Green, Blue) component that corresponds to the meaning of the color. Use the java.awt.Color class. Should be implementing just a single paintComponent method to paint the 8 panels and write the meaning of each color.
Table 1
The problem is that my JPanel does not appear in JDialog. And I have no idea how to make it appear.
Follows the code:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SigCoresGUI extends JDialog {
private static final long serialVersionUID = 1L;
private Color[] cores = { new Color(255, 255, 255), new Color(249, 206, 137), new Color(255, 128, 0),
new Color(255, 0, 0), new Color(244, 102, 174), new Color(5, 120, 203), new Color(116, 186, 160),
new Color(0, 0, 0) };
private String[] sig = { "Paz", "Energia", "Criatividade", "Paixão", "Ternura", "Tranquilidade", "Harmonia",
"Elegância" };
private Font font = new Font("Arial", Font.BOLD, 18);
public SigCoresGUI() {
super();
Desenha desenha = new Desenha();
add(desenha);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
setLayout(new GridLayout(8, 8));
setSize(400, 500);
setVisible(true);
}
public class Desenha extends JPanel {
private static final long serialVersionUID = 1L;
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
for (int i = 0; i < 8; i++) {
JPanel panel = new JPanel();
panel.setBackground(cores[i]);
panel.setFont(font);
JLabel label = new JLabel(sig[i]);
label.setFont(font);
if (i > 0)
label.setForeground(Color.WHITE);
panel.add(label);
add(panel);
}
}
}
}
Never add or remove components from a container (here your JPanel) within a painting method. Painting methods should be for painting and painting only, not for changing the component structure of a container. Understand that you do not have direct control over when or even if a painting method is called, and it can be called many times -- adding many unnecessary components to the container -- and you also never want to slow painting down.
You are overriding paintComponents, a method that (per the API)
Paints each of the components in this container
and since the JPanel has no components to begin with, the method is likely never called.
Instead, add your components in the SigCoresGUI constructor.
Also:
Avoid using setSize(...)
Instead pack() the JDialog before displaying it to let the components and containers size themselves using their preferred sizes.
So this will work although I don't know what layout you're looking for:
import java.awt.*;
import javax.swing.*;
public class SigCoresGUI extends JDialog {
private static final long serialVersionUID = 1L;
private Color[] cores = { new Color(255, 255, 255), new Color(249, 206, 137), new Color(255, 128, 0),
new Color(255, 0, 0), new Color(244, 102, 174), new Color(5, 120, 203), new Color(116, 186, 160),
new Color(0, 0, 0) };
private String[] sig = { "Paz", "Energia", "Criatividade", "Paixão", "Ternura", "Tranquilidade", "Harmonia",
"Elegância" };
private Font font = new Font("Arial", Font.BOLD, 18);
public SigCoresGUI() {
super();
Desenha desenha = new Desenha();
add(desenha);
pack();
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
// setLayout(new GridLayout(8, 8));
// setSize(400, 500);
setVisible(true);
}
public class Desenha extends JPanel {
private static final long serialVersionUID = 1L;
public Desenha() {
setLayout(new GridLayout(0, 1));
for (int i = 0; i < 8; i++) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(cores[i]);
panel.setFont(font);
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel label = new JLabel(sig[i]);
label.setFont(font);
if (i > 0)
label.setForeground(Color.WHITE);
panel.add(label);
add(panel);
}
}
//#Override
//public void paintComponents(Graphics g) {
// super.paintComponents(g);
//}
}
public static void main(String[] args) {
new SigCoresGUI();
}
}
Im trying to draw a simple rectangle on a frame with some scrollbars and textfields(just testing) but the paintComponent its not showing, ive seen some similar cases here but i cant manage to make it work, any help please?
package appletdeslizadores;
import java.awt.*;
import javax.swing.*;
public class frame extends JPanel {
JFrame f1;
JPanel p1, p2;
JLabel lbl1, lbl2, lbl3;
JTextField txtfld1, txtfld2, txtfld3;
JScrollBar sbar1, sbar2, sbar3;
public frame() {
f1 = new JFrame("Applet ScrollBars");
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(380, 350);
f1.setLayout(new FlowLayout());
p1 = new JPanel(new GridLayout(3,3,10,10));
lbl1 = new JLabel("Scroll Bar 1");
lbl2 = new JLabel("Scroll Bar 2");
lbl3 = new JLabel("Scroll Bar 3");
sbar1 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
sbar2 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
sbar3 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
txtfld1 = new JTextField(3);
txtfld1.setText(String.valueOf(sbar1.getValue()));
txtfld1.setEditable(false);
txtfld2 = new JTextField(3);
txtfld2.setText(String.valueOf(sbar2.getValue()));
txtfld2.setEditable(false);
txtfld3 = new JTextField(3);
txtfld3.setText(String.valueOf(sbar3.getValue()));
txtfld3.setEditable(false);
p1.add(lbl1);
p1.add(lbl2);
p1.add(lbl3);
p1.add(sbar1);
p1.add(sbar2);
p1.add(sbar3);
p1.add(txtfld1);
p1.add(txtfld2);
p1.add(txtfld3);
f1.add(p1);
f1.setVisible(true);
}
public void paintComponent(Graphics2D g) {
g.drawRect(50,50,70,100);
g.setColor(Color.red);
}
public static void main(String[] args) {
new frame();
}
}
Problem
You're not sticking to conventions. This is causing problems small mistakes. Your frame class is actually a JPanel, not a JFrame.
There are two main problems: You never added the panel to the frame, and the paintComponent() method has a Graphics object, not a Graphics2D object as a parameter.
The changes to your code are at the bottom of this answer.
Solution
Stick to conventions. (You should also rename your class to a more appropriate name, but that is your choice.) Add the #Override annotation to your paintComponent() method since you wish to override this method from the original JPanel. If it crashes because of the annotation, it means you are not overriding correctly.
Change the paintComponent() parameter from Graphics2D to Graphics.
Add the JPanel to the JFrame.
Make sure you call setPreferredSize() on your JPanel and specify a size.
Call pack() on the JFrame right before making it visible so the layout manager can place everything accordingly.
Now I'm sure by the end of all this you are still not going to be happy with what you see because the code still needs some work, but at least this should give you a boost into the right direction. Also, you may want to call setColor() before drawing the rectangle. ;)
Hope this helped.
Code
public class frame extends JPanel {
JFrame f1;
JPanel p1, p2;
JLabel lbl1, lbl2, lbl3;
JTextField txtfld1, txtfld2, txtfld3;
JScrollBar sbar1, sbar2, sbar3;
public frame() {
f1 = new JFrame("Applet ScrollBars");
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(380, 350);
f1.setLayout(new FlowLayout());
p1 = new JPanel(new GridLayout(3,3,10,10));
lbl1 = new JLabel("Scroll Bar 1");
lbl2 = new JLabel("Scroll Bar 2");
lbl3 = new JLabel("Scroll Bar 3");
sbar1 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
sbar2 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
sbar3 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
txtfld1 = new JTextField(3);
txtfld1.setText(String.valueOf(sbar1.getValue()));
txtfld1.setEditable(false);
txtfld2 = new JTextField(3);
txtfld2.setText(String.valueOf(sbar2.getValue()));
txtfld2.setEditable(false);
txtfld3 = new JTextField(3);
txtfld3.setText(String.valueOf(sbar3.getValue()));
txtfld3.setEditable(false);
p1.add(lbl1);
p1.add(lbl2);
p1.add(lbl3);
p1.add(sbar1);
p1.add(sbar2);
p1.add(sbar3);
p1.add(txtfld1);
p1.add(txtfld2);
p1.add(txtfld3);
f1.add(p1);
setPreferredSize(new Dimension(512, 512));
f1.add(this);
f1.pack();
f1.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
g.drawRect(50,50,70,100);
g.setColor(Color.red);
}
public static void main(String[] args) {
new frame();
}
}
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.
In my Tic-Tac-Toe game, I have painted the lines and I am now trying to put in the buttons. The first button I am trying to put in, I am trying to set the bounds of, and It doesn't set the bounds. It just fills the whole screen. How do I get button to only be in the top right square?
public class Project extends JFrame{
static JButton button = new JButton("");
static JButton button2 = new JButton("");
static JButton button3 = new JButton("");
static JButton button4 = new JButton("");
static JButton button5 = new JButton("");
static JButton button6 = new JButton("");
static JButton button7 = new JButton("");
static JButton button8 = new JButton("");
static JButton button9 = new JButton("");
public Project(){
setSize(1000, 750);
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Float(100, 100, 100, 400);
Line2D line2 = new Line2D.Float(200, 100, 200, 400);
Line2D line3 = new Line2D.Float(0, 200, 300, 200);
Line2D line4 = new Line2D.Float(0, 300, 300, 300);
g2.draw(line);
g2.draw(line2);
g2.draw(line3);
g2.draw(line4);
}
public static void main(String[] args){
Project t = new Project();
t.setVisible(true);
button.setBounds(0, 0, 50, 50);
t.add(button);
}
}
Your Project class extends JFrame, and the JFrame contentPane, the JFrame container that accepts new components, uses BorderLayout by default. When you add a component to a BorderLayout-using container without specifying where the component goes, it is by default added to the BorderLayout.CENTER position, effectively filling up your GUI. Several options exist to solve your dilemma:
Use a GridLayout as suggested by PM77-1. This way a 3x3 grid will hold all 9 buttons in equal sized cells, filling up the container.
Not using buttons and ActionListeners at all, but rather using a MouseListenerListener to check where a button press has occurred, deciding if its an empty cell, and acting accordingly.
I am working on a little menu program with clickable buttons and an image that changes based on button clicks. If I click a button I get a shadow of the button at the bottom where I change the JLabel text. I cannot figure it out for the life of me. Any advice would be greatly appreciated. Visuals below...thanks
public class SampleGUI
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
System.out.println("Created GUI on EDT? " +
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Robert's VICI Prototype");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel
{
// Fields
Image imageDisplayed;
JLabel status;
// Methods
public MyPanel()
{
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setLayout(null);
JLabel title = new JLabel("CS380 TEAM 5 VICI Prototype");
title.setFont(new Font("Tahoma", Font.BOLD, 20));
title.setBounds(425, 10, 400, 40);
add(title);
status = new JLabel("Please click an option above.");
status.setFont(new Font("Tahoma", Font.BOLD, 14));
status.setBounds(425, 740, 400, 40);
add(status);
JButton choice1 = new JButton("Search Class");
choice1.setBounds(50, 50, 150, 40);
add(choice1);
JButton choice2 = new JButton("Add Class");
choice2.setBounds(225, 50, 150, 40);
add(choice2);
JButton choice3 = new JButton("Drop Class");
choice3.setBounds(400, 50, 150, 40);
add(choice3);
JButton choice4 = new JButton("Verify Reg Hold");
choice4.setBounds(575, 50, 150, 40);
add(choice4);
JButton choice5 = new JButton("Verify Reg Date");
choice5.setBounds(750, 50, 150, 40);
add(choice5);
JButton choice6 = new JButton("Schedule Advisor");
choice6.setBounds(925, 50, 150, 40);
add(choice6);
choice6.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Schedule Advisor button pressed.");
status.setText("Choose a date.");
imageDisplayed = new ImageIcon("C:\\Temp\\sa01.jpg").getImage();
}
});
JButton exit = new JButton("EXIT");
exit.setBounds(940, 750, 150, 40);
add(exit);
exit.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
imageDisplayed = new ImageIcon("C:\\Temp\\main.jpg").getImage();
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(1100, 800);
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(imageDisplayed, 100, 120, 900, 600, this);
}
}
You've broken the paint chain...
#Override
public void paintComponent(Graphics g)
{
g.drawImage(imageDisplayed, 100, 120, 900, 600, this);
}
The first thing you should be calling is super.paintComponent(g)
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(imageDisplayed, 100, 120, 900, 600, this);
}
The Graphics context is shared resource, meaning that the Graphics context you get has also been used to paint the other components that have also been painted. One of the jobs of paintComponent is to clear the Graphics context ready for the component to be painted (fill the background)
See Painting in AWT and Swing and Performing Custom Painting for more details
You should, also, avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify. See Why is it frowned upon to use a null layout in SWING? for more details...
Before you go all defensive over getting your screen laid out just nicely, you shouldn't be doing it this way. You controls should be laid out on separate containers (using appropriate layout managers) and you "drawing surface" should be it's own component. See Laying Out Components Within a Container for more details...
If you're still not convicned, take a look at Why setting setPreferredSize() on JFrame is bad? and java expandable JDialog for examples of differences between Mac and Windows