JFrame background color
I have a JFrame and I'm setting the background color in the constructor:
frame.setBackground(Color.green);
The frame opens up, and the background color flashes green for an instant, then it goes back to grey. What am I missing? Do I have to set the background color in the paint() method?
TIA,
Rich
I found a post from back in April about setting the background color of the contentPane instead, and that works.
Thanks anyway!
Rich
Similar Messages
-
How to set background color for a JFrame
Hi,
i am new to swing programming. I have created a JFrame called framehelp and i placed some labels in the frame.
I have set the background color as yellow for the frame ie by setBackground(new java.awt.Color(255, 255, 204));
But after compiling the program i am still getting the background color of frame as gray.
How can i change the background color of frame as lightish yellow.
I have used NETBEANS to generate this code and i am posting the code..
Kindly help me
Thanks in adavance
public class framehelp extends javax.swing.JFrame {
/** Creates new form framehelp */
public framehelp() {
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
jLabel31 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
getContentPane().setLayout(null);
setBackground(new java.awt.Color(255, 255, 204));
setForeground(new java.awt.Color(204, 204, 204));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
jLabel1.setText("The CAME framework software measurement process evaluation is used to determine the Level of measurement in the ITarea. This measurementprocess evaluation is ");
getContentPane().add(jLabel1);
jLabel1.setBounds(40, 50, 41, 16);
jLabel2.setText("performed individually for software coomponents ie SoftwareProduct, SoftwareProcess and SoftwareResource.");
getContentPane().add(jLabel2);
jLabel2.setBounds(40, 70, 41, 16);
jLabel3.setText("Below we describe the steps which will guide through the measurement process evaluation. There are two types of evaluation considerd here, General evaluation");
getContentPane().add(jLabel3);
jLabel3.setBounds(40, 100, 913, 16);
jLabel4.setText("and Evaluation with respect to a standard. The measurement intensions considerd by varoius measurement standards will be used in our tool based method. ");
getContentPane().add(jLabel4);
jLabel4.setBounds(40, 120, 893, 16);
jLabel5.setText("Information about the measurement standards can be found at www.iso.org , www.ieee.org.");
getContentPane().add(jLabel5);
jLabel5.setBounds(40, 140, 542, 16);
jLabel6.setText("Steps to calculate the MetricsLevel");
getContentPane().add(jLabel6);
jLabel6.setBounds(40, 190, 199, 16);
jLabel8.setText("2 ) The opened frame consists of several metrics and measures, evaluation level buttons, result textfields and selection choice lists. To calculate");
getContentPane().add(jLabel8);
jLabel8.setBounds(70, 240, 41, 16);
jLabel9.setText("general Metricslevel without any standard, select general from Measurement standard choice list. then select Both from scaleType choice list and finally select metrics ");
getContentPane().add(jLabel9);
jLabel9.setBounds(90, 260, 949, 16);
jLabel10.setText(" and measures from the frame and press MetricsLevel Button. The metricslevel for the selected metrics will be displayed in textfield1.");
getContentPane().add(jLabel10);
jLabel10.setBounds(90, 280, 756, 16);
jLabel11.setText("3 ) To determine MetricsLevel with respect to a standard select a standard from MeasurementStandard choice list, select Both from ScaleType choice list and finally ");
getContentPane().add(jLabel11);
jLabel11.setBounds(70, 300, 933, 16);
jLabel12.setText("select darkened metrics and measures and press MetricsLevel Button. The Metrics Level for the selected Metrics and standard will be diplayed in textfield1.");
getContentPane().add(jLabel12);
jLabel12.setBounds(90, 320, 883, 16);
jLabel13.setText("4 ) Repeat steps 1 2, 3 for ProcessMeasurementEvaluation and ResourceMeasurementEvaluation menu items from the select menu.");
getContentPane().add(jLabel13);
jLabel13.setBounds(70, 340, 751, 16);
jLabel7.setText("1 ) Select ProductMeasurementEvaluation menu item from the select menu,a frame called CAME framework software product measurement evaluation will be opened. ");
getContentPane().add(jLabel7);
jLabel7.setBounds(70, 220, 946, 16);
jLabel14.setText("Steps to calculate MeasurementLevel");
getContentPane().add(jLabel14);
jLabel14.setBounds(50, 390, 214, 16);
jLabel15.setText("1 ) Select ProductMeasurementEvaluation menu item from the select menu,a frame called CAME framework software product measurement evaluation will be opened.");
getContentPane().add(jLabel15);
jLabel15.setBounds(80, 420, 943, 16);
jLabel16.setText("2 ) The opened frame consists of several metrics and measures, evaluation level buttons, result textfields and selection choice lists. To calculate");
getContentPane().add(jLabel16);
jLabel16.setBounds(80, 450, 822, 16);
jLabel17.setText("general Measurementlevel without any standard, select general from Measurement standard choice list. then select Quantitative measures from scaleType choice list ");
getContentPane().add(jLabel17);
jLabel17.setBounds(100, 470, 943, 16);
jLabel18.setText("and finally select metrics and measures from the frame and press MeasurementLevel Button. The MeasurementLevel for the selected metrics will be displayed in textfield2.");
getContentPane().add(jLabel18);
jLabel18.setBounds(100, 490, 973, 20);
jLabel19.setText("3 ) To determine MeasurementLevel with respect to a standard select a standard from MeasurementStandard choice list, select Quantitative measures from ScaleType choice list");
getContentPane().add(jLabel19);
jLabel19.setBounds(80, 510, 1009, 16);
jLabel20.setText("and finally select darkened metrics and measures and press MeasurementLevel Button. The MeasurementLevel will be diplayed in textfield2.");
getContentPane().add(jLabel20);
jLabel20.setBounds(100, 530, 799, 16);
jLabel21.setText("4 )Repeat steps 1 2, 3 for ProcessMeasurementEvaluation and ResourceMeasurementEvaluation menu items from the select menu.");
getContentPane().add(jLabel21);
jLabel21.setBounds(80, 550, 748, 16);
jLabel22.setText("Steps to calculate MeasurementProcessLevel");
getContentPane().add(jLabel22);
jLabel22.setBounds(50, 600, 262, 16);
jLabel23.setText("1 ) Select ProductMeasurementEvaluation menu item from the select menu,a frame called CAME framework software product measurement evaluation will be opened.");
getContentPane().add(jLabel23);
jLabel23.setBounds(80, 630, 943, 16);
jLabel24.setText("2 )The opened frame consists of several metrics and measures, evaluation level buttons, result textfields and selection choice lists. To calculate");
getContentPane().add(jLabel24);
jLabel24.setBounds(80, 650, 819, 16);
jLabel25.setText("general MeasurementProcesslevel without any standard, select general from Measurement standard choice list. then select Quantitative measures from scaleType ");
getContentPane().add(jLabel25);
jLabel25.setBounds(100, 670, 930, 16);
jLabel26.setText("choice list, enter migrated metrics if any in textfield below migrated metrics label and finally select metrics measures from the frame and press ");
getContentPane().add(jLabel26);
jLabel26.setBounds(100, 690, 818, 16);
jLabel27.setText("MeasurementProcessLevel Button. The MeasurementProcessLevel for the selected metrics will be displayed in textfield3.");
getContentPane().add(jLabel27);
jLabel27.setBounds(100, 710, 691, 16);
jLabel28.setText("3 ) To determine MeasurementProcessLevel with respect to a standard select a standard from MeasurementStandard choice list, select Quantitative measures from ");
getContentPane().add(jLabel28);
jLabel28.setBounds(80, 740, 937, 16);
jLabel29.setText("from ScaleType choice list, enter migrated metrics if any in textfield below migrated metrics and finally select darkened metrics and measures and press ");
getContentPane().add(jLabel29);
jLabel29.setBounds(100, 760, 873, 16);
jLabel30.setText("MeasurementProcessLevel Button. The MeasurementprocessLevel for the selected metrics will be displayed in textfield3");
getContentPane().add(jLabel30);
jLabel30.setBounds(100, 780, 687, 16);
jLabel31.setText("4 ) Repeat steps 1,2,3 for ProcessMeasurementEvaluation and ResourceMeasurementEvaluation menuitems.");
getContentPane().add(jLabel31);
jLabel31.setBounds(80, 800, 618, 16);
jLabel32.setText("Steps to calculate MeasuredSoftwareProcessLevl");
getContentPane().add(jLabel32);
jLabel32.setBounds(60, 830, 285, 16);
jLabel33.setText("1 ) Follow the same steps as MetricsLevel calcualtion but select metrics and measures covered by CAME Tools only.");
getContentPane().add(jLabel33);
jLabel33.setBounds(90, 860, 657, 16);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-1100)/2, (screenSize.height-940)/2, 1100, 940);
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
* @param args the command line arguments
public static void main(String args[]) {
new framehelp().show();
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration
}1. When you post code, post a minimal example. Did we have to scroll through
all those bloody labels.
2. Can't say much for the quality of code NetBeans generates.
3. To answer your question (sorry, I don't have an autographed copy of the photo):
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class Example {
public static void main(String[] args) throws MalformedURLException {
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = f.getContentPane();
cp.setBackground(new Color(0xff, 0xff, 0xee));
cp.add(new JLabel("set the color on the content pane, not the frame"), BorderLayout.SOUTH);
URL url = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
cp.add(new JLabel(new ImageIcon(url)));
f.pack();
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
} -
How to add background color in JFrame
I have three classes, Car, CarComponent, and CarViewer. I don't know how to code background color. Do I add it to CarViewer where the JFrame is or CarComponent?
CarViewer:
import javax.swing.JFrame;
public class CarViewer
public static void main(String[] args)
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("Two cars");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CarComponent component = new CarComponent();
frame.add(component);
frame.setVisible(true);
}CarComponent
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
This component draws two car shapes.
public class CarComponent extends JComponent
public void paintComponent(Graphics g)
Graphics2D g2 = (Graphics2D) g;
Car car1 = new Car(0, 0);
int x = getWidth() - 60;
int y = getHeight() - 30;
Car car2 = new Car(x, y);
car1.draw(g2);
car2.draw(g2);
}What JSG said, plus I really don't think it's a good idea to instantiate new Car objects in a paintComponent override. Painting methods should be restricted to painting activities, as a matter of principle.
One alternative is to construct your Car instances in a separate method and call repaint() when done; another is to provide a Car method say moveTo(int x, int y) OR refactor the draw(Graphics g) method of Car to draw(Graphics g, int x, int y). Both these suggest that you maintain the Car references as instance fields of CarViewer.
In future (not this time), Swing related questions should be posted in the [Swing forum|http://forums.sun.com/forum.jspa?forumID=57]
db -
Background Color change JFrame
I have to change the background color when the result is either too high or low. Program runs great except the background color doesn't change. And before you complain about my code, I hit the "CODE" button before and after my code in here and it does nothing. The videos wouldn't play. So I don't know how to add code correctly.
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class NumberGuess extends JFrame {
Random rand = new Random ( ) ;
int randomNumber = 1 + rand.nextInt(1000);
int count = 0;
private JFrame panel = new JFrame();
private JFrame panelButtons = new JFrame();
private JFrame panelBottom = new JFrame();
private void compareResult() {
int userInput = Integer.parseInt(tempTextField.getText().trim());
if ( userInput > randomNumber )
resultLabel.setText( "Too High. Try a lower number." );
setBackgroundColor(Color.blue);
private void setBackgroundColor(Color color)
panel.setBackground(color);
panelBottom.setBackground(color);
panelButtons.setBackground(color);Goofy_1969 wrote:
And before you complain about my code, I hit the "CODE" button before and after my code in here and it does nothing.Well, you did manage to create 2 empty code blocks though.
I know this is New To Java, so I need to be nicer and most of you people don't probably have the intrinsic knowledge of "start tag" and "end tag".
But still. All you need is to put your code between tags and everything will work great.
AND HEY, There's the preview button too! So you can actually try and try and try until it works. It's just that programming is a difficult hobby and if you can't work the code tags, you really need to rethink whether you're ready for something that's actually complicated.
(Also if you're not using the code tags, your code will totally get screwed up and people can't help you even if they wanted to.)
As for your code, try using SwingUtilities.invokeLater(). That's the only way you can modify the GUI when you're not running in the event thread. -
Change background color for JFrame
hi,
i want to change background color of JFrame. In my application i didn't create any panels.
my code like this,
Frame myFrame = new JFrame ( " Grid Layout Frame ");
myFrame.setSize(500,500);
myFrame.getContentPane().setBackground(Color.white);
myFrame.setVisible(true);thanks,
BalajiYou don't get a white frame when you run this program?import java.awt.*;
import javax.swing.*;
public class junk
public static void main(String[] args) throws Exception
JFrame f = new JFrame("Hello");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
f.getContentPane().setBackground(Color.white);
f.setVisible(true);
} -
How we can change JFrame Border Color Not Background.
How we change jframe border color not background
if any body know about that then plz tell me
at this [email protected]
i m thanksfull to ..... .hi Shafr
beleive it or not, i got it using trial and error. i keep
trying words in the function setStyle until the color changed. i
dont know why it is not documented.
var periodBarColor:SolidColor = new
SolidColor(taskSchedColorChooser.selectedColor, 1);
periodBar.setStyle("fill",periodBarColor);
//where taskSchedColorChooser is colorPicker component. you
can replace it by any color you want -
System default background color to JFrame on MAC OSX & Ubuntu
I want to set JFrame backgroud color to System Default color of MAC OSX and UBuntu OS. Can anyone plz help me in this regard.
ThanksJust an addition: If you want to give your application the typical 'brushed metal' look on Mac OS, try starting the application with "-Dapple.awt.brushMetalLook=true"
-
How to give Common Background color for all JPanels in My Swing application
Hi All,
I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
Now is there any way to set a common background color for the all the JPanel's available in the application??
I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
Also let me know if SAF has some inbuilt method or way to do this.
Your inputs are valuable.
Thanks in Advance,
Nishanth.CIt is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
Edited by: jduprez on Feb 15, 2010 10:07 AM -
How to set cell background color for JCheckBox renderer in JTable?
I need to display table one row with white color and another row with customized color.
But Boolean column cannot set color background color.
Here is my codes.
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.TreeSet;
public class BooleanTable extends JFrame
Object[][] data = {{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE}};
String[] header = {"CheckBoxes"};
public BooleanTable()
setDefaultCloseOperation( EXIT_ON_CLOSE );
TableModel model = new AbstractTableModel()
public String getColumnName(int column)
return header[column].toString();
public int getRowCount()
return data.length;
public int getColumnCount()
return header.length;
public Class getColumnClass(int columnIndex)
return( data[0][columnIndex].getClass() );
public Object getValueAt(int row, int col)
return data[row][col];
public boolean isCellEditable(int row, int column)
return true;
public void setValueAt(Object value, int row, int col)
data[row][col] = value;
fireTableCellUpdated(row, col);
JTable table = new JTable(model);
table.setDefaultRenderer( Boolean.class, new MyCellRenderer() );
getContentPane().add( new JScrollPane( table ) );
pack();
setLocationRelativeTo( null );
setVisible( true );
public static void main( String[] a )
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch( Exception e )
new BooleanTable();
private class MyCellRenderer extends JCheckBox implements TableCellRenderer
public MyCellRenderer()
super();
setHorizontalAlignment(SwingConstants.CENTER);
public Component getTableCellRendererComponent(JTable
table, Object value, boolean isSelected, boolean
hasFocus, int row, int column)
if (isSelected) {
setForeground(Color.white);
setBackground(Color.black);
} else {
setForeground(Color.black);
if (row % 2 == 0) {
setBackground(Color.white);
} else {
setBackground(new Color(239, 245, 217));
setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
return this;
}Instead of extending JCheckBox, extend JPanel... put a checkbox in it. (border layout center).
Or better yet, don't extend any gui component. This keeps things very clean. Don't extend a gui component unless you have no other choice.
private class MyCellRenderer implements TableCellRenderer {
private JPanel _panel = null;
private JCheckBox _checkBox = null;
public MyCellRenderer() {
// Create & configure the gui components we need
_panel = new JPanel( new BorderLayout() );
_checkBox = new JCheckBox();
_checkBox.setHorizontalAlignment( SwingConstants.CENTER );
// Layout the gui
_panel.add( _checkBox, BorderLayout.CENTER );
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if( isSelected ) {
_checkBox.setForeground(Color.white);
_panel.setBackground(Color.black);
} else {
_checkBox.setForeground(Color.black);
if( row % 2 == 0 ) {
_panel.setBackground(Color.white);
} else {
_panel.setBackground(new Color(239, 245, 217));
_checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
return _panel;
} -
How can I create an alt background color for items in a jlistbox or jtree
What I'm looking to do is have a white background for say items 1,3,5, etc. and a light yellow background for items 2,4,6, etc. I was wondering how can I set an alternative background color on items in a JTree or a JList
Use a cell renderer:
import java.awt.*;
import javax.swing.*;
public class ListAlternating extends JFrame
public ListAlternating()
String[] items = {"one", "two", "three", "four", "five", "six", "seven"};
JList list = new JList( items );
list.setVisibleRowCount(5);
list.setCellRenderer( new MyCellRenderer() );
JScrollPane scrollPane = new JScrollPane( list );
getContentPane().add( scrollPane );
public static void main(String[] args)
ListAlternating frame = new ListAlternating();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
class MyCellRenderer extends DefaultListCellRenderer
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (!isSelected)
setBackground(index % 2 == 0 ? list.getBackground() : Color.LIGHT_GRAY);
return this;
} -
How to change background color in a window? Please help.
Please help me to set background color to my window that includes some panels components.
I have tried
content.setBackground(Color.green); and
frame.setBackground(Color.RED);
but nothing works?
Please what should I change in my code? Thanks already in advance for helping!!
Main parts of my code:
public void addComponentToPane(Container allComponents) throws IOException
definePanels();
allComponents.setLayout(new BoxLayout(allComponents, BoxLayout.Y_AXIS));
allComponents.add(panel_introduction);
allComponents.add(panel_n);
allComponents.add(panel_resultTitle);
allComponents.add(panel_w);
allComponents.add(panel_testing);
allComponents.setVisible(true);
public static void main(String[] args) throws IOException
try {
GraphicsDevice device;
Container content;
JFrame frame = new JFrame("ImageOrder");
device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingApplication app = new SwingApplication();
content = frame.getContentPane();
content.setBackground(Color.green);
app.addComponentToPane(content);
frame.setVisible(true);
finally {
System.out.println("helle");
}import java.awt.Color;
import javax.swing.*;
class Test extends JFrame {
public Test( ){
getContentPane().setBackground(Color.RED);
pack();
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String[] argv) {
new Test().setVisible(true);
} -
Why does JButton background color change when clicking ?
Hello,
I have defined :
JButton mybutton = new JButton(Icon xxx) ;
with no associated text and I set both foreground and background colors to black, and an empty border.
This is because the background color of the container which contents this button is also black and I want to see only the button icon.
When I click on the icon , the button background color becomes grey. How can I change this to make it remains black ?
Thanks a lot.
GegeWell, the color changes because that is how the look and feel is defined,
presumably to give better feedback to the user that she has clicked the
button.
If you don't want this, you could try using a different L&F which doesn't do this.
Alternatively, If you've only got the one button, you could just do
UIManager.put( "Button.select", Color.BLACK );If you have multiple buttons, and you want the other buttons to behave
normally, you can extend the one button and have it change the color
while it is pressed, e.g.,
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import javax.swing.*;
public class ButtonSelect extends JFrame {
public ButtonSelect() throws IOException {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add( new JButton( "Normal" ) );
Image img = Toolkit.getDefaultToolkit().getImage( new URL("http://www.google.com/intl/en/images/logo.gif" ) );
ImageIcon ii = new ImageIcon( img );
JButton b = new JButton( ii ) {
static final private String KEY = "Button.select";
public void paint( Graphics g ) {
Color save = null;
if ( getModel().isArmed() && getModel().isPressed() ) {
save = UIManager.getColor( KEY );
UIManager.put( KEY, Color.WHITE );
super.paint( g );
if ( save != null )
UIManager.put( KEY, save );
b.setForeground( Color.WHITE );
b.setBackground( Color.WHITE );
b.setFocusPainted( false );
panel.add( b );
getContentPane().add( panel );
pack();
setVisible( true );
public static void main( String[] a ) throws IOException {
new ButtonSelect();
} -
How to use a GradientPaint as background color in a JPopupMenu
I want to use a GradientPaint as background color in a JPopupMenu.
I try to use something like
GradientPaint p;
p = new GradientPaint(0, 12, Color.white, 0, 24, Color.pink);
UIManager.put("MenuItem.selectionBackground", p);but it doesn't work.
I also tried to extends BasicMenuItemUI in MenuItems
public class CMenuItem extends JMenuItem {
public CMenuItem(String text) {
super(text);
setUI(BUI.createUI(this));
static final class BUI extends BasicMenuItemUI {
private final static BUI ui = new BUI();
public static BUI createUI(JComponent c) {
return ui;
@Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
Graphics2D g2 = (Graphics2D)g.create();
int w = c.getWidth();
int h = c.getHeight();
GradientPaint p;
p = new GradientPaint(0, 12, Color.white, 0, 24, Color.pink);
g2.setPaint(p);
g2.fillRect(0, 0, w, h);
g2.dispose();
paint(g, c);
}I used this technique for JLabel and it works fine.
Please helpok, here the SSCCE. I hope its helpful for an answer.
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicMenuItemUI;
public class Menu {
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
//Create the menu bar.
menuBar = new JMenuBar();
//Build the first menu.
menu = new JMenu("A Menu");
menuBar.add(menu);
GradientPaint p;
p = new GradientPaint(0, 12, Color.white, 0, 24, Color.pink);
UIManager.put("MenuItem.selectionBackground", p);
menuItem = new JMenuItem("1st item: when selected its background is black: wrong");
menu.add(menuItem);
UIManager.put("MenuItem.selectionBackground", Color.pink);
menuItem = new JMenuItem("2nd item: when selected its background is pink: ok");
menu.add(menuItem);
menuItem = new CMenuItem("3rd item: when selected its background is pink: WRONG!");
menu.add(menuItem);
return menuBar;
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Menu demo = new Menu();
frame.setJMenuBar(demo.createMenuBar());
//Display the window.
frame.setSize(450, 260);
frame.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
class CMenuItem extends JMenuItem {
private static final long serialVersionUID = 1L;
public CMenuItem(String text) {
super(text);
setUI(BUI.createUI(this));
static final class BUI extends BasicMenuItemUI {
private final static BUI ui = new BUI();
public static BUI createUI(JComponent c) {
return ui;
@Override
public void update(Graphics g, JComponent c) {
if (true || c.isOpaque()) {
// System.out.println("update()");
Graphics2D g2 = (Graphics2D)g.create();
int w = c.getWidth();
int h = c.getHeight();
GradientPaint p;
p = new GradientPaint(0, 0, Color.white, 0, 10, Color.pink);
g2.setPaint(p);
g2.fillRect(0, 0, w, h);
g2.dispose();
paint(g, c);
}Thanks for the help -
Set background color when condition applied
hi,
Can anybody tell me how to set background color when condition applied.
My initial plan was to highlight a specify row(Change color) when the third column of this JTable consists of OK word.
int rowCount = table.getRowCount();
for(int i=0 ;i <rowCount ; i++)
String word = table.getValueAt(i,3).toString();
if(word.equals("Word")) {
table.setSelectionBackground(Color.red);
break;
else {
table.setBackground(getBackground());
Thanks.import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableChanges
public TableChanges()
String[] headers = { "column 1", "column 2", "column 3", "column 4" };
int rows = 18;
int cols = 4;
String[][] data = new String[rows][cols];
for(int row = 0; row < rows; row++)
for(int col = 0; col < cols; col++)
data[row][col] = "item " + (row * cols + col + 1);
JTable table = new JTable(data, headers);
// add custom cell renderer to each column
TableColumnModel columnModel = table.getColumnModel();
for(int j = 0; j < columnModel.getColumnCount(); j++)
TableColumn col = columnModel.getColumn(j);
col.setCellRenderer(new CellRenderer());
// add table model listener to listen for cell edits
// so we can detect our special selection edit value
// which is "word"
TableModel tableModel = table.getModel();
tableModel.addTableModelListener(new ModelListener(table));
JScrollPane scrollPane = new JScrollPane(table);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(scrollPane);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
Dimension d = scrollPane.getViewport().getSize();
table.setRowHeight(d.height/rows);
public static void main(String[] args)
new TableChanges();
class ModelListener implements TableModelListener
JTable table;
public ModelListener(JTable table)
this.table = table;
public void tableChanged(TableModelEvent e)
int firstRow = e.getFirstRow();
int lastRow = e.getLastRow();
int colIndex = e.getColumn();
if(e.getType() == TableModelEvent.UPDATE &&
firstRow != TableModelEvent.HEADER_ROW &&
colIndex != TableModelEvent.ALL_COLUMNS &&
colIndex == 2) // column 3 only
String value = (String)table.getValueAt(firstRow, colIndex);
// check for our special selection criteria
if(value.equals("word"))
for(int j = 0; j < table.getColumnCount(); j++)
CellRenderer renderer =
(CellRenderer)table.getCellRenderer(firstRow, j);
renderer.setSpecialSelection(firstRow, j);
class CellRenderer extends DefaultTableCellRenderer
int specRow, specCol;
public CellRenderer()
specRow = -1;
specCol = -1;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int col)
setHorizontalAlignment(JLabel.CENTER);
Color color = Color.black;
if(hasFocus)
color = Color.blue;
else if(isSelected)
color = Color.green.darker();
else if(row == specRow && col == specCol)
color = color.red;
setForeground(color);
setText((String)value);
return this;
public void setSpecialSelection(int row, int col)
specRow = row;
specCol = col;
} -
Set JInternalFrame Background Color
Hey Guys!
I've got the following problem. I've a JInternalFrame and I want to simply modify the background color of it, at runtime...
I've tried the following:
setBackground(Color.red);
getGlassPane().setBackground(Color.red);
getContentPane().setBackground(Color.red);
UIManager.put("control", new ColorUIResource(Color.red));
UIManager.put("InternalFrame.background", new ColorUIResource(Color.red));
Nothing changed anything!
Any idea?
Thanks & best regards,
KristianNothing changed anything!Are you sure?
A simple example.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InternalFrameDemo implements ActionListener {
private JDesktopPane desktopPane;
private void createAndShowUI(){
JFrame frame = new JFrame("Internal Frame Demo");
desktopPane = new JDesktopPane();
JButton button = new JButton("Create and Show Internal Frame");
desktopPane.setPreferredSize(new Dimension(600,500));
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.PAGE_START);
frame.getContentPane().add(desktopPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public void actionPerformed(ActionEvent evt){
desktopPane.add(new createInternalFrame("My Frame"));
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new InternalFrameDemo().createAndShowUI();
class createInternalFrame extends JInternalFrame implements ActionListener {
public createInternalFrame(String title){
super(title);
JButton btn = new JButton("Change color");
btn.addActionListener(this);
setIconifiable(true);
setClosable(true);
setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setSize(new java.awt.Dimension(300,300));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(btn, BorderLayout.PAGE_START);
setVisible(true);
public void actionPerformed(ActionEvent evt){
getContentPane().setBackground(Color.GREEN);
}
Maybe you are looking for
-
Mass Delete of Unreleased Transports
Mass Delete of Unreleased Transports Hi, I have to delete ~2000 unreleased transports. Could you advise any way to mass delete transports? Regards, Vivian
-
Hi, I've installed the trial version of LiveCycle ES Server & Workbench v8.0.1.1 SP 1b on a PC running Vista Business, 3Gb RAM, Core Duo Processor. Everything is running OK; except when I try to edit a Process in Workbench. If I double click on a Pro
-
thank you.
-
Has anyone got FOP working on OC4J? I have compiled the FopServlet that comes with the download. It does not render a PDF just a blank webpage. Maybe someone else has seen this error? Thanks, Tom Henricksen
-
Photo preview blank when browsing Aperture Library from iPhoto
Hello to everyone, I need to import in iPhoto some photo of my Aperture's Library, but when I open it from iPhoto I can see all the pictures exept the lastest that I've imported in the Aperture Library (that have been taken with a Canon EOS 550D with