I want to add a jPanel which is semi transparent. But other components which are placed inside the jPanel such as buttons and labels should be displayed with 100% opacity. I am using netbeans to design the GUIs. Normally i drag and drop the swing components in the palette to design the GUI(I don't code them). I can't see any property in properties window to achieve this. Please help me. As I am quite new to java please give me a detailed answer. Thanks in advance.
You can use
JPanel.setBackground(Color bg);
to make the panel semi-transparent. What matter is the color's property.
You can construct a color with alpha values to set the transparent degree of the color.
panel.setBackground(new Color(213, 134, 145, 123));
The last parameter is actual the alpha value and you can adjust it to see the effect.
Here is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PanelTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
PanelTest test = new PanelTest();
test.createUI();
}
};
SwingUtilities.invokeLater(runnable);
}
public void createUI(){
JFrame frame = new JFrame("Panel Test");
JPanel panel = new JPanel();
panel.setBackground(new Color(213, 134, 145, 123));
JButton button = new JButton("I am a button");
JLabel label = new JLabel("I am a label");
label.setFont(new Font("Arial", Font.BOLD, 15));
JTextField textField = new JTextField();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(Box.createVerticalStrut(20));
panel.add(label);
panel.add(Box.createVerticalStrut(20));
panel.add(textField);
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
BottomPanel buttomPanel = new BottomPanel();
buttomPanel.add(panel);
frame.add(buttomPanel,BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class BottomPanel extends JPanel{
#Override
protected void paintComponent(Graphics g) {
for (int y = 0; y < 200; y = y + 20) {
g.drawString("I am the string on the bottom", 5, y);
}
}
}
}
Here is the effect and hope it can help you.
You can simply create your jPanel using drag and drop, as you always do and then for changing the panel's color and making it transparent or semi-transparent you can use this code:
panel.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));
You can change the color by changing first three parameters of Color constructor, which represent RGB and you can change transparency by changing fourth parameter, which is the alpha value of color.
Related
Hello I'm newish to Java and have recently attempted to go from using netbeans IDE to using raw code for making my JIternalFrames, but it displays either with no components or not at all.
To correct the issue I have attempted to move around the order in which I set up components for example I originally had it as initvariables > addcomponentstopanes > setsizes/text > setvisible, i've also tried using repaint() and revalidate() to no avail.
package tester;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestChunk extends javax.swing.JInternalFrame
{
JInternalFrame consumeWindow;
JScrollPane coScrollPane;
JPanel panel;
JButton eatBerriesButton, eatMushroomsButton, eatFishButton;
public void startComponents()
{
consumeWindow = new JInternalFrame("Consume Panel");
panel = new JPanel();
eatBerriesButton = new JButton();
eatMushroomsButton = new JButton();
eatFishButton = new JButton();
GridLayout myLayout;
consumeWindow.setBorder(null);
consumeWindow.setResizable(true);
myLayout = new GridLayout(0, 3, 10, 5);
panel.setLayout(myLayout);
consumeWindow.setSize(500, 325);
panel.setSize(500, 650);
eatBerriesButton.setBounds(5, 5, 150, 50);
eatMushroomsButton.setBounds(5, 60, 150, 50);
eatFishButton.setBounds(5, 105, 150, 50);
panel.add(eatMushroomsButton);
panel.revalidate();
panel.repaint();
panel.add(eatBerriesButton);
panel.revalidate();
panel.repaint();
panel.add(eatFishButton);
panel.revalidate();
panel.repaint();
coScrollPane = new JScrollPane(panel);
coScrollPane.setSize(500, 325);
coScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
coScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
consumeWindow.setContentPane(coScrollPane);
consumeWindow.revalidate();
consumeWindow.repaint();
consumeWindow.setVisible(true);
consumeWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The problem is my newest JInternalFrame (The one written entirely in code) isn't displaying and when I do get it to display it doesn't have any of it's components. The internal frame as it currently is should contain 3 buttons within a JScrollPane with about a 5 gap between each button. (If you'd like more code for clarification feel free to request it).
When I try to add a JButton and a JLabel into a JFrame, they both conflict each other in which all the JButtons would disappear and only the JLabel would be visible. The JLabel for some reason would go to the left most side of the JFrame instead of the desired location I set it to go. I'm new to GUI related material and I'm willing to learn from these mistakes.
Here is my code:
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.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Windowb extends JFrame{
static String title = "This is a JFrame";
static int width = 500;
static int height = 400;
private static final int BUTTON_LOCATION_X = 46;
private static final int BUTTON_LOCATION_Y = 80;
public static void main(String[]args){
Windowb simple = new Windowb(title, width, height);
JPanel p = new JPanel();
p.setLayout(null);
JLabel c1 = new JLabel("Name: ");
JButton b1 = new JButton("Name:");
JButton b2 = new JButton("Grade:");
JButton b3 = new JButton("GPA");
b1.setBounds(BUTTON_LOCATION_X, BUTTON_LOCATION_Y, 90, 20);
b2.setBounds(50, 170, 90, 20);
b3.setBounds(50, 240, 90, 20);
c1.setLocation(100, 250);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "ActionListener is working!");
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "The second one works too!");
}
});
b3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "Surprise!");
}
});
p.add(b1);
p.add(b2);
p.add(b3);
simple.add(p);
simple.add(c1);
}
public Windowb(String t, int w, int h){
setVisible(true);
setResizable(true);
setSize(w, h);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(500, 100);
setTitle(t);
}
}
You probably should use a LayoutManager. See the layout manager tutorial: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
setBounds() is used by the layout manager to position components. You can set the LayoutManager to null and position the components yourself but stuff like window resizing isn't handled for you that way (ie. components and space aren't scaled accordingly). If you want to maintain your sanity then don't use the build in GridBag layout! It will drive you insane! For more complex layouts use http://www.miglayout.com/ or http://www.jgoodies.com/freeware/libraries/forms/ . For simple layouts use layoutmanagers like BorderLayout.
If you really don't want to use a layoutmanager then use a JPanel. A JFrame can only hold a single component so thats your problem. Put a JPanel inside the JFrame and put your components in the JPanel.
I have in a JFrame, one main JPanel, and only in the left half of JFrame, a second JPanel.
When i click in a JButton in a main JPanel, the second JPanel becomes visible.
I'm going to create a paintComponent in main JPanel class, to draw a immage, and one circle and all work.
The problem arises when I go to change a color of this circle. I change R-G-B every time that i repaint();
The color of circle change , but if I click on a JButton in main JPanel to open the Second JPanel I saw it for a little time and it becomes invisible.
I suppose because it redraws the main JPanel above the second..
How i fix this problem? Thank's you!.
P.S.
I use super.paintComponent(g);
and in the costructor of JPanel i do this.repaint() to bring up immediately the components of the first page, otherwise I should minimize and make the window reappear.
//Panel extends JPanel
//at the end of Constructor
this.repaint();
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
setOpaque(true);
g.drawImage(img, 210, 50, 580,580,this);
g.setColor(Color.black);
g.drawOval(480,40,40,40);
g.fillOval(480,40,40,40); //Various..
repaint(); //With this i can't saw the second JPanel that it's overlapped
} //whit the main JPanel
Alessandro Amedei, Florence.
27-01-2015
This is my code..
MAIN PANEL
package a;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
// #author Alessandro Amedei
public class FirstPanel extends JPanel{
Image img = null;
FirstPanel(){
LotL LotL = new LotL();
FPListener FPL = new FPListener();
this.setVisible(true);
this.setSize(1000,1000);
this.setLayout(null);
this.setBackground(Color.white);
this.addMouseListener(FPL);
Main.f1.add(this);
Button start = new Button("Start Game!");
Button options = new Button("Options");
start.setVisible(true);
start.setSize(200,80);
start.setLayout(null);
start.setLocation(400,650);
start.addActionListener(LotL);
start.setBackground(Color.green);
start.identificatore=1;
this.add(start);
options.setVisible(true);
options.setSize(200,70);
options.setLayout(null);
options.setLocation(400,750);
options.addActionListener(LotL);
options.setBackground(Color.green);
options.identificatore=2;
this.add(options);
img= Toolkit.getDefaultToolkit().getImage("ok.jpg");
this.repaint();
}
int B=30;
int R=80;
int G=90;
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
setOpaque(true);
g.drawImage(img, 210, 65, 580,580,this);
g.setColor(new Color(R,G,B));
g.drawOval(455,20,90,90);
g.fillOval(455,20,90,90);
if(B==150)
B=0;
if(R==170)
R=0;
if(G==160)
G=0;
try {
Thread.sleep(5);
} catch (InterruptedException ex) {
}
B++;
R++;
G++;
repaint();
}
}
SECOND PANEL
package a;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
//#author Alessandro Amedei
public class OptionsPanel extends JPanel {
static JSlider rgb1 = new JSlider(0,255);
static JSlider rgb2 = new JSlider(0,255);
static JSlider rgb3 = new JSlider(0,255);
static SpinnerNumberModel noba = new SpinnerNumberModel();
static JTextField fg1 = new JTextField();
static JTextField fg2 = new JTextField();
OptionsPanel(){
this.setVisible(false);
this.setSize(350,1000);
this.setLayout(null);
this.setBackground(new Color(255,150,0));
Main.f1.add(this);
JSpinner nob = new JSpinner(noba);
JLabel l1= new JLabel("Options");
JLabel l2= new JLabel("Background Color");
JLabel g1= new JLabel("Left Button Color");
JLabel g2= new JLabel("Right Button Color");
JLabel nob1 = new JLabel("Number of Checkers for Player");
JLabel ng1= new JLabel("Name of Left Player");
JLabel ng2= new JLabel("Name of Right Player");
rgb1.setVisible(true);
rgb1.setSize(240,40);
rgb1.setLocation(55,90);
this.add(rgb1);
rgb1.setBackground(new Color(rgb1.getValue(),255,0));
rgb1.addChangeListener(new SListener());
rgb2.setVisible(true);
rgb2.setSize(240,40);
rgb2.setLocation(55,180);
this.add(rgb2);
rgb2.setBackground(new Color(255,0,rgb1.getValue()));
rgb2.addChangeListener(new SListener());
rgb3.setVisible(true);
rgb3.setSize(240,40);
rgb3.setLocation(55,270);
this.add(rgb3);
rgb3.setBackground(new Color(0,rgb1.getValue(),255));
rgb3.addChangeListener(new SListener());
nob.setVisible(true);
nob.setSize(60,30);
nob.setLocation(55,360);
noba.setMaximum(10);
noba.setMinimum(3);
noba.setValue(3);
this.add(nob);
fg1.setVisible(true);
fg1.setSize(150,30);
fg1.setLocation(55,450);
this.add(fg1);
fg2.setVisible(true);
fg2.setSize(150,30);
fg2.setLocation(55,540);
this.add(fg2);
Font f= new Font("arial",Font.ITALIC,20);
Font f2= new Font("arial",Font.BOLD,13);
l1.setVisible(true); //Etichetta OPTIONS
l1.setSize(70,20);
l1.setLocation(140,10);
l1.setFont(f);
this.add(l1);
l2.setVisible(true);
l2.setSize(120,30);
l2.setLocation(55,65);
l2.setFont(f2);
this.add(l2);
g1.setVisible(true);
g1.setSize(150,30);
g1.setLocation(55,155);
g1.setFont(f2);
this.add(g1);
g2.setVisible(true);
g2.setSize(150,30);
g2.setLocation(55,245);
g2.setFont(f2);
this.add(g2);
nob1.setVisible(true);
nob1.setSize(200,30);
nob1.setLocation(55,335);
nob1.setFont(f2);
this.add(nob1);
ng1.setVisible(true);
ng1.setSize(200,30);
ng1.setLocation(55,425);
ng1.setFont(f2);
this.add(ng1);
ng2.setVisible(true);
ng2.setSize(200,30);
ng2.setLocation(55,515);
ng2.setFont(f2);
this.add(ng2);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
Ok so, If I change the color of the circle in the main JPanel using repaint(); i can't show the Options Panel I think because of the refresh caused by the repaint() method of the Main JPanel.
How I can change the color of the circle in Main JPanel and visualize the Options Panel at the same time? (exluding creating another panel where I draw the circle).
Sorry for my bad English!
Thank's you very much.
Alessandro Amedei,Florence.
I am very new in Java Swing develompment and I have the following problem.
I have to create a JFrame window that have a background immage.
So I have perform the following operation to do it:
1) I have create a class named JPanelWithBackground that extends JPanel:
package com.test.login;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class JPanelWithBackground extends JPanel {
private Image backgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
// g.drawImage(backgroundImage, 0, 0, this);
g.drawImage(backgroundImage, 0, 0, 550, 230, this);
}
}
As you can see this class read an immage file and put its reference into an Image object named backgroundImage and then draw it on a Graphics object.
2) Then I have create a class named LoginFrame2:
package com.test.login;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.Dimension;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu.Separator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import net.miginfocom.swt.MigLayout;
import org.jdesktop.application.SingleFrameApplication;
public class LoginFrame2 extends SingleFrameApplication {
private static final int FIXED_WIDTH = 550;
private static final Dimension INITAL_SIZE = new Dimension(FIXED_WIDTH, 230);
public static void main(String[] args) {
System.out.println("DENTRO: LoginFrame() ---> main()");
launch(LoginFrame2.class, args);
}
#Override
protected void startup() {
// TODO Auto-generated method stub
System.out.println("Inside startup()");
JFrame mainFrame = this.getMainFrame(); // main JFrame that represents the Windows
mainFrame.setTitle("Chilli Login");
mainFrame.setPreferredSize(INITAL_SIZE);
mainFrame.setResizable(false);
Container mainContainer = mainFrame.getContentPane(); // main Container into the main JFrame
// JPanel creation and settings of the MigLayout on it:
// JPanel externalPanel = new JPanel();
JPanelWithBackground externalPanel = null;
try {
externalPanel = new JPanelWithBackground("/home/andrea/Immagini/logo2.jpg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
externalPanel.setLayout(new net.miginfocom.swing.MigLayout("fill"));
externalPanel.add(new JLabel("Username"), "w 50%, wrap");
JTextField userNameTextField = new JTextField(20);
externalPanel.add(userNameTextField, "w 90%, wrap");
externalPanel.add(new JLabel("Password"), "w 50%, wrap");
JTextField pswdTextField = new JTextField(20);
externalPanel.add(pswdTextField, "w 90%, wrap");
JButton loginButton = new JButton("Login");
externalPanel.add(loginButton, "w 25%, wrap");
mainContainer.add(externalPanel);
//mainFrame.add(mainContainer);
show(mainFrame);
}
}
This class extends SingleFrameApplication abstract class of the JDesktop Swin framework that provide me a JFrame istance.
This class simply create the JPanelWithBackground object by the line:
externalPanel = new JPanelWithBackground("/home/andrea/Immagini/logo2.jpg");
and put in this object some Swing component.
This is my result:
My doubt/problem is: as you can see the JLabel that show the string Password is on the red part of the immage (of my chilli logo) and so is not very readable.
What can I do to make it more readable? For example can I set in some way that the background of my JLabel have to be white?
Tnx
Andrea
You could set the background of the JLabel, but that would look ugly. I would suggest just changing the foreground of only the Password label to be white. Possibly increase the size of font of both labels as well to help readability.
JLabel password = new JLabel("Password");
password.setForeground(Color.WHITE);
More extreme mods: would be to extend the label to output white text that is outlined by black, or to use images for the words in nice fonts that have transparency.
EDIT:
Here is how to set the background to white.
password.setBackground(Color.WHITE);
password.setOpaque(true);
You could change the opacity of the back ground image...
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
// Draw the background image.
// g.drawImage(backgroundImage, 0, 0, this);
g2d.setComposite(AlphaComposite.SrcOvr.derive(0.5f));
g2d.drawImage(backgroundImage, 0, 0, 550, 230, this);
g2d.dispose();
}
I want the racket to be positioned by using the getWidth method for the gamePanel, but it returns 0. It works fine for the frame, and it worked for the panel as well, but I decided to rewrite alot of the code and now I cant get it to work. Help is appreciated :)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
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;
public class Oppgave1 extends JFrame {
public static void main(String[] args) {
JFrame frame = new Oppgave1();
frame.setTitle("Oppgave 1");
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private JLabel jlbBallCount = new JLabel("Ballcount");
private JLabel jlbTimer = new JLabel("Timer");
private JButton jbtNewBall = new JButton("New Ball");
private Racket racket;
private Ball ball;
public Oppgave1() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(jlbBallCount);
buttonPanel.add(jlbTimer);
buttonPanel.add(jbtNewBall);
JPanel gamePanel = new JPanel();
gamePanel.add(racket = new Racket (100, 60));
gamePanel.add(ball = new Ball(10, 3, racket));
this.add(gamePanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void paint(Graphics g){
racket.draw(g);
ball.draw(g);
}
}
Don't override the paint() method of a JFrame.
You added the racket and ball to the game panel. The game panel will now paint these components automatically.
If you want to be able to move these components then you must set the layout to null and initially set the bounds of the components. Then when you want to move the component you just invoke the setLocation() method and Swing will paint the component in its new position.