I made my own BottomBar with a simple gradient extending JComponent and adjusting the paintComponent() method.
Then I add it to the SOUTH of my JFrame which uses BorderLayout.
Everything looks correct at the beginning.
When I resize the frame the BottomBar gets repainted and set to the new position correctly. The think is, it happens a few milliseconds to late, so that one can see the JFrame 's background for a second.
The funny thing is, that when I set the execution environment to Java-SE 1.6 it works... (instead of 1.7)
Also, Im running it on a mac, if that makes a difference.
Code - JButton Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]){
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Resize Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JButton(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
Code - BottomBar Example
Main:
public class Main {
public static void main(String args[]){
Frame window = new Frame();
window.setSize(500, 400);
window.setVisible(true);
}
}
Frame:
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class Frame extends JFrame{
private static final long serialVersionUID = 1L;
public Frame() {
setLayout( new BorderLayout() );
getContentPane().add( BorderLayout.SOUTH, new BottomBar() );
}
}
BottomBar
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
public class BottomBar extends JComponent {
private static final long serialVersionUID = 1L;
public BottomBar() {
setSize(200, 30);
setPreferredSize( new Dimension(200, 30) );
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint gradient = new GradientPaint(0, 0, new Color(185, 185, 185), 0, getHeight() , new Color(151, 151, 151) );
g2.setPaint(gradient);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setColor( new Color(64, 64, 64) );
g2.drawLine(0, 0, getWidth(), 0);
g2.setColor( new Color(215, 215, 215) );
g2.drawLine(0, 1, getWidth(), 1);
}
}
I am unable to reproduce the effect you describe on 1.6; you might try the sscce below on 1.7. Note, several suggestions for your example:
Avoid setXxxxSize(), as discussed here. If you just want a 30 pixel high bar in SOUTH, override getPreferredSize() as shown below. If you later decide to add components, you'll need to add a layout manager.
#Override
public Dimension getPreferredSize() {
return new Dimension(0, 30);
}
Use pack() to let the Window adopt the preferred sizes of the enclosed components. I've added an arbitrary size JPanel to the CENTER; resize the frame to see how the bar grows horizontally in SOUTH.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/a/13610367/230513 */
public class Main {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("BottomBar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
}, BorderLayout.CENTER);
frame.add(new BottomBar(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
private static class BottomBar extends JComponent {
#Override
public Dimension getPreferredSize() {
return new Dimension(0, 30);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint gradient = new GradientPaint(
0, 0, new Color(185, 185, 185),
0, getHeight(), new Color(151, 151, 151));
g2.setPaint(gradient);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setColor(new Color(64, 64, 64));
g2.drawLine(0, 0, getWidth(), 0);
g2.setColor(new Color(215, 215, 215));
g2.drawLine(0, 1, getWidth(), 1);
}
}
}
Related
I am trying to create a jframe and set a background colour, but also putting in a drawstring. It seems like whenever I use .add, the text appears, but not the background. Without the .add, the background changes, but not the text.
`
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JPanel{
public void paint(Graphics g){
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Serif", Font.PLAIN, 500);
g.setFont(font);
g.setColor(Color.red);
g.drawString("Hello", 300, 900);
}public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame jf=new JFrame();
jf.getContentPane().setBackground(Color.YELLOW);
jf.getContentPane().add(new Test());
jf.setSize(1920,1024);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
`
There's a few ways you can do this...
You could..
Make the Test panel the content panel for the frame...
JFrame jf = new JFrame();
jf.setContentPane(new Test());
jf.getContentPane().setBackground(Color.YELLOW);
jf.setSize(1920, 1024);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You could...
Make the Test panel transparent
JFrame jf = new JFrame();
Test test = new Test();
test.setOpaque(false);
jf.getContentPane().setBackground(Color.YELLOW);
jf.add(test);
jf.setSize(1920, 1024);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You could...
Just set the background color of the Test panel
JFrame jf = new JFrame();
Test test = new Test();
test.setBackground(Color.YELLOW);
jf.add(test);
jf.setSize(1920, 1024);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Regardless of which you do...
You Should...
Call the super method of the paint method
Prefer paintComponent of paint - it's just a lot safer
Only manipulate the UI from the context of the Event Dispatching Thead
For example...
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Serif", Font.PLAIN, 500);
g.setFont(font);
g.setColor(Color.red);
g.drawString("Hello", 300, 900);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame jf = new JFrame();
jf.setContentPane(new Test());
jf.getContentPane().setBackground(Color.YELLOW);
jf.setSize(1920, 1024);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
Set the background color of the Test JPanel, not the JFrame.
Also:
Override paintComponent, not paint
Don't forget to call the super's painting method within your override
Learn and follow Java naming and code formatting conventions. Your code is hard to read and understand as it is currently written.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test3 {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(new MyTest("Hello", Color.RED));
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}
class MyTest extends JPanel {
private static final int PREF_W = 1600;
private static final int PREF_H = 900;
private static final Color BG = Color.YELLOW;
private static final Font FONT = new Font("Serif", Font.PLAIN, 500);;
private String text;
private Color color;
MyTest(String text, Color color) {
this.text = text;
setBackground(BG);
this.color = color;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setFont(FONT);
g.setColor(color);
g.drawString("Hello", 300, 600);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
I have a JPanel in my java code and I want to set its size, I have used JPanel.setSize(500,500); and JPanel.setSize(new Dimension(500,500)); but both are not working. Please tell how I can set the size of JPanel?
Most Swing layout managers respect a component's preferredSize and not its size. You could call setPreferredSize(new Dimension(500, 500)), but this can be overridden later in your code, and can lead to an inflexible GUI. Better to override the JPanel's getPreferredSize() method and return a calculated Dimension that works best in all situations.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
public class PrefSizePanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
public Dimension getPreferredSize() {
// update as per Marco:
if (super.isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// just for fun
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0, 0, Color.red, 20, 20, Color.blue, true));
g2.fillOval(0, 0, 2 * getWidth(), 2 * getHeight());
}
private static void createAndShowGUI() {
PrefSizePanel paintEg = new PrefSizePanel();
JFrame frame = new JFrame("PrefSizePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Which displays as
I need learn the logic how can i change JPanel color which created own Painter method. I create a sample project for illustration;
Issue: Direct color changing code in button action not change anything.
Question 1) Is override the paintComponent method is proper way for paint he JPanel with Gradient colors while panel creation?
Question 2) How can i change the background color of this JPanel with other Gradient color or Direct color?
--CODE--
package tryingproject2;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
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 TryingProject2 {
public static void main(String[] args) {
class ImagePanel extends JPanel{
public void paintComponent( Graphics g ) {
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
Color color1;
Color color2;
color1 = new Color(223,130,24,255);
color2 = new Color(255,255,255,255);
GradientPaint gp = new GradientPaint(0, 0, color1, w, 0, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel userPanel = new ImagePanel();
userPanel.setBounds(100, 40, 200, 200);
userPanel.setLayout(null);
JLabel newLabel = new JLabel("Sample Label");
newLabel.setBounds(50, 10, 100, 100);
userPanel.add(newLabel);
JButton button = new JButton("Change Color To Red");
button.setBounds(100, 300, 200, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userPanel.setBackground(Color.red);
userPanel.repaint();
System.out.println("Button Pressed.");
}
});
frame.add(userPanel);
frame.add(button);
frame.setVisible(true);
}
}
I rearranged some of your code to get rid of other problems.
Here's the GUI I created.
Here's the GUI after I left clicked the button.
I made the following changes to your code.
I moved all of the JFrame code into a run method, so I could get out of static methods and into object-oriented classes and methods as fast as possible.
I added a call to the SwingUtilitiles invokeLater method to ensure that Swing components are created and modified on the Event Dispatch thread.
I created a createMainPanel method to create the main panel. Instead of using ugly null layouts with pixel precision settings, I used a Swing layout, the BorderLayout, to position the components. This allows the user to expand the GUI to fill the screen, as well as the GUI fitting different computers with different screen sizes.
The ImagePanel class is a complete, first-class Java class. That means you can have class fields and class constructors. I provided a way to set the colors from outside the class. Set both colors to the same color if you don't want a gradient.
The paintComponent method of the ImagePanel class should start with a super call, to maintain the Swing Paint chain. The paintComponent method should do nothing but paint. Period. Full stop. Nothing else. I removed the code that had nothing to do with painting.
Looking in the actionPerformed method inside the createMainPanel method, you see how I change one of the gradient colors and perform a repaint. The action listener is the controller of your GUI. Only controller code should change the model (the colors in ImagePanel) or the view (ImagePanel and the JFrame). Always look for the model / view / controller pattern when creating a Swing GUI.
Here's the revised code.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
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.SwingUtilities;
public class TryingProject2 implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TryingProject2());
}
#Override
public void run() {
JFrame frame = new JFrame("Color Gradient Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JPanel imageLabelPanel = new JPanel();
imageLabelPanel.setLayout(new BorderLayout());
final ImagePanel imagePanel = new ImagePanel(new Color(223, 130, 24,
255), new Color(255, 255, 255, 255));
imageLabelPanel.add(imagePanel, BorderLayout.CENTER);
JLabel newLabel = new JLabel("Sample Label");
newLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabelPanel.add(newLabel, BorderLayout.SOUTH);
panel.add(imageLabelPanel, BorderLayout.CENTER);
JButton button = new JButton("Change Color To Red");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
imagePanel.setColor1(Color.RED);
imagePanel.repaint();
System.out.println("Button Pressed.");
}
});
panel.add(button, BorderLayout.SOUTH);
return panel;
}
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 6970287820048941335L;
private Color color1;
private Color color2;
public ImagePanel(Color color1, Color color2) {
this.color1 = color1;
this.color2 = color2;
this.setPreferredSize(new Dimension(200, 200));
}
public void setColor1(Color color1) {
this.color1 = color1;
}
public void setColor2(Color color2) {
this.color2 = color2;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, color1, w, 0, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
}
I've done several inspection and done research on how to make a single panel transparent so that the image underneath it will show but has been unsuccessful with panels on a JTabbedPane. I have setOpaque(false) and setBackground(new Color(0,0,0,20)) on both the panels of the JTabbedPane and also did the same on the JTabbedPane itself. However, I still can't get the image on the back of the tabbed pane to show. What else am I missing here?
tabbePane.java
package tabbedpanetransparencypractice;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
public class tabbedPane extends JTabbedPane{
JPanel tab1panel = new JPanel();
JPanel tab2panel = new JPanel();
public tabbedPane(){
this.setPreferredSize(new Dimension(400,400));
this.setBackground(new Color(0,0,0,20));
this.setOpaque(false);
tab1panel.setBackground(new Color(0,0,0,20));
tab2panel.setBackground(new Color(0,0,0,20));
tab1panel.setOpaque(false);
tab2panel.setOpaque(false);
this.addTab("Tab 1", tab1panel);
this.addTab("Tab 2", tab2panel);
}
}
topPanel.java
package tabbedpanetransparencypractice;
import javax.swing.*;
import java.awt.*;
public class topPanel extends JPanel{
Image myBG = new ImageIcon(getClass().getClassLoader().getResource("Assets/loginBg.jpg")).getImage();
#Override
public void paintComponent(Graphics g){
g.drawImage(myBG,0,0,getWidth(),getHeight(),this);
}
public topPanel(){
addTabbedPane();
}
public void addTabbedPane(){
tabbedPane tabbedpane = new tabbedPane();
this.add(tabbedpane);
}
}
frame.java
package tabbedpanetransparencypractice;
import java.awt.Dimension;
import javax.swing.*;
public class frame extends JFrame{
topPanel myPanel = new topPanel();
public frame(){
this.setPreferredSize(new Dimension(600,600));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.pack();
this.setLocationRelativeTo(null);
addComponents();
}
final void addComponents(){
this.setContentPane(myPanel);
}
}
main.java
package tabbedpanetransparencypractice;
public class main {
public static void main(String[] args) {
frame myFrame = new frame();
}
}
This is the output I get (I want the tab1 and tab2 to be transparent to reveal the bg image underneath)
I'd appreciate any help. Thanks.
First, Swing DOES NOT know how to deal with component's whose background colors are alpha based but which are opaque. Swing only knows how to deal with fully opaque and fully transparent components.
Using alpha based colors will generate weird and random paint artefacts. The simple answer is, you should never apply a alpha based color to a component's background (the only exception is JFrame - thanks Sun :P)
The primary solution is, fake it.
That is, make the component transparent (setOpaque(false)) and paint the background at a reduced alpha level. You can then use a alpha based color (because the component is no longer reliant on the color, as it's transparent), but I tend to just use a AlphaComposite as it's generally easier to control and manipulate.
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
BackgroundPane bp = new BackgroundPane();
bp.setLayout(new BorderLayout());
bp.setBorder(new EmptyBorder(20, 20, 20, 20));
SeeThroughTabbedPane tp = new SeeThroughTabbedPane();
tp.setAlpha(0.5f);
tp.addTab("Tab 1", new TestPane("I be see through"));
tp.addTab("Tab 2", new TestPane("But you can't see me"));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(bp);
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane(String text) {
setOpaque(false);
setLayout(new GridBagLayout());
JLabel label = new JLabel(text);
label.setForeground(Color.WHITE);
add(label);
}
}
public class BackgroundPane extends JPanel {
private BufferedImage bg;
public BackgroundPane() {
try {
bg = ImageIO.read(new File("/Volumes/Disk02/Dropbox/MegaTokyo/megatokyo_omnibus_1_3_cover_by_fredrin-d4oupef 50%.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return bg == null ? new Dimension(200, 200) : new Dimension(bg.getWidth(), bg.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - bg.getWidth()) / 2;
int y = (getHeight() - bg.getHeight()) / 2;
g2d.drawImage(bg, x, y, this);
g2d.dispose();
}
}
}
public class SeeThroughTabbedPane extends JTabbedPane {
private float alpha;
public SeeThroughTabbedPane() {
setOpaque(false);
setAlpha(1f);
}
public void setAlpha(float value) {
if (alpha != value) {
float old = alpha;
this.alpha = value;
firePropertyChange("alpha", old, alpha);
repaint();
}
}
public float getAlpha() {
return alpha;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
}
Remember, anything you added to the JTabbedPane which is still opaque will remain so, not in my TestPane's constructor, I set the panel's opaque state to false
You might also like to take a look at Painting in AWT and Swing and Performing Custom Painting
You might be able to use UIManager.put("TabbedPane.contentAreaColor", new Color(255, 255, 0, 100));
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TransparentTabbedPaneTest {
public JComponent makeUI() {
Color bgc = new Color(110, 110, 0, 100);
Color fgc = new Color(255, 255, 0, 100);
UIManager.put("TabbedPane.shadow", fgc);
UIManager.put("TabbedPane.darkShadow", fgc);
UIManager.put("TabbedPane.light", fgc);
UIManager.put("TabbedPane.highlight", fgc);
UIManager.put("TabbedPane.tabAreaBackground", fgc);
UIManager.put("TabbedPane.unselectedBackground", fgc);
UIManager.put("TabbedPane.background", bgc);
UIManager.put("TabbedPane.foreground", Color.WHITE);
UIManager.put("TabbedPane.focus", fgc);
UIManager.put("TabbedPane.contentAreaColor", fgc);
UIManager.put("TabbedPane.selected", fgc);
UIManager.put("TabbedPane.selectHighlight", fgc);
UIManager.put("TabbedPane.borderHightlightColor", fgc);
JTabbedPane tabs = new JTabbedPane();
JPanel tab1panel = new JPanel();
tab1panel.setBackground(new Color(0, 220, 220, 50));
JPanel tab2panel = new JPanel();
tab2panel.setBackground(new Color(220, 0, 0, 50));
JPanel tab3panel = new JPanel();
tab3panel.setBackground(new Color(0, 0, 220, 50));
JCheckBox cb = new JCheckBox("setOpaque(false)");
cb.setOpaque(false);
tab3panel.add(cb);
tab3panel.add(new JCheckBox("setOpaque(true)"));
tabs.addTab("Tab 1", tab1panel);
tabs.addTab("Tab 2", tab2panel);
tabs.addTab("Tab 3", new AlphaContainer(tab3panel));
JPanel p = new JPanel(new BorderLayout()) {
private Image myBG = new ImageIcon(getClass().getResource("test.png")).getImage();
#Override public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(myBG, 0, 0, getWidth(), getHeight(), this);
}
};
p.add(tabs);
p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TransparentTabbedPaneTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
//https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/
class AlphaContainer extends JComponent {
private JComponent component;
public AlphaContainer(JComponent component) {
this.component = component;
setLayout( new BorderLayout() );
setOpaque( false );
component.setOpaque( false );
add( component );
}
/**
* Paint the background using the background Color of the
* contained component
*/
#Override
public void paintComponent(Graphics g) {
g.setColor( component.getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
}
}
I have a JPanel in my java code and I want to set its size, I have used JPanel.setSize(500,500); and JPanel.setSize(new Dimension(500,500)); but both are not working. Please tell how I can set the size of JPanel?
Most Swing layout managers respect a component's preferredSize and not its size. You could call setPreferredSize(new Dimension(500, 500)), but this can be overridden later in your code, and can lead to an inflexible GUI. Better to override the JPanel's getPreferredSize() method and return a calculated Dimension that works best in all situations.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
public class PrefSizePanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
public Dimension getPreferredSize() {
// update as per Marco:
if (super.isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// just for fun
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0, 0, Color.red, 20, 20, Color.blue, true));
g2.fillOval(0, 0, 2 * getWidth(), 2 * getHeight());
}
private static void createAndShowGUI() {
PrefSizePanel paintEg = new PrefSizePanel();
JFrame frame = new JFrame("PrefSizePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Which displays as