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.
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();
}
}
This question already has answers here:
Add an Background image to a Panel
(2 answers)
Closed 7 years ago.
I just making kmap program but there is a problem in the code . I take JFrame on which I use JLabel to set background image and another JPanel on which I make table of 4x4 using gridlayout. I add two JButtons compute and reset and 8 JLabels indicating the positions(A'B' etc). but the background image comes infront of buttons labels and table.
package kmap;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class kmapping extends JFrame {
static String output = "";
static int Arr[][] = new int[4][4];
static int checked[][] = new int[4][4];
static int value[] = new int[16];
JButton btn[] = new JButton[16];
JLabel lbl[] = new JLabel[10];
JPanel table;
;
JLabel text, bg;
JButton compute, reset;
kmapping() {
JFrame f = new JFrame();
f.setTitle("KARNAUGH MAP");
f.setSize(580, 430);
f.setVisible(true);
f.setLocation(300, 50);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setResizable(false);
f.setLayout(null);
bg = new JLabel(new ImageIcon("C:\\Documents and Settings\\user\\My Documents\\NetBeansProjects\\kmap\\background.png"));
bg.setBounds(0, 0, 579, 429);
f.add(bg);
table = new JPanel();
text = new JLabel();
table.setBounds(140, 30, 400, 300);
table.setBackground(Color.white);
text.setBounds(50, 300, 620, 110);
text.setBackground(Color.blue);
//adding button in table
table.setLayout(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) {
btn[i] = new JButton();
btn[i].setIcon(new ImageIcon("C:\\Documents and Settings\\user\\My Documents\\NetBeansProjects\\kmap\\images\\x.png"));
table.add(btn[i]);
table.validate();
value[i] = 2;
}
//
lbl[0] = new JLabel("A'B'");
lbl[0].setBounds(110, 30, 30, 75);
f.add(lbl[0]);
lbl[1] = new JLabel("A'B");
lbl[1].setBounds(110, 105, 30, 75);
f.add(lbl[1]);
lbl[2] = new JLabel("AB");
lbl[2].setBounds(110, 180, 30, 75);
f.add(lbl[2]);
lbl[3] = new JLabel("AB'");
lbl[3].setBounds(110, 255, 30, 75);
f.add(lbl[3]);
lbl[4] = new JLabel("C'D'");
lbl[4].setBounds(160, 0, 80, 30);
f.add(lbl[4]);
lbl[5] = new JLabel("C'D");
lbl[5].setBounds(260, 0, 80, 30);
f.add(lbl[5]);
lbl[6] = new JLabel("CD");
lbl[6].setBounds(360, 0, 80, 30);
f.add(lbl[6]);
lbl[7] = new JLabel("CD'");
lbl[7].setBounds(460, 0, 80, 30);
f.add(lbl[7]);
f.validate();
compute = new JButton("COMPUTE");
compute.setBounds(5, 100, 100, 40);
f.add(compute);
reset = new JButton("RESET");
reset.setBounds(5, 160, 100, 40);
f.add(reset);
f.add(table);
compute.validate();
reset.validate();
f.add(text);
f.validate();
try this ..thanks
1. Create a subclass of JComponent.
2. Override the paintComponent(Graphics g) method to paint the image that you want to display.
3. Set the content pane of the JFrame to be this subclass.
// elsewhere
BufferedImage myImage = ImageIO.load(...);
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));
Don't worry mate the problem is that your background JLabel should be the last thing you put on your constructor no need to make drastic changes try this hope it works , base on my experience I always do this when I put a back ground image on my JFrame.
package kmap;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class kmapping extends JFrame {
static String output = "";
static int Arr[][] = new int[4][4];
static int checked[][] = new int[4][4];
static int value[] = new int[16];
JButton btn[] = new JButton[16];
JLabel lbl[] = new JLabel[10];
JPanel table;
;
JLabel text, bg;
JButton compute, reset;
kmapping() {
JFrame f = new JFrame();
f.setTitle("KARNAUGH MAP");
f.setSize(580, 430);
f.setVisible(true);
f.setLocation(300, 50);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setResizable(false);
f.setLayout(null);
table = new JPanel();
text = new JLabel();
table.setBounds(140, 30, 400, 300);
table.setBackground(Color.white);
text.setBounds(50, 300, 620, 110);
text.setBackground(Color.blue);
//adding button in table
table.setLayout(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) {
btn[i] = new JButton();
btn[i].setIcon(new ImageIcon("C:\\Documents and Settings\\user\\My Documents\\NetBeansProjects\\kmap\\images\\x.png"));
table.add(btn[i]);
table.validate();
value[i] = 2;
}
//
lbl[0] = new JLabel("A'B'");
lbl[0].setBounds(110, 30, 30, 75);
f.add(lbl[0]);
lbl[1] = new JLabel("A'B");
lbl[1].setBounds(110, 105, 30, 75);
f.add(lbl[1]);
lbl[2] = new JLabel("AB");
lbl[2].setBounds(110, 180, 30, 75);
f.add(lbl[2]);
lbl[3] = new JLabel("AB'");
lbl[3].setBounds(110, 255, 30, 75);
f.add(lbl[3]);
lbl[4] = new JLabel("C'D'");
lbl[4].setBounds(160, 0, 80, 30);
f.add(lbl[4]);
lbl[5] = new JLabel("C'D");
lbl[5].setBounds(260, 0, 80, 30);
f.add(lbl[5]);
lbl[6] = new JLabel("CD");
lbl[6].setBounds(360, 0, 80, 30);
f.add(lbl[6]);
lbl[7] = new JLabel("CD'");
lbl[7].setBounds(460, 0, 80, 30);
f.add(lbl[7]);
f.validate();
compute = new JButton("COMPUTE");
compute.setBounds(5, 100, 100, 40);
f.add(compute);
reset = new JButton("RESET");
reset.setBounds(5, 160, 100, 40);
f.add(reset);
f.add(table);
compute.validate();
reset.validate();
f.add(text);
f.validate();
//Setting up the background
bg = new JLabel(new ImageIcon("C:\\Documents and Settings\\user\\My Documents\\NetBeansProjects\\kmap\\background.png"));
bg.setBounds(0, 0, 579, 429);
f.add(bg);
This will now work and all you components are going to be on top of your background
Hi i am trying to make java desktop application where i am using multiple jlabel i want to give little spaces between every label
how can i achieve this
here is my code
public class Second extends javax.swing.JFrame {
JLabel label=new JLabel();
/**
* Creates new form Second
*/
public Second() {
this.getContentPane().setBackground(new java.awt.Color(255, 140, 0));
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setUndecorated(true);
JButton print= new JButton();
print.setBackground(new java.awt.Color(153, 153, 0));
print.setOpaque(true);
print.setBounds(525,1282,130,85);
print.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
print.setForeground(new java.awt.Color(255,255,255));
print.setText("Print");
this.add(print);
JButton home= new JButton();
home.setBackground(new java.awt.Color(153, 153, 0));
home.setOpaque(true);
home.setBounds(640,1282,130,85);
home.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
home.setForeground(new java.awt.Color(255, 255,255 ));
home.setText("Home");
this.add(home);
int Height = 134;
int a=100;
ArrayList<JLabel> label = new ArrayList<JLabel>();
for(int i=0;i<23;i++){
JLabel j = new JLabel();
j.setBackground(new java.awt.Color(255, 140, 255));
j.setOpaque(true);
j.setBounds(5,Height,378,50);
j.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
j.setForeground(new java.awt.Color(128, 128, 128));
j.setText("Case Item CourtNo ");
LineBorder line = new LineBorder(Color.blue, 2, true);
j.setBorder(line);
this.add(j);
label.add(j);
JLabel j1 = new JLabel();
j1.setBackground(new java.awt.Color(255, 140, 0));
j1.setOpaque(true);
j1.setBounds(390,Height,768,50);
j1.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
j1.setForeground(new java.awt.Color(128, 128, 128));
j1.setText("Case Item CourtNo ");
this.add(j1);
label.add(j1);
Height = Height +50;
a=a+10;
}
initComponents();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g3 = (Graphics2D) g;
BasicStroke bs = new BasicStroke(2);
Line2D lin1 = new Line2D.Float(386, 100, 386, 1282);
Line2D lin = new Line2D.Float(0, 1283, 768, 1283);
Line2D line3=new Line2D.Float(400,1284,400,1364);
g3.setStroke(bs);
g3.setColor(Color.white);
g3.draw(lin1);
g3.draw(lin);
g3.draw(line3);;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Second().setVisible(true);
}
});
}}
My new code
public class Testing1 extends javax.swing.JFrame {
public Testing1() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
panel.setLocation(100, 100);
//panel.setLayout(null);
this.add(panel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
initComponents();
}
private JPanel createPanel() {
jPanel1 = new JPanel(new GridLayout(0, 1, 10, 5));
EmptyBorder panelBorder = new EmptyBorder(10, 10, 10, 10);
jPanel1.setBorder(panelBorder);
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i <12; i++) {
JLabel label = new JLabel("Label" + i);
label.setBorder(compound);
// label.setBounds(13, 100, 100, 50);
jPanel1.add(label);
}
return jPanel1;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(204, 0, 153));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 306, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 243, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 94, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Testing1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
updated
Thanks in advance
"How to give spaces between jlabel?"
setBounds and null layouts: no; Use EmptyBorders: YES!; Use LayoutManagers: YES!
"how can i use this can u explain little bit "
Use can use the default FlowLayout of the containing JPanel (or in this case set the gaps of the FlowLayout)
FlowLayout constructor:
public FlowLayout(int align,
int hgap,
int vgap)
align - the alignment value
hgap - the horizontal gap between components and between the components and the borders of the Container
vgap - the vertical gap between components and between the components and the borders of the Container
Example
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 5);
for (int i = 0; i < 10; i++) {
panel.add(new JLabel("Label" + i));
}
You could use EmptyBorder
EmptyBorder constructor
public EmptyBorder(int top,
int left,
int bottom,
int right)
top - the top inset of the border
left - the left inset of the border
bottom - the bottom inset of the border
right - the right inset of the border
Example
JPanel panel = new JPanel();
for (int i = 0; i < 10; i++) {
JLabel label = new JLabel("Label" + i);
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
label.setBorder(border);
panel.add(label);
}
If you want to use a LineBorder and an EmptyBorder for margins, you can use a CompoundBorder
A composite Border class used to compose two Border objects into a single border by nesting an inside Border object within the insets of an outside Border object. For example, this class may be used to add blank margin space to a component with an existing decorative border:
CompoundBorder Example
JPanel panel = new JPanel();
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i < 10; i++) {
JLabel label = new JLabel("Label" + i);
label.setBorder(compound);
panel.add(label);
}
There is an abundant number possibilities. Choose your flavor. The whole point it no not try and set size and position to everything, and make use of layout managers and borders and gaps for sizing, spacing etc.
Learn to use the different layout managers at Laying out Components Within a Container
Full example using CompoundBorder and GridLayout(int rows, int cols, int hgap, int vgap)
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CompoundBorderDemo {
public CompoundBorderDemo() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel = new JPanel(new GridLayout(5, 5, 10, 10));
EmptyBorder panelBorder = new EmptyBorder(10, 10, 10, 10);
panel.setBorder(panelBorder);
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i < 25; i++) {
JLabel label = new JLabel("Label" + i);
label.setBorder(compound);
panel.add(label);
}
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CompoundBorderDemo();
}
});
}
}
Try using layouts like GridLayout instead of setting bounds to every label.
it is the simplest solution for your problem.Grid Layout May suit you better.
refer the links below for that..
GRID LAYOUT
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
I'm new to java so bear with me:
I want the size of the window/pane/panel to chance once the tab is clicked/changed.
How would I do/impletement this?
I've done it successfully on a button click/event, but how do I do a tab click/event?
Here is my code: (I'm sorry for any bad/bloated/unnessicary code in advance)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//Class shows how to setup up a tabbed window
public class GUI implements ActionListener
{
static JFrame aWindow = new JFrame("Project");
JTabbedPane myTabs = new JTabbedPane();
JPanel loginMainPanel = new JPanel();
JPanel displayMainPanel = new JPanel();
JPanel editMainPanel = new JPanel();
JLabel loginLabel = new JLabel("Username:");
JTextField loginField = new JTextField();
JLabel loginLabel2 = new JLabel("Password:");
JPasswordField loginPass = new JPasswordField();
JButton displayButton = new JButton("Press This Button");
JButton loginButton = new JButton("Login");
JLabel editLabel = new JLabel("Write a story:");
JTextArea editArea = new JTextArea();
public GUI()
{
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize=theKit.getScreenSize();
aWindow.setBounds(wndSize.width/3, wndSize.height/3, 200, 200); //set position, then dimensions
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(1,1);
Container content = aWindow.getContentPane();
content.setLayout(grid);
createLoginPanel();
createDisplayPanel();
createEditPanel();
myTabs.addTab("Login", loginMainPanel);
myTabs.addTab("Display", displayMainPanel);
myTabs.addTab("Edit", editMainPanel);
myTabs.setSelectedIndex(0);
//myTabs.setEnabledAt(1,false);
myTabs.setEnabledAt(2, false);
content.add(myTabs);
aWindow.setVisible(true);
}
public void createLoginPanel()
{
loginMainPanel.setLayout(null);
loginLabel.setBounds(10, 15, 150, 20);
loginMainPanel.add(loginLabel);
loginField.setBounds(10, 35, 150, 20);
loginMainPanel.add(loginField);
loginLabel2.setBounds(10, 60, 150, 20);
loginMainPanel.add(loginLabel2);
loginPass.setBounds(10, 80, 150, 20);
loginMainPanel.add(loginPass);
loginButton.addActionListener(this);
loginButton.setBounds(50, 110, 80, 20);
loginMainPanel.add(loginButton);
}
public void createDisplayPanel()
{
//Toolkit theKit = aWindow.getToolkit();
//Dimension wndSize = theKit.getScreenSize();
//aWindow.setBounds(20, 20, 20, 20); //set position, then dimensions
displayMainPanel.setLayout(null);
displayButton.addActionListener(this);
displayButton.setBounds(10, 80, 150, 20);
displayMainPanel.add(displayButton);
}
public void createEditPanel()
{
editMainPanel.setLayout(null);
editLabel.setBounds(10, 15, 150, 20);
editMainPanel.add(editLabel);
editArea.setBounds(10, 65, 150, 50);
editMainPanel.add(editArea);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//System.out.println("Working...");
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, 300, 300);
}
//Would the event go here?
}
public static void main(String[] args)
{
GUI tw1 = new GUI();
}
}
Thanks very much :)
James,
but how do I do a tab click/event?
Use a ChangeListener.