Java swing jbutton background

Java swing custom background

I have a JFrame on which I have some panels, each containing different items. How can I set the frame background ? I mean, if I set only the background, without adding the items, the background is the one I wanted, but if I add the items, the background is clear. Likewise, if I first set the background of one panel and then insert some objects into it, the item does not appear on the frame, the frame is colored with the background I chose. Could you show me the easiest way to set a background color to a panel/frame that already has items? Thanks. I would like to set a custom bacground color. If the only way is to set a background Image, I will go for that. EDIT : I want a single background color, not more.

3 Answers 3

I had made a sample program for you, do let me know, if you want something other than this. I had done it both ways, you can set a new Color to the Background without any Item on the JPanel by pressing the JButton, or you can first add Item to the JPanel and then change the Background Color, this is working fine. Seems like your question is a bit unclear as to what is expected, and what actually is happening. Do let me know, if you want something else, other than this.

Moreover, as you add Items to the already displayed JPanel, always revalidate() and repaint() your JPanel after that, for changes to take effect.

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AddItemOrColor extends JFrame < private JPanel contentPane; private JButton modifyItemButton; private JButton modifyColorButton; private ActionListener action; private int count = 0; private Color[] color = < Color.RED, Color.BLUE, Color.GRAY, Color.WHITE, Color.CYAN, Color.PINK, Color.DARK_GRAY, Color.ORANGE, Color.MAGENTA >; public AddItemOrColor() < setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationByPlatform(true); contentPane = new JPanel(new FlowLayout(FlowLayout.LEFT, 3, 3)); //contentPane.setMargin(new Insets(10, 10, 10, 10)); contentPane.setBackground(Color.BLUE); modifyItemButton = new JButton("MODIFY CONTENT"); modifyColorButton = new JButton("MODIFY COLOR"); action = new ActionListener() < public void actionPerformed(ActionEvent ae) < JButton button = (JButton) ae.getSource(); if (count == 9) count = 0; if (button == modifyItemButton) < contentPane.add(new JLabel("LABEL " + count)); >else if (button == modifyColorButton) < contentPane.setBackground(color[count]); >contentPane.revalidate(); contentPane.repaint(); count++; > >; modifyItemButton.addActionListener(action); modifyColorButton.addActionListener(action); add(modifyColorButton, BorderLayout.PAGE_START); add(contentPane, BorderLayout.CENTER); add(modifyItemButton, BorderLayout.PAGE_END); setSize(400, 400); setVisible(true); > public static void main(String. args) < SwingUtilities.invokeLater(new Runnable() < public void run() < new AddItemOrColor(); >>); > > 

Источник

Customizing JButton Background in Swing

Utilize this instance to decide how to modify the UI or model when a state change event occurs. As for changing the background color of a button, your code seems accurate since the method ‘setBackground color’ performs as intended. However, you are generating several instances of the game, causing its state to always be in its default state upon inspection.

Swing : Setting JButton’s background

Red Buttons

import java.awt.*; import javax.swing.*; class ColoredButtons < ColoredButtons() < JPanel gui = new JPanel(new GridLayout(1,0,5,5)); JButton one = new JButton("One"); one.setBackground(Color.RED); JButton two = new JButton("Two"); two.setBackground(Color.RED); gui.add(one); gui.add(two); JOptionPane.showMessageDialog(null, gui); >public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < public void run() < new ColoredButtons(); >>); > > 

Here is my SSCCE featuring red buttons and a metal PLAF.

This leads me to ask again, do you have an SSCCE available? Additionally, which PLAF have you implemented?

The control of the Jbutton background is based on the look-and-feel applied. Altering the background may require adjustments to be made.

Attempt disabling border painting and enabling opacity.

account_btn.setBorderPainted(false); account_btn.setOpaque(true); 

Change Background Color of Frame on Button Click Event in JAVA

How to get a white background in Java Swing JButton in Windows 10

setContentAreaFilled(false) does the magic here.

Читайте также:  Python smtplib connection unexpectedly closed

As seen on Windows 10.

The code employs a cyan panel in the middle to differentiate it from the default light gray of the PLAF. This allows the button to be set to a color different from its container. However, if the intention is to have the button match the color of its parent container, the intermediary panel can be omitted.

import java.awt.*; import javax.swing.*; import javax.swing.border.EmptyBorder; public class Test2 < public Test2() < // Frame, orange background JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel(); JButton button = new JButton("Button 2"); button.setContentAreaFilled(false); panel.setBackground(Color.ORANGE); // Add Components frame.add(panel); panel.setBorder(new EmptyBorder(10,100,10,100)); JPanel buttonColorPanel = new JPanel(new GridLayout()); // adjust color as needed buttonColorPanel.setBackground(Color.CYAN); panel.add(buttonColorPanel); buttonColorPanel.add(button); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); >public static void main(String[] args) < try < UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); >catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) < ex.printStackTrace(); >Test2 t = new Test2(); > > 

Apart from being a good programming habit, I have made some additional code modifications that do not affect the final result. Furthermore, it is recommended to initiate Swing GUIs on the EDT. Best regards.

JButton button2 = new JButton("Button 2"); panel2.setBackground(Color.WHITE); button2.setBackground(Color.WHITE); button2.setContentAreaFilled(false); button2.setOpaque(true); button2.setBorder(new LineBorder(Color.BLACK,1)); button2.setFocusPainted(false); 

Java — Button background not changing, I do not know in what part of the execution flow you intend to change the background color of a button, but at first sight, you code looks

How to change the button backgrounds inside JOptionPane

There is no direct way to do this.

In case you’re interested in attempting it, you’ll have to refer to the JOptionPane API to learn how to create and exhibit a JOptionPane manually, without relying on the showXXX approaches.

With this method, you can gain entry to the real JDialog and subsequently employ Darryl’s SwingUtils to modify the background of the specific buttons.

The code would be something like:

JButton ok = SwingUtils.getDescendantOfType(JButton.class, dialog, "Text", "Ok"); ok.setBackground(. ); 

The easiest way is to design a custom JDialog and customize the button features as per your preference.

In showOptionDialog , it is possible to utilize customized buttons that possess unique attributes. Although it may not be the optimal approach, it is a functional solution.

JButton button = new JButton("OK"); button.setBackground(Color.BLACK); button.setForeground(Color.WHITE); button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent actionEvent) < JOptionPane.getRootFrame().dispose(); >>); JButton[] buttons = < button >; OptionPane.showOptionDialog(null, "Test Message", "Dialog", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(), buttons, buttons[0]); 

Design Button in Java (like in CSS), Swing has a pluggable Look&Feel which allows to alter the appearance of its widgets by means of a ComponentUI (in this case: a ButtonUI ).

Button background not changing

By creating numerous instances of both Reversi and Reversi x = new Reversi() , the game state is consistently in its default state upon inspection.

It appears that you are struggling to distinguish between the operational mechanisms of a console (linear) program and a GUI-based (event-driven) program.

To begin, instantiate your Reversi as a single instance field within your class. Then, whenever a state change event occurs, utilize this instance to ascertain the appropriate updates to make to either the UI or model.

It’s not clear at what point in the execution flow you plan to modify the button’s background color, but your code seems correct at first glance. This is because the setBackground color method does precisely what it claims to do.

Are you attempting to set the background within a listener’s callback function on a component using the Event Dispatch Thread? Or are you setting the background from a separate thread?

Make sure to verify that the isOpaque component has its property set to true using the public void setOpaque(boolean isOpaque) mutator method. Occasionally, this can be the root cause of the issue.

Читайте также:  Configure php mysql php ini

Changing the background color of JButton always shows as grey, Your title says you want to change the background of a JButton, but your example is changing the color of a JPanel. It could be the background

Источник

How to change the background color of a Jbutton on click

I’m trying to change the color of a JButton when you click on it, but a blue color appears instead of the one I wrote about. Goal: The goal is that when you click on the button the color change I did several searches, but each time a blue font appeared. I tried overide paintComponent, several alternatives such as this.getModel, but nothing works. My button class:

package com.tralamy.lancherX.display; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TButton extends JButton < private Color hoverColor = Display.LIGHT_GRAY; private Color pressColor = Display.LIGHT_DARK; private Color firstColor; private Color basic; private MouseAdapter hoverAdapter = new MouseAdapter() < @Override public void mouseEntered(MouseEvent e) < basic = firstColor; TButton.this.setBackground(hoverColor); >@Override public void mouseExited(MouseEvent e) < TButton.this.setBackground(basic); >>; private MouseAdapter pressAdapter = new MouseAdapter() < @Override public void mousePressed(MouseEvent e) < TButton.this.setBackground(pressColor); super.mousePressed(e); >@Override public void mouseReleased(MouseEvent e) < TButton.this.setBackground(basic); super.mouseReleased(e); >>; public TButton (String text) < super(text); init(); >public TButton (Icon icon) < super(icon); init(); >public TButton () < super(); init(); >private void init() < firstColor = this.getBackground(); setBorder(null); setBorderPainted(false); setContentAreaFilled(false); setOpaque(false); setFocusPainted(false); setPressedIcon(new ImageIcon()); >@Override public void setBackground(Color bg) < super.setBackground(bg); firstColor = bg; >public void setHover() < this.addMouseListener(hoverAdapter); >public void removeHover() < this.removeMouseListener(hoverAdapter); >public void setPress() < this.addMouseListener(pressAdapter); >public void removePress() < this.removeMouseListener(pressAdapter); >public void setHoverColor(Color color) < hoverColor = color; >public Color getHoverColor() < return hoverColor; >public Color getPressColor() < return pressColor; >public void setPressColor(Color pressColor) < this.pressColor = pressColor; >> 
private JPanel menuPanel() < mp = new JPanel(); setPercentWidth(mp, 25); mp.setBackground(LIGHT_GRAY); mp.setLayout(new BorderLayout()); JPanel userSection = new JPanel(); userSection.setLayout(new GridBagLayout()); setPercentHeight(userSection, 5); userSection.setPreferredSize(new Dimension(userSection.getWidth(), 0)); userSection.setBackground(LIGHT_DARK); userIconButton.setHorizontalAlignment(SwingConstants.CENTER); userName.setHorizontalAlignment(SwingConstants.CENTER); userIconButton.setBorder(new EmptyBorder(0,0,0,10)); userSection.add(userIconButton); userSection.add(userName); menuButtons.add(new TButton("Library")); menuButtons.add(new TButton("Store")); menuButtons.add(new TButton("Friends")); menuButtons.add(new TButton("News")); JPanel menuSection = new JPanel(); menuSection.setLayout(new BoxLayout(menuSection, BoxLayout.Y_AXIS)); menuSection.setOpaque(false); for (TButton button : menuButtons) < button.setAlignmentX(TButton.CENTER_ALIGNMENT); button.setFont(App.setSemiBoldNunito(48)); button.setForeground(SUPER_SUPER_LIGHT_GRAY); button.setBackground(SUPER_LIGHT_GRAY); button.setBorder(null); button.setBorderPainted(true); button.setContentAreaFilled(true); button.setOpaque(true); button.setHoverColor(DARK_GRAY); button.setHover(); button.setPressColor(LIGHT_DARK); button.setPress(); TButton marginLabel = new TButton(); marginLabel.setSize(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN); marginLabel.setMaximumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN)); marginLabel.setMinimumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN)); setPercentWidth(button, 20); menuSection.add(marginLabel); menuSection.add(button); >mp.add(menuSection); mp.add(userSection, BorderLayout.SOUTH); return mp; > 

Источник

Using JButton to change background color in JFrame

I’m writing a program that uses JButton. When the user clicks a button, the background should change color, but the JFrame can’t be accessed from the actionPerformed() method. Can someone please tell me how to make it work?

import java.awt.event.*; import java.awt.*; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JPanel; public class HandlerClass implements ActionListener < public static void main(String[] args)< HandlerClass handler = new HandlerClass(); final JFrame f = new JFrame("Testing out these JPanels"); f.setSize(400, 100); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.setLayout(new GridLayout(2, 3)); JButton b = new JButton("button 1"); b.addActionListener(new HandlerClass()); JButton butt = new JButton("button 2"); JButton bug = new JButton("button 3"); JButton button = new JButton("button 4"); JButton button5 = new JButton("button 5"); JButton button6 = new JButton("button 6"); JPanel p = new JPanel(); p.setVisible(true); JPanel pnl = new JPanel(); p.add(b); p.add(butt); p.add(bug); pnl.add(button); pnl.add(button5); pnl.add(button6); f.add(p, BorderLayout.CENTER); f.add(pnl, BorderLayout.SOUTH); f.setVisible(true); f.setBackground(Color.RED); >public void actionPerformed(ActionEvent e) < f.setBackground(Color.WHITE); >> 

3 Answers 3

  1. Don’t write all your code in a single huge main method. That’s for rank beginner programs, and if you want your code to do more than hello world, you’re going to have to make it a true OOPs program.
  2. Create a class with non-static fields and methods.
  3. Have your ActionListener call a method that in its body changes the background color of your main JPanel, the one that you add to the JFrame’s contentPane.
  4. Consider using anonymous inner listener classes, and then off-load the meat of the listener code to a separate method, either in your GUI or in a control class.
Читайте также:  Проверьте является ли число простым питон

    Move the JFrame instance outside the main body so that it becomes an instance variable as such:

public class HandlerClass < private JFrame frame; public HandlerClass() < . >> 
public class HandlerClass < public HandlerClass() < final JFrame frame = new JFrame(); JButton button = new JButton(); . button.addActionListener(new ActionerListener() < @Override public void actionPerformed(ActionEvent e)< frame.setBackground(Color.WHITE); >> > > 
JFrame can't be accessed from the actionPerformed() 

The solution is, You cannot access a local variable from another method Take a look at here and here

Now the important thing: You have two JPanel s over your JFrame . So if you change the color of the JFrame , then you will not be able to see the color change. So my suggestion is change the color of the JPanel . Take the example of the code below:

import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridBagLayout; import javax.swing.JButton; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class HandlerClass extends JFrame < private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) < EventQueue.invokeLater(new Runnable() < public void run() < try < HandlerClass frame = new HandlerClass(); frame.setVisible(true); >catch (Exception e) < e.printStackTrace(); >> >); > /** * Create the frame. */ public HandlerClass() < setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[]; gbl_contentPane.rowHeights = new int[]; gbl_contentPane.columnWeights = new double[]; gbl_contentPane.rowWeights = new double[]; contentPane.setLayout(gbl_contentPane); JButton btnRed = new JButton("Red"); GridBagConstraints gbc_btnRed = new GridBagConstraints(); gbc_btnRed.insets = new Insets(0, 0, 5, 5); gbc_btnRed.gridx = 3; gbc_btnRed.gridy = 1; contentPane.add(btnRed, gbc_btnRed); JButton btnBlue = new JButton("Blue"); GridBagConstraints gbc_btnBlue = new GridBagConstraints(); gbc_btnBlue.insets = new Insets(0, 0, 5, 0); gbc_btnBlue.gridx = 5; gbc_btnBlue.gridy = 1; contentPane.add(btnBlue, gbc_btnBlue); JButton btnWhite = new JButton("White"); GridBagConstraints gbc_btnWhite = new GridBagConstraints(); gbc_btnWhite.insets = new Insets(0, 0, 0, 5); gbc_btnWhite.gridx = 3; gbc_btnWhite.gridy = 2; contentPane.add(btnWhite, gbc_btnWhite); JButton btnGreen = new JButton("Green"); GridBagConstraints gbc_btnGreen = new GridBagConstraints(); gbc_btnGreen.gridx = 5; gbc_btnGreen.gridy = 2; contentPane.add(btnGreen, gbc_btnGreen); btnRed.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < contentPane.setBackground(Color.red); >>); btnBlue.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < contentPane.setBackground(Color.blue); >>); btnWhite.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < contentPane.setBackground(Color.WHITE); >>); btnGreen.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < contentPane.setBackground(Color.green); >>); pack(); > > 

enter image description here

Screen shot:

Источник

Adding background in jButton (netbeans gui builder)

When i try to add background in Jbutton in java by going to its properties and then icon, it then sets the background of the button but the text which i have written on the button,it moves right(outside the button area).What is the solution for this?

there must be another issue, or atributes from used GUI Framework, for better help soonep please edit your question with a SSCCE

3 Answers 3

If you wanted to add an Image to your JButton with NetBeans follow these steps :

FIGURE 1

  1. Right Click Source Packages , under Projects and Select New -> Other -> (Under Categories) Select Other -> (Under File Types) Select Folder .
  2. Click Next, and provide a name to the folder. For Example resources , do check that for Parent Folder , src is written inside the field. Now Click Finish.
  3. Now manually go to this location on your Computer and create a New Folder, say images, and then paste the IMAGE inside this folder.
  4. Now Under Design Mode , select your JButton, and on the Right Side go to this JButton ‘s properties. Just under foreground you will see icon is written, click the Eclipse Button associated with it to open the window as shown in Figure below :
  5. Do check, this FIGURE 1, to fill in your values and then Press OK

You are done adding image to your JButton. If you want to use the image I used, here it is . Yeah, I forgot to mention, for this, I had set horizontalTextPosition = CENTER and veritcalTextPosition = BOTTOM under Other Properties, inside Properties.

And Here is the output of the whole thing :

Источник

Оцените статью