I'm trying to add three rectangles to the center of BorderLayout and I'm completely lost. My finished program needs to increase the height of the rectangle as the sliders move but I'm trying to figure out how to intitally draw these three rectangles to the jpanel. I'm so lost. My code is below.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ShowColors extends JPanel
{
public static void main(String args[])
{
JFrame frame = new JFrame();
JPanel main = new JPanel(new BorderLayout());
main.setSize(2000, 1000);
frame.setContentPane(main);
JPanel jp1 = new JPanel(new GridLayout(0, 1));
JPanel jp2 = new JPanel(new GridLayout(2,3));
JPanel jp3 = new JPanel(new GridLayout(1, 3));
jp1.setPreferredSize(new Dimension(90, 800));
jp2.setPreferredSize(new Dimension(1000, 150));
jp3.setPreferredSize(new Dimension(800, 600));
JRadioButton rb1 = new JRadioButton("Decimal", true);
JRadioButton rb2 = new JRadioButton("Binary");
JRadioButton rb3 = new JRadioButton("Hex");
JRadioButton rb4 = new JRadioButton("Octal");
JButton jb1 = new JButton("RESET");
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
group.add(rb4);
JSlider jRed = new JSlider(0,255);
JSlider jGreen = new JSlider(0,255);
JSlider jBlue = new JSlider(0,255);
jRed.setPaintLabels(true);
jRed.setPaintTicks(true);
jRed.setMinorTickSpacing(5);
jRed.setMajorTickSpacing(50);
jRed.setValue(0);
jGreen.setPaintLabels(true);
jGreen.setPaintTicks(true);
jGreen.setMinorTickSpacing(5);
jGreen.setMajorTickSpacing(50);
jGreen.setValue(0);
jBlue.setPaintLabels(true);
jBlue.setPaintTicks(true);
jBlue.setMinorTickSpacing(5);
jBlue.setMajorTickSpacing(50);
jBlue.setValue(0);
JLabel labelR = new JLabel("Red", JLabel.CENTER);
JLabel labelG = new JLabel("Green", JLabel.CENTER);
JLabel lableB = new JLabel("Blue", JLabel.CENTER);
jp1.add(rb1);
jp1.add(rb2);
jp1.add(rb3);
jp1.add(rb4);
jp1.add(jb1);
jp2.add(labelR);
jp2.add(labelG);
jp2.add(lableB);
jp2.add(jRed);
jp2.add(jGreen);
jp2.add(jBlue);
main.add(jp1, BorderLayout.WEST);
main.add(jp2, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
super.paint(g);
g.drawRect(0, 0, 10, 20);
g.setColor(Color.RED);
g.fillRect(0, 0, 10, 20);
g.drawRect(10, 0, 10, 20);
g.setColor(Color.GREEN);
g.fillRect(10, 0, 10, 20);
g.drawRect(20, 0, 10, 20);
g.setColor(Color.BLUE);
g.fillRect(20, 0, 10, 20);
}
}
here is my layout and i want the rectangles in the center.
I think you just need a simple subclass of JPanel and override paintComponent(). Something like this should get you going:
import javax.swing.*;
import java.awt.*;
public class Canvas extends JPanel {
// TODO member variables for rectangle size/color
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(10,10,100,50);
g.drawRect(10,80,100,50);
}
}
EDIT:
Actually, I guess you really don't need a "Canvas" class, you can just use a plain JPanel as #MadProgrammer suggests. What you do need is a class that will encapsulate the Rectangle behavior, which can just be a simple JComponent that gets added to the JPanel that holds your three rectangles.
Here's a working solution, imports excluded for brevity:
public class ShowColors {
class Rectangle extends JComponent implements ChangeListener {
private JSlider slider;
private Color color;
public Rectangle(JSlider slider, Color color) {
this.slider = slider;
this.color = color;
this.setPreferredSize(new Dimension(250, 250));
slider.addChangeListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int value = slider.getValue();
g.setColor(color);
g.fillRect(10,10,100,value);
}
#Override
public void stateChanged(ChangeEvent arg0) {
this.repaint();
}
}
public ShowColors() {
JFrame frame = new JFrame();
JPanel main = new JPanel(new BorderLayout());
main.setSize(2000, 1000);
frame.setContentPane(main);
JPanel jp1 = new JPanel(new GridLayout(0, 1));
JPanel jp2 = new JPanel(new GridLayout(2, 3));
jp1.setPreferredSize(new Dimension(90, 800));
jp2.setPreferredSize(new Dimension(1000, 150));
JRadioButton rb1 = new JRadioButton("Decimal", true);
JRadioButton rb2 = new JRadioButton("Binary");
JRadioButton rb3 = new JRadioButton("Hex");
JRadioButton rb4 = new JRadioButton("Octal");
JButton jb1 = new JButton("RESET");
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
group.add(rb4);
JSlider jRed = buildSlider();
JSlider jGreen = buildSlider();
JSlider jBlue = buildSlider();
JLabel labelR = new JLabel("Red", JLabel.CENTER);
JLabel labelG = new JLabel("Green", JLabel.CENTER);
JLabel lableB = new JLabel("Blue", JLabel.CENTER);
jp1.add(rb1);
jp1.add(rb2);
jp1.add(rb3);
jp1.add(rb4);
jp1.add(jb1);
jp2.add(labelR);
jp2.add(labelG);
jp2.add(lableB);
jp2.add(jRed);
jp2.add(jGreen);
jp2.add(jBlue);
JPanel canvas = new JPanel();
canvas.setLayout(new FlowLayout());
canvas.setPreferredSize(new Dimension(800, 600));
canvas.add(new Rectangle(jRed, Color.RED));
canvas.add(new Rectangle(jGreen, Color.GREEN));
canvas.add(new Rectangle(jBlue, Color.BLUE));
main.add(jp1, BorderLayout.WEST);
main.add(jp2, BorderLayout.SOUTH);
main.add(canvas, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static JSlider buildSlider() {
JSlider slider = new JSlider(0, 255);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(50);
slider.setValue(50);
return slider;
}
public static void main(String args[]) {
new ShowColors();
}
}
And here's what it looks like:
Don't override paint, painting in Swing is achieved by a delicate and complicated chain of methods, which is easily broken. Instead, override it's paintComponent method instead. See Painting in AWT and Swing for more details
Having said that, don't add all your components to the same panel onto which you want to draw, you'll end up painting underneth all the components. Instead, create a separate JPanel which acts as the paint surface and another JPanel which acts as the controller (containing the controls and the paint surface). Use setters and getters to change the state of the paint surface. See Performing Custom Painting for more details.
Create some kind of "drawable" object, which knows how to paint itself and what it should use to paint itself (the color)
Create some kind of List (in the paint surface class) which can hold the objects which you want to paint. Within in it's paintComponent you will will loop through the list and request that each object paint itself, passing it the Graphics context. Take a look at 2D Graphics for more details
This previous answer may also help
Related
I'm making a Java Swing app and I came across a problem. I want to make a button with an icon on it.
To make it, I first make a rescaled ImageIcon:
studentIcon = new ImageIcon(new ImageIcon(
"D:\\Programming\\Java\\ELearningDesktop\\src\\com\\core\\student.png")
.getImage().getScaledInstance(64, 64, Image.SCALE_SMOOTH));
Then I make a button and set the icon on it:
JButton studentButton = new JButton();
studentButton.setIcon(studentIcon);
studentButton.setFocusable(false);
It works fine, but for some reason the icon on button becomes pixelated every time I hover mouse onto it. After hovering it never becomes smooth unless I rescale the JFrame, so that it probably calls repaint() somewhere and it repaints it.
I use a downloaded look-and-feel but the problem remains if I use the default look-and-feel. Using ImageIcon the same way, but without rescaling does not help - pixilation still appears.
What could be the solution?
Starting point of the program
public class Starter {
public static void main(String[] args) {
FlatLightLaf.install();
EventQueue.invokeLater(()->{
AuthFrame frame = new AuthFrame();
frame.setVisible(true);
});
}
}
AuthFrame
public class AuthFrame extends JFrame {
private JPanel mainPanel;
private LoginPanel loginPanel;
private ImageIcon studentIcon;
private ImageIcon teacherIcon;
public AuthFrame() {
setLayout(new GridBagLayout());
ImageIcon imageIcon = new ImageIcon(new ImageIcon(
"D:\\Programming\\Java\\ELearningDesktop\\src\\com\\core\\tileBackground.jpg")
.getImage().getScaledInstance(321, 333, Image.SCALE_SMOOTH));
mainPanel = new BackgroundPanel(imageIcon.getImage(), BackgroundPanel.TILED,
0f, 0.5f);
add(mainPanel, new GBC(0, 0).setFill(BOTH).setWeights(1, 1));
mainPanel.setLayout(new GridBagLayout());
studentIcon = new ImageIcon(new ImageIcon(
"D:\\Programming\\Java\\ELearningDesktop\\src\\com\\core\\student.png")
.getImage().getScaledInstance(64, 64, Image.SCALE_SMOOTH));
teacherIcon = new ImageIcon(new ImageIcon(
"D:\\Programming\\Java\\ELearningDesktop\\src\\com\\core\\teacher.png")
.getImage().getScaledInstance(64, 64, Image.SCALE_SMOOTH));
loginPanel = new LoginPanel();
mainPanel.add(loginPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setExtendedState(Frame.MAXIMIZED_BOTH);
}
LoginPanel - a private inner class that is used in the AuthFrame
private class LoginPanel extends JPanel {
private JTextField usernameField;
private JPasswordField passwordField;
private JLabel errorLabel;
private JButton studentButton;
private JButton teacherButton;
private JLabel titleLabel;
private boolean forStudent = true;
public LoginPanel() {
setLayout(new GridBagLayout());
setBackground(new Color(255, 255, 255, 181));
studentButton = new JButton();
studentButton.setIcon(studentIcon);
studentButton.setFocusable(false);
//add(studentButton, new GBC(0, 0).setAnchor(GBC.WEST).setInsets(10));
teacherButton = new JButton(teacherIcon);
teacherButton.setFocusable(false);
add(teacherButton, new GBC(0, 0).setAnchor(GBC.WEST).setInsets(10));
titleLabel = new JLabel("<html>Signing in as <b>student</b></html>");
Utils.deriveFontForTo(titleLabel, 24f);
add(titleLabel, new GBC(1, 0).setAnchor(GBC.EAST).setInsets(10));
titleLabel.setVerticalAlignment(JLabel.BOTTOM);
JLabel usernameLabel = new JLabel("Username");
Utils.deriveFontForTo(usernameLabel, 24f);
add(usernameLabel, new GBC(0, 1).setAnchor(GBC.WEST).setInsets(10));
usernameLabel.setHorizontalAlignment(LEFT);
JLabel passwordLabel = new JLabel("Password");
Utils.deriveFontForTo(passwordLabel, 24f);
add(passwordLabel, new GBC(0, 2).setAnchor(GBC.WEST).setInsets(10));
usernameField = new JTextField(15);
Utils.deriveFontForTo(usernameField, 24f);
add(usernameField, new GBC(1, 1).setInsets(10));
passwordField = new JPasswordField(15);
Utils.deriveFontForTo(passwordField, 24f);
add(passwordField, new GBC(1, 2).setInsets(10));
errorLabel = new JLabel();
Utils.deriveFontForTo(errorLabel, 16f);
errorLabel.setForeground(Color.RED);
add(errorLabel, new GBC(1, 3).setAnchor(GBC.WEST).setInsets(2));
errorLabel.setHorizontalAlignment(LEFT);
JButton loginButton = new JButton("Log in");
loginButton.setFocusable(false);
Utils.deriveFontForTo(loginButton, 24f);
add(loginButton, new GBC(1, 4, 1, 1)
.setFill(GridBagConstraints.HORIZONTAL).setInsets(10));
JButton registerButton = new JButton("Sign Up");
loginButton.setFocusable(false);
Utils.deriveFontForTo(registerButton, 24f);
add(registerButton, new GBC(1, 5, 1, 1)
.setInsets(10));
}
}
GBC - a covenience class to use GridBagLayout
package com.core.helpers.graphics;
import java.awt.*;
public class GBC extends GridBagConstraints {
public GBC(int gridX, int gridY){
super.gridx = gridX;
super.gridy = gridY;
}
public GBC(int gridX, int gridY, int gridWidth, int gridHeight){
super.gridx = gridX;
super.gridy = gridY;
super.gridwidth = gridWidth;
super.gridheight = gridHeight;
}
public GBC setAnchor(int anchor){
super.anchor = anchor;
return this;
}
public GBC setWeights(double weightX, double weightY){
super.weightx = weightX;
super.weighty = weightY;
return this;
}
public GBC setFill(int fill){
super.fill = fill;
return this;
}
public GBC setInsets(int k){
this.insets = new Insets(k,k,k,k);
return this;
}
}
Thanks
Screenshots:
first - two buttons are smooth
second - hovered button becomes pixilated
third - button becomes smooth again after resizing frame
it never becomes smooth unless I rescale the JFrame, so that it probably calls repaint() somewhere and it repaints it.
setBackground(new Color(255, 255, 255, 181));
I would guess the above is related to the problem. Swing does not support transparent backgrounds.
Swing expects the component to be opaque, in which case the component is responsible for painting its opaque background.
Or, the component can be non-opaque in which case the parent component is painted first to make sure an opaque background is painted.
If you have transparency then you need to make the component non-opaque and override the paintComponent method and paint the background yourself.
Basic code is:
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);
See Backgrounds With Transparency for more information and a reusable solution so you don't need to use custom painting every time.
Edit:
Looks like my problem was connected to windows scaling, as the marked answer here Java Swing, all images appear pixelated
suggests. Using the marked answer from this link helped me. Here it is: https://stackoverflow.com/a/50566705/12538636
Brute force approach :
By repainting the button's panel every time there's a change in button makes it look smooth all the time. Here's code fragment:
teacherButton.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
mainPanel.repaint();
}
});
studentButton.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
mainPanel.repaint();
}
});
The only little issue remained is that now there's a tiny gap between hovering and button's respond to hovering (changing a color slightly to denote it's hovered).
I'm currently doing a GUI project as you can see below. While designing the UI I encountered a problem with my JLabel. It wouldn't appear as soon as I run the program.
public class Main extends JFrame {
private JFrame mainFrame;
private JPanel parentPanel;
private JPanel sidePanel;
private JLayeredPane layer;
private JPanel info, tri, sqr, rect, circ;
private JLabel infoTF, triLabel, sqrTF, circTF;
public static void main(String[] args) {
Main show = new Main();
}
public Main() {
mainFrame = new JFrame("Geometric Shapes Computation");
layer = new JLayeredPane();
layer.setLayout(null);
layer.setBounds(0,0,700,600);
Color standard = new Color (76 ,41, 211);
Color fg = new Color (204, 204, 204);
Font items = new Font("Century Gothic", Font.BOLD, 12);
triLabel = new JLabel("Triangle");
triLabel.setFont(items);
triLabel.setBackground(standard);
triLabel.setForeground(fg);
triLabel.setVisible(true);
tri = new JPanel();
tri.add(triLabel);
tri.setBackground(Color.ORANGE);
tri.setLayout(null);
tri.setBounds(0, 215, 200, 70);
sqr = new JPanel();
sqr.setBackground(standard);
sqr.setLayout(null);
sqr.setBounds(0, 315, 200, 70);
parentPanel = new JPanel();
parentPanel.setLayout(null);
parentPanel.setSize(700, 600);
sidePanel = new JPanel();
sidePanel.setLayout(null);
sidePanel.setBounds(0,0,200, 600);
sidePanel.setBackground(standard);
sidePanel.add(tri);
layer.add(parentPanel, JLayeredPane.DEFAULT_LAYER);
layer.add(sidePanel, JLayeredPane.PALETTE_LAYER);
layer.add(tri, JLayeredPane.MODAL_LAYER);
mainFrame.add(layer);
mainFrame.setSize(700, 600);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}
If I am understanding your question correctly you are just having issues displaying the label, I was able to show the label by commenting out the tri.setLayout(null);
tri = new JPanel();
tri.add(triLabel);
tri.setBackground(Color.ORANGE);
//tri.setLayout(null);
tri.setBounds(0, 215, 200, 70);
This was able to display the text for me. Hopefully, this helps.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import reactiontimer.ReactionTimer;
class MyPanel1 extends JPanel
{
boolean showEllipse;
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.red);
g2.drawOval(0, 0, 36, 36);
}
}
public class DrawOval extends JFrame implements ActionListener
{
Boolean flag1=false;
Boolean flag2=false;
Boolean flag3=false;
JButton name;
JButton oval;
JButton rectangle;
JPanel centerPanel;
MyPanel1 leftPanel;
JPanel rightPanel;
JLabel centerLabel;
JPanel botPanel;
JLabel label1;
JLabel label2;
JLabel label3;
public static void main(String args[])
{
// [Add Your Name and section number Below]
Gui rt = new Gui("Chengjie Lin, Section 012");
rt.setVisible(true);
}
public DrawOval(String title)
{
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
this.setVisible(true);
Font buttonFont = new Font(Font.SANS_SERIF, Font.BOLD, 24);
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
botPanel=new JPanel();
name = new JButton("Name");
name.setFont(buttonFont);
botPanel.add(name);
//
oval = new JButton("Oval");
oval.setFont(buttonFont);
botPanel.add(oval);
//
rectangle = new JButton("Rectangle");
rectangle.setFont(buttonFont);
botPanel.add(rectangle);
contentPane.add(botPanel, BorderLayout.SOUTH);
Font bigLabelFont = new Font(Font.SANS_SERIF, Font.BOLD, 48);
label1=new JLabel("1");
label1.setFont(bigLabelFont);
label1.setHorizontalAlignment(SwingConstants.CENTER);
label2=new JLabel("2");
label2.setFont(bigLabelFont);
label2.setHorizontalAlignment(SwingConstants.CENTER);
label3=new JLabel("3");
label3.setFont(bigLabelFont);
label3.setHorizontalAlignment(SwingConstants.CENTER);
centerPanel = new JPanel();
leftPanel=new MyPanel1();
rightPanel=new JPanel();
leftPanel.setLayout(new BorderLayout());
rightPanel.setLayout(new BorderLayout());
centerPanel.setLayout(new BorderLayout());
// centerPanel.add(label1, BorderLayout.EAST);
centerPanel.add(label2, BorderLayout.CENTER);
// centerPanel.add(label3, BorderLayout.WEST);
contentPane.add(leftPanel, BorderLayout.EAST);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(rightPanel, BorderLayout.WEST);
name.addActionListener(this);
oval.addActionListener(this);
rectangle.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
String command = e.getActionCommand();
System.out.println(command);
// [Add Menu Code 3]
if (source == name)
{
updateView1();
}
if (source == oval)
{
updateView2();
}
if(source==rectangle){
}
}
void updateView1()
{
// [ADD Center Panel Code 2]
if(flag2==false){
label2.setText("cj");
}else{
label2.setText(null);
}
flag2=!flag2;
repaint();
}
void updateView2()
{
// [ADD Center Panel Code 2]
//leftPanel.add(label1);
if(flag1==false){
}else{
//leftPanel.removeAll();
}
flag1=!flag1;
leftPanel.repaint();
}
}
I am new to the Java.This might be a stupid question to ask.I tried to draw an oval in the leftPanel when the oval button is clicked. But nothing happened when I clicked the Button. Can someone help me out plz?
Your MyPanel1 panel has a size of (0, 0) so there is nothing to paint.
Override the getPreferredSize() method of the class to return the Dimension of your custom painting.
Read the section from the Swing tutorial on Custom Painting for more information and a working example.
I want to make a background image for a game I'm designing but I cant figure out the right way to get the effect I want, I want a background that can be seen behind text etc. basically having the background cover the whole JFrame / JPanel not just one section of the layout (e.g. BorderLayout.Center) I think it does this anyway but if it does do that how do I make the background for those transparent to see the background which is behind...
Confusing i know but I hope someone here understands what I am trying to do and can help... this is my current code. I have been playing around with the background so dont read to much in how i have written it.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JLabel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
ImageIcon banner = new ImageIcon("images/banner.png", "North Background");
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JLabel northpanel = new JLabel();
northpanel.setLayout(new BorderLayout());
northpanel.setIcon(banner);
northpanel.add(new JSeparator(), BorderLayout.PAGE_END);
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.setBackground(Game.getBackgroundColor());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
So if you already have a JPanel that has your image as Background and you want to add another panel over it with your components you can use Opacity to achieve this. Only the components added to this panel will be visible. Here's the code :
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class TransparentPane extends JPanel {
public TransparentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0f));
g2d.setColor(getBackground());
g2d.fill(getBounds());
g2d.dispose();
}
}
Create a class that extends from JPanel and in its paint method draw an image over it.
Now create a class the extends from JFrame and in its constructor set its contentpane to the object of that JPanel class like below. Now you can add components to jframe.
class SimpleTest extends JFrame {
JButton btn = new JButton("A Game");
public SimpleTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new CPane());
getContentPane().setBackground(Color.red);
getContentPane().add(btn, BorderLayout.NORTH);
setSize(new Dimension(300, 300));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleTest();
}
});
}
}
class CPane extends JPanel {
Image back;
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
back = ImageIO.read(getClass().getResource("back.jpg"));
} catch (Exception ex) {
}
g.drawImage(back, 0, 0, this);
}
}
If you want to make a jpanel transparent then do
panel.setOpaque(false);
I am trying to add a JPanel (well, several) to a JLayeredPane. However, when I do so, the paint component method of the JPanel seems to have no effect. An example is included below:
import javax.swing.*;
import java.awt.*;
public class Example {
public static void main(String[] args) {
// This Works as expected
JFrame usingPanel = new JFrame();
JPanel p = new JPanel();
p.add(new BluePanel());
usingPanel.setContentPane(p);
usingPanel.pack();
usingPanel.setVisible(true);
// This makes the frame but does not paint the BluePanel
JFrame usingLayer = new JFrame();
JLayeredPane l = new JLayeredPane();
l.setPreferredSize(new Dimension(200,200));
l.add(new BluePanel(), JLayeredPane.DEFAULT_LAYER);
JPanel p2 = new JPanel();
p2.add(l);
usingLayer.setContentPane(p2);
usingLayer.pack();
usingLayer.setVisible(true);
}
static class BluePanel extends JPanel{
public BluePanel(){
setPreferredSize(new Dimension(200,200));
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 200, 200);
}
}
}
Why is this? and what are the possible solutions?
JLayeredPane does not have a LayoutManager, so you need to set the location and size of your panels yourself.
See the tutorial
you hardcoded the size on the screen and have to change from
g.fillRect(0, 0, 200, 200);
to
g.fillRect(0, 0, getWidth(), getHeight());
(a minor change) add the method
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
and then remove of code line setPreferredSize(new Dimension(200,200));