SetBackground(Color c)
Hello All,
What do you know about setBackground(Color c) execution ?
I mean does this function work as PostMessage() or as SendMessage ? Can I be sure that after the funcion has returned this "paint message" has already been processed by the system ?
Wrong. I suggest you take a look at the code in JComponent:
public void setBackground(Color bg) {
Color oldBg = getBackground();
super.setBackground(bg);
if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
// background already bound in AWT1.2
repaint();
}But in general if you program in such a way that it matters when exactly
your component gets repainted, better re-think your approach:
You should call setBackground() only from AWTs event thread and you
better don't make long-running calculations in this thread.
However at the latest your component will get repainted when this
thread is idle.
Also, take a look at the JavaDoc of repaint():
"Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched."
So even repaint() does not paint your component immediatly.
The gist of it: JavaDoc and the JDK sources are your friend.
Similar Messages
-
SetBackground(Color.WHITE) not working
I am trying to set background color to white, but it's not working. Can anyone find out the problem?
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.*;
public class Lab3ex2 {
* @param args ignored
public static void main(String[] args) throws IOException {
// Station[] stations = new Station[100];
// int n = 0;
ArrayList<Station> stations = new ArrayList<Station>();
ArrayList xPos = new ArrayList();
ArrayList yPos = new ArrayList();
final String fname = "C://Positions-v2.csv";
BufferedReader br = new BufferedReader(new FileReader(fname));
String stationName, item, line;
line = br.readLine(); // first line skipped
line = br.readLine(); // 2nd
while (line != null) {
StringTokenizer stoke = new StringTokenizer(line, ",");
stationName = stoke.nextToken().trim();
item = stoke.nextToken();
float x = Float.parseFloat(item);
item = stoke.nextToken();
float y = Float.parseFloat(item);
item = stoke.nextToken();
String justification = item;
// stations[n] = new Station(stationName, x, y);
// n++;
stations.add(new Station(stationName, x, y, justification));
xPos.add(x);
yPos.add(y);
line = br.readLine(); // line 3,4,...
for (Station station : stations) {
System.out.println(station);
//System.out.printf("%20s %6.1f,%6.1f)%n",station.name, station.x, station.y);
System.out.print("Press enter...");
System.in.read();
JFrame f = new JFrame("Lab3ex2");
f.add(new MyPanel(stations, xPos, yPos));
f.setSize(500,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to avoid needing ^C
class Station {
public String name;
public float x;
public float y;
public String justification;
public Station(String name, float x, float y, String justification) {
this.name = name;
this.x = x;
this.y = y;
this.justification = justification;
public String toString() {
// todo: format x and y
return name + " (" + x + "," + y + ")";
class MyPanel extends JPanel {
private ArrayList<Station> stations;
private float xMax, yMax;
private ArrayList xPos;
private ArrayList yPos;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Dimension dim = getSize();
float xScale, yScale, scale, x, y, radius = 1.0f, diam;
String justification = null;
diam = 2.0f*radius;
Shape s;
xScale = dim.width/xMax;
yScale = dim.height/yMax;
scale = Math.min(xScale, yScale);
g2.scale(scale, scale);
g2.setStroke(new BasicStroke(1.0f/scale)); // thin lines
g2.setFont(new Font("SanSerif", Font.PLAIN, (int)(11.2f/scale))); // always 12 approx
int total = 0;
for (Station st : stations) {
if(st.name.length()>total)
total = st.name.length();
for (Station st : stations) {
x = st.x - radius;
y = st.y - radius;
justification = st.justification;
s = new Ellipse2D.Float(x, y, 2.0f*radius, 2.0f*radius);
g2.draw(s);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(justification.equals("R"))
g2.drawString(st.name, (x-st.name.length())-2, (y+diam));
else
g2.drawString(st.name, (x+diam+radius), (y+diam));
GeneralPath theShape = new GeneralPath();
theShape.moveTo((float)(Float)xPos.get(0), (float)(Float)yPos.get(0));
for(int i=0; i<15; i++)
theShape.lineTo((float)(Float)xPos.get(i), (float)(Float)yPos.get(i));
g2.draw(theShape);
this.setBackground(Color.WHITE);
public MyPanel(ArrayList<Station> stations, ArrayList xPos, ArrayList yPos) {
this.stations = stations;
this.xPos = xPos;
this.yPos = yPos;
xMax = -99999.0f;
yMax = -99999.0f;
for (Station st : stations) {
if (st.x > xMax) xMax = st.x;
if (st.y > yMax) yMax = st.y;
}import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.*;
* Advanced Java Lab 3 ex 2: reading and drawing Met station data
* @author rallen
public class Lab3ex2 {
* @param args
* ignored
public static void main(String[] args) throws IOException {
// Station[] stations = new Station[100];
// int n = 0;
ArrayList<Station> stations = new ArrayList<Station>();
ArrayList xPos = new ArrayList();
ArrayList yPos = new ArrayList();
final String fname = "C://Positions-v2.csv";
BufferedReader br = new BufferedReader(new FileReader(fname));
String stationName, item, line;
line = br.readLine(); // first line skipped
line = br.readLine(); // 2nd
while (line != null) {
StringTokenizer stoke = new StringTokenizer(line, ",");
stationName = stoke.nextToken().trim();
item = stoke.nextToken();
float x = Float.parseFloat(item);
item = stoke.nextToken();
float y = Float.parseFloat(item);
item = stoke.nextToken();
String justification = item;
// stations[n] = new Station(stationName, x, y);
// n++;
stations.add(new Station(stationName, x, y, justification));
xPos.add(x);
yPos.add(y);
line = br.readLine(); // line 3,4,...
for (Station station : stations) {
System.out.println(station);
// System.out.printf("%20s %6.1f,%6.1f)%n",station.name, station.x,
// station.y);
System.out.print("Press enter...");
System.in.read();
JFrame f = new JFrame("Lab3ex2");
f.add(new MyPanel(stations, xPos, yPos));
f.setSize(500, 400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to avoid needing ^C
class Station {
public String name;
public float x;
public float y;
public String justification;
public Station(String name, float x, float y, String justification) {
this.name = name;
this.x = x;
this.y = y;
this.justification = justification;
public String toString() {
// todo: format x and y
return name + " (" + x + "," + y + ")";
class MyPanel extends JPanel {
private ArrayList<Station> stations;
private float xMax, yMax;
private ArrayList xPos;
private ArrayList yPos;
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setLayout(new FlowLayout());
Graphics2D g2 = (Graphics2D) g;
Dimension dim = getSize();
float xScale, yScale, scale, x, y, radius = 1.0f, diam;
String justification = null;
diam = 2.0f * radius;
Shape s;
xScale = dim.width / xMax;
yScale = dim.height / yMax;
scale = Math.min(xScale, yScale);
g2.scale(scale, scale);
g2.setStroke(new BasicStroke(1.0f / scale)); // thin lines
g2.setFont(new Font("SanSerif", Font.PLAIN, (int) (11.2f / scale))); // always
// 12
// approx
int total = 0;
for (Station st : stations) {
if (st.name.length() > total)
total = st.name.length();
for (Station st : stations) {
x = st.x - radius;
y = st.y - radius;
justification = st.justification;
s = new Ellipse2D.Float(x, y, 2.0f * radius, 2.0f * radius);
g2.draw(s);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (justification.equals("R")) {
g2.drawString(st.name, (x - st.name.length()) - 2, (y + diam));
} else {
g2.drawString(st.name, (x + diam + radius), (y + diam));
GeneralPath theShape = new GeneralPath();
theShape.moveTo((float) (Float) xPos.get(0), (float) (Float) yPos
.get(0));
for (int i = 0; i < 15; i++) {
theShape.lineTo((float) (Float) xPos.get(i), (float) (Float) yPos
.get(i));
g2.draw(theShape);
setOpaque(true);
public MyPanel(ArrayList<Station> stations, ArrayList xPos, ArrayList yPos) {
this.stations = stations;
this.xPos = xPos;
this.yPos = yPos;
xMax = -99999.0f;
yMax = -99999.0f;
for (Station st : stations) {
if (st.x > xMax)
xMax = st.x;
if (st.y > yMax)
yMax = st.y;
this.setBackground(Color.WHITE);
this.setVisible(true);
}Edited by: swapnil_raverkar on Sep 21, 2008 5:10 AM -
JFrame setBackground(Color c)
i'm just curious about Swing so i started reading sun tut Using Swing Components /Using Top-Level Containers and at the same time reviewing a tut i built some time ago called DiveLog (also from sun).
package divelog;
import javax.swing.*;
import java.awt.*; // Contains all of the classes for creating user
// interfaces and for painting graphics and images.
import java.awt.event.*; // Provides interfaces and classes for
// dealing with different types of events fired by AWT components
public class DiveLog {
private JFrame dlframe;
//private JTabbedPane tabbedPane;
public DiveLog() {
JFrame.setDefaultLookAndFeelDecorated(true);
dlframe = new JFrame ("T?tulo do frame");
dlframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dlframe.setSize(400, 200);
//dlframe.setBackground(Color(49, 106, 197));
Color c = new Color(49, 106, 197);
dlframe.setBackground(c);
//dlframe.setForeground(c);
//dlframe.pack();
// Causes this Window to be sized to fit the
// preferred size and layouts of its subcomponents.
// If the window and/or its owner are not yet displayable,
// both are made displayable before calculating the preferred size.
// The Window will be validated after the preferredSize is calculated.
dlframe.setVisible(true);
System.out.print(dlframe.getBackground());
public static void main(String args[]) {
DiveLog dl = new DiveLog();
}My Q:
what's the use of
.setBackground(c); if we cant see it?The content pane is always painted over the JFrame. So you would set the background color of the content pane, not the frame. So, I agree with you, there is no need for that line of code.
The only possible reason I could think of is that when using a slow computer the painting may not be done fast enough and you could get a flicker as the frame is painted and then the content pane.
JFrame frame = new JFrame();
frame.setBackground( Color.RED );
frame.getContentPane().setBackground( Color.GREEN );
frame.setSize(300, 300);
frame.setVisible(true);
Run the above code and you will notice a flicker as the frame is first painted red and then green. So to reduce flicker you could set the frame background to green as well. In most cases when using the default background color of gray you don't notice the flicker so you don't usually worry about it. -
SetBackground color not working
Hello,
While viewing my applet from within a HTML file, my background color is still grey, except the buttons.
The color is fine while viewing with appletviewer so I'm a bit confussed.
Any ideas as to why would be appreciated.
Thanks in advance.
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.awt.event.*;
public class MyCalendar extends javax.swing.JApplet {
public void init()
Container content = getContentPane();
JPanel calendars = new JPanel(new GridLayout(0,1));
JScrollPane jsp = new JScrollPane(calendars);
content.add(jsp, BorderLayout.CENTER);
GregorianCalendar gc = new GregorianCalendar();
//gc.set(GregorianCalendar.DAY_OF_YEAR,1);c
gc.set(GregorianCalendar.DAY_OF_MONTH,1);
for (int i=0; i<12; i++)
calendars.add(new CalendarPanel(gc));
gc.add(GregorianCalendar.MONTH, 1);
//setSize(300, 300);
//setVisible(true);
class CalendarPanel extends JPanel implements ActionListener
private JLabel jl;
private int testYear;
private final static String[] DOW = {"S","M","T","W","T","F","S"};
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
GridBagConstraints gbc = new GridBagConstraints(0,0,7,1,1.0,1.0,GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0);
public CalendarPanel(GregorianCalendar cal)
setLayout(new GridBagLayout());
setBorder(BorderFactory.createEtchedBorder());
setBackground(Color.white);
//get the month name
String testMonth=sdf.format(cal.getTime());
testYear = cal.get(GregorianCalendar.YEAR);
int nextYear = cal.get(GregorianCalendar.YEAR)+1;
JLabel lblYear = new JLabel(""+testYear);
JLabel jl = new JLabel(testMonth, JLabel.CENTER);
add(jl,gbc);
gbc.gridwidth=1;
gbc.gridy=1;
for (int i=0; i<7; i++)
gbc.gridx=i;
add(new JLabel(DOW, JLabel.CENTER),gbc);
gbc.gridx = cal.get(GregorianCalendar.DAY_OF_WEEK)-1;
gbc.gridy++;
int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
for (int i=1; i<=daysInMonth; i++)
JButton jb = new JButton(""+i);
jb.setBackground(Color.white);
jb.setForeground(Color.blue);
jb.addActionListener(this);
//jb.setBorder(BorderFactory.createRaisedBevelBorder());
add(jb,gbc);
if (++gbc.gridx==7)
gbc.gridx=0;
gbc.gridy++;
public void actionPerformed(ActionEvent event)
String command = event.getActionCommand();
if(event.getSource() instanceof JButton)
System.out.println("Button:"+command);
String text = jl.getText();
System.out.println("Month:"+text);
System.out.println("Year:"+testYear);Ok, the last one worked but now one of my labels won't change color even after jl.setOpaque(true).
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.awt.event.*;
public class MyCalendar extends javax.swing.JApplet {
public void init()
Container content = getContentPane();
JPanel calendars = new JPanel(new GridLayout(0,1));
JScrollPane jsp = new JScrollPane(calendars);
content.add(jsp, BorderLayout.CENTER);
GregorianCalendar gc = new GregorianCalendar();
//gc.set(GregorianCalendar.DAY_OF_YEAR,1);c
gc.set(GregorianCalendar.DAY_OF_MONTH,1);
for (int i=0; i<12; i++)
calendars.setOpaque(true); //this worked
calendars.add(new CalendarPanel(gc));
gc.add(GregorianCalendar.MONTH, 1);
class CalendarPanel extends JPanel implements ActionListener
private JLabel jl;
private int testYear;
private final static String[] DOW = {"S","M","T","W","T","F","S"};
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
GridBagConstraints gbc = new GridBagConstraints(0,0,7,1,1.0,1.0,GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0);
public CalendarPanel(GregorianCalendar cal)
setLayout(new GridBagLayout());
setBorder(BorderFactory.createEtchedBorder());
setBackground(Color.white);
//get the month name
String testMonth=sdf.format(cal.getTime());
testYear = cal.get(GregorianCalendar.YEAR);
int nextYear = cal.get(GregorianCalendar.YEAR)+1;
JLabel lblYear = new JLabel(""+testYear);
JLabel jl = new JLabel(testMonth, JLabel.CENTER);
jl.setOpaque(true); //only works in appletviewer NOT html
jl.setBackground(Color.red);
add(jl,gbc);
gbc.gridwidth=1;
gbc.gridy=1;
for (int i=0; i<7; i++)
gbc.gridx=i;
add(new JLabel(DOW, JLabel.CENTER),gbc);
gbc.gridx = cal.get(GregorianCalendar.DAY_OF_WEEK)-1;
gbc.gridy++;
int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
for (int i=1; i<=daysInMonth; i++)
JButton jb = new JButton(""+i);
jb.setBackground(Color.white);
jb.setForeground(Color.blue);
jb.addActionListener(this);
jb.setBorder(BorderFactory.createRaisedBevelBorder());
add(jb,gbc);
if (++gbc.gridx==7)
gbc.gridx=0;
gbc.gridy++;
public void actionPerformed(ActionEvent event)
String command = event.getActionCommand();
if(event.getSource() instanceof JButton)
System.out.println("Button:"+command);
String text = jl.getText();
System.out.println("Month:"+text);
System.out.println("Year:"+testYear);
[\code] -
JComponent.setbackground(Color.BLACK) is NOT working
I am creating Space Invaders game and have GamePanel as my JComponent, named panel. The background is not changing for sum reason though???
import java.awt.*;
import javax.swing.*;
public class SpaceInvaders{
//variables
public static final int WIDTH = 800;
public static final int HEIGHT = 800;
GamePanel panel;
public SpaceInvaders()
//create frame
JFrame demoFrame = new JFrame("Space Invaders");
demoFrame.setBounds(0,0,WIDTH,HEIGHT);
demoFrame.setVisible(true);
demoFrame.setResizable(false);
demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demoFrame.setBackground(Color.BLACK);
//create panel
GamePanel panel = new GamePanel(this);
panel.setBackground(Color.BLACK);
demoFrame.add(panel);
//add buttons
JButton startButton = new JButton("Start");
startButton.setEnabled(true);
JButton stopButton = new JButton("Stop");
stopButton.setEnabled(true);
..... import java.awt.*;
import javax.swing.*;
import java.awt.Image;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import javax.swing.*;
import java.awt.event.*;
public class GamePanel extends JComponent implements KeyListener, ActionListener
SpaceInvaders game;
static Player player1;
Bullets bullet;
private BufferStrategy strategy;
static int alienNum = 36;
static int alienRow = 6;
static int alienCol = 6;
static Aliens[][] aliens;
static Bullets[] bullets;
private Timer timer;
int bulletNum=0;
public GamePanel(SpaceInvaders game)
this.game = game;
player1 = new Player(this);
player1.start();
aliens = new Aliens[alienRow][alienCol];
for(int i=0; i<alienRow; i++)
for(int j=0; j<alienCol; j++){
aliens[i][j] = new Aliens(this);
aliens[i][j].setX(i*50);
aliens[i][j].setY(j*50);
bullets = new Bullets[5];
bullets[0]=new Bullets(this);
timer=new Timer(500, this);
//timer.setDelay(500);
timer.start();
this.setFocusable(true);
this.addKeyListener(this);
public void paintComponent(Graphics g)
super.paintComponent(g);
Image pic1 = player1.getImage();
...........I changed the GamePanel class to extend JPanel instead of extend JComponent and it works now. Didnt realise JComponent had no paint functions.. Thanks for your help.
import java.awt.image.BufferStrategy;
import javax.swing.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements KeyListener, ActionListener
SpaceInvaders game;
static Player player1;
Bullets bullet;
private BufferStrategy strategy; -
JScrollPane.setBackground(Color.white);
Hi @all,
I want to make the BackgroundColor of my JScrollPane white. Does anybody know, why this little piece of code doesn?t do anything?
I can compile it, but then the background is still grey.
JLabel pic = new JLabel(new ImageIcon("dile_logo.jpg"));
JScrollPane sp = new JScrollPane(pic, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
sp.setBackground(Color.white);
add(sp);
thank you
JuergenI tried:
sp.setOpaque(true);
and also:
pic.setBackground(Color.white);
but both does not change anything.
@vaskol
I have a picture that is smaller than the window and also as the scrollpane. So I do not have ScrollBars.
The background of the picture is white and the rest of the window is grey and I want to change that to white.
I do not understand what you mean with "that square in the corner" and also this part of your explication.
Sorry
Juergen -
JLabel.setBackground(Color.red) not working
Hi, I am using the (JLabel) lblPrmf.setBackground(Color.RED), but the label is not colored. Here is my program:
import java.util.*;
import javax.swing.*; //JFrame and JPanel etc...
import java.awt.*; //BorderLayout and Container etc....
import java.awt.Color;
import java.awt.event.*; //ActionListener og WindowAdapter
public class AllVac extends JFrame
//Define JLabel
private JLabel lblDays;
private JLabel lblAbs;
private JLabel lblPrmf;
//Define JButton
private JButton month;
private JButton back;
private JButton forward;
//Define JPanel
private JPanel south;
private JPanel north;
public AllVac()
// JFrame jf = new JFrame("Vacation for the Stavanger Team ");
Container c = getContentPane();
// c.setTitle("Vacation for the Stavanger Team ");
c.setLayout(new BorderLayout());
c.add(new ShowNorth(), BorderLayout.NORTH);
c.add(new ShowSouth(), BorderLayout.SOUTH);
pack();
setVisible(true);
addWindowListener(new Close());
public static void main(String args[])
AllVac a = new AllVac();
public class ShowNorth extends JPanel
public ShowNorth()
north = new JPanel(new GridLayout(1, 3));
month = new JButton("August 2006");
back = new JButton("<<");
forward = new JButton(">>");
north.add(back);
north.add(month);
north.add(forward);
add(north);
public class ShowSouth extends JPanel
public ShowSouth()
int days = 31;
south = new JPanel(new GridLayout(16, days+1));
//Arrange the days
for ( int i = 1; i<(days+1); i++)
lblDays = new JLabel(" " + Integer.toString(i));
lblDays.setBorder(BorderFactory.createLineBorder(Color.red));
south.add(lblDays);
add(south, BorderLayout.LINE_START);
//Fill in the names and vacation days
for ( int i = 1; i<(days+1); i++)
lblAbs = new JLabel(" ");
south.add(lblAbs);
add(south, BorderLayout.LINE_START);
for (int j = 0; j<14; j++)
for ( int i = 1; i<days+1; i++)
String v = "v";
lblPrmf = new JLabel(" " + v + " ");
lblPrmf.setBackground(Color.RED);
lblPrmf.setBorder(BorderFactory.createLineBorder(Color.blue));
lblPrmf.setBackground(Color.RED);
lblPrmf.repaint();
south.add(lblPrmf);
add(south);
public class Close extends WindowAdapter
public void windowClosing(WindowEvent c)
System.exit(0);
}You are building a GUI with Swing components. Why would you ask the question in the general programming forum???? People there may never have built a GUI or heard of Swing.
Concepts of creating GUI components adding then to a GUI, dealing with models, listening to events and responding to the events are all techniques related to GUI programming. Even Swing programming is different from AWT programming in some cases.
So when you topic title says. "I have a problem, with a Swing (JLabel) component", or "How do I change a JTable in a JScrollPane" where do you think the question should be asked. Maybe its just me but I would think the Swing forum is where you would find the experts, or at least people who think they know something about Swing.
Your previous posting on "display a button on a background image" was not very clear. You use an Applet and Panel which are an AWT components. But then you are also using JFrame and JButton which are Swing components. Since you posted the question in the general programming forum, I had no idea whether you where attempting to write an AWT or a Swing application so I ignored the posting. -
JButton.setBackground(Color color) not working
With JDK 1.4.2, my JButtons below have a blue background. When I compile with 1.5, they are gray. I tried using setOpaque(true) on one of them below. It didn't work. Any ideas?
class MainMenu extends JFrame
public MainMenu() throws Exception
super("");// no title on main menu
JPanel pane = new JPanel(null, true);
pane.setBackground(new Color(4194496));
Icon icon = new ImageIcon(BizThriveMenu.getResourceDir()+"\\BizThriveSmall.gif");
JLabel lImage = new JLabel(icon);
JButton bEditCustomers = new JButton("<html><FONT COLOR=WHITE>Customers</FONT></html>");
bEditCustomers.setOpaque(true);
bEditCustomers.setBackground(new Color(4194496));
JButton bAccounting = new JButton("<html><FONT COLOR=WHITE>Accounting</FONT></html>");
bAccounting.setBackground(new Color(4194496));
JButton bEditReminders = new JButton("<html><FONT COLOR=WHITE>Reminders</FONT></html>");
bEditReminders.setBackground(new Color(4194496));
JButton bPublish = new JButton("<html><FONT COLOR=WHITE>Publish</FONT></html>");
bPublish.setBackground(new Color(4194496));
JButton bExit = new JButton("<html><FONT COLOR=WHITE>Exit</FONT></html>");
bExit.setBackground(new Color(4194496));
bEditCustomers.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
new TableListFrame(MainMenu.this, "customers");
catch (Exception e) {
e.printStackTrace();
bAccounting.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
new AccountCategoryListFrame(MainMenu.this, "accountCategories");
catch (Exception e) {
e.printStackTrace();
bEditReminders.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
new CurrentRemindersFrame(MainMenu.this);
catch (Exception e) {
e.printStackTrace();
bPublish.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
new Designer(MainMenu.this);
catch (Exception e) {
e.printStackTrace();
bExit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.exit(0);
Font buttonFont = bEditCustomers.getFont();
buttonFont = new Font("Times New Roman", Font.ITALIC+Font.BOLD, 24);
bEditCustomers.setFont(buttonFont);
bAccounting.setFont(buttonFont);
bEditReminders.setFont(buttonFont);
bPublish.setFont(buttonFont);
bExit.setFont(buttonFont);
pane.add(lImage);
pane.add(bEditCustomers);
pane.add(bAccounting);
pane.add(bEditReminders);
pane.add(bPublish);
pane.add(bExit);
int appWidth = 500;
int appHeight = 700;
this.setSize(new Dimension(appWidth,appHeight));
this.setResizable(false);
this.getContentPane().add(pane);
Insets insets = pane.getInsets();
lImage.setBounds(((appWidth-4-icon.getIconWidth())/2)+insets.left, 35+insets.top, icon.getIconWidth(), icon.getIconHeight());
bEditCustomers.setBounds(((appWidth-4-235)/2)+insets.left, 200 + insets.top, 235, 40);
bAccounting.setBounds(((appWidth-4-235)/2)+insets.left, 250 + insets.top, 235, 40);
bEditReminders.setBounds(((appWidth-4-235)/2)+insets.left, 300 + insets.top, 235, 40);
bPublish.setBounds(((appWidth-4-235)/2)+insets.left, 350 + insets.top, 235, 40);
bExit.setBounds(((appWidth-4-235)/2)+insets.left, 400 + insets.top, 235, 40);
//center application window on desktop
Dimension screenSize = null;;
screenSize = getToolkit().getScreenSize();
this.setBounds((screenSize.width - appWidth)/2,
(screenSize.height - appHeight)/2, appWidth, appHeight);
// make the frame visible
this.setVisible(true);
}As a newbie to the forum you obviously didn't understand how to post a simple direct question, with only the relevant code to demonstrate the problem, which is why I provided you with all the extra information to help you get better answers in the future.
Did you bother to read the link of creating an SSCCE?
Your question is about setting the background color of a button. 99% of the code you posted is not related to that issue. Keep the code simple so we don't waste time reading through unnecessary code. That way we can determine whether the problem is with your code or the environment as I already mentioned.
1) Though the information about setting the text color is helpful, the
background color of the button is the subject of the posting. Please
limit your replies to the subject of the posting.If the code posted was only related to the background color then we wouldn't have this issue now would we? When I see something strange or wrong I make a comment whether it is directly related to the question or not. It has been my experience that most people appreciate the bonus advice, so I will not change my behaviour for you. If you don't like the advice, then just ignore it.
2) Regarding, "I don't use 1.5 so I can't really help you, but neither can
anybody else...", please read Michael_Dunn's post, who remarkably
was able to provide help.My comment was related to the code you provided. Nobody could use the code to compile and execute to see if it ran on their machine. So, Michael, had to waste time creating his own simple test program to see if it worked, which it did.
My point was if you provided the same simple demo program that Michael did, then all he (or anybody else) would have had to do would be to copy, compile and test the program. You should be spending the time creating the simple test program not each of us individually. Think of how much time is wasted if everybody who wanted to help you had to create their own program? Thats why I included the link on creating an SSCCE, so the next time we don't need to waste time.
3) ..... Otherwise, it's alright not to reply to a subject. Nobody will think less of you.Of course I don't have to replay to every question (and I don't), but if you don't learn to post a question properly you will make the same mistake again and again. That was the context of my answer. It was designed to help you ask a better question the next time.
4) Your comment, "And don't forget to use the Code Formatting Tags > so the code retains its original formatting." That was a standard message I use for many newbies to the forum. I'm amazed at the number of people who think we are mind readers and can guess exactly what is causing the problem without posting any code. So I got tired of typing in a different message every time and I now just cut and paste. Yes I could have edited the last line out, but you would be amazed at how many people format the code the first time but then forget to do it when prompted for more detail. So I just keep it in all messages.
Please keep your comments related to the problem. I think I've learned a think or two over the years on how to ask and answer a question. -
Usage of setPreferredSize(Dimension) and setbackground(Color)
Hi,
I'm using BorderLayout panel, this panel in-turn holds FlowPanels which has all the components. Now, I'm trying to set the background color and the preferred size to the Borderlayout panel, but its not reflecting. My panel is taking the default gray color and some default font.
I want this panel use the color that the frame has and also want to set the Dimension, to which Panel has to resize.
Please help me out, how to do this ?
Code snippets will be a gr8 help.
Thanks in advance,
Chandrasekhar.I'm using BorderLayout panel, this panel in-turn holds FlowPanels which has all the components. Now, I'm trying to set the background color and the preferred size to the Borderlayout panel, but its not reflecting. My panel is taking the default gray color and some default font.
I doubt those grey bits you see are the BorderLayout panel: they're the FlowPanels or even the components in them. Bear in mind that most components are opaque by default - so if you create a JPanel with a BorderLayout, add a JPanel in its center and then set the background of the original, it won't matter because what you're seeing is the child panel.
As for the preferred size, how that gets used depends on what layout that component is placed in. So what's it in? -
Jpanel setBackground color thread safe?
is this method thread safe?
meaning do i have to use Invoke on the dispatch thread everytime or
it doesn't really matteris this method thread safe?
meaning do i have to use Invoke on the dispatch
thread everytime or
it doesn't really matterThat's not what thread safe means, but yes, you should be able to call it from any thread. -
Can not control the color in JOGL
I am a beginner to use JOGL.
I find that I can not control the color, both background and foreground. The background is always Black, and foreground is always Red.
I use canvas.setBackground(Color),
gl.glColor3*(), trying to change the color. But it does not work.
What is the problem?
Thanks.
TobyA big help for learning JOGL is reading the Red Book from OpenGL, which can be downloaded in pdf. Since JOGL is almost a direct wrapper, the function calls are identical.
To set the background color, you need to add a GLEventListener to the GLCanvas that you're using. To set the background color, in your init() method for GLEventListener do:
public void init(GLAutoDrawable glad) {
GL gl=glad.getGL();
gl.glClearColor(r,g,b);
or something similar, I'm not on my normal computer so this was all from memory. Check the JOGL API for the exact method name for glClearColor. To change the foreground color, there are a bunch of various methods that are all similar to glColor3f(float r,float g,float b).
Calling this on the GL object in the display() method will set the foreground color and everything drawn that isn't using lighting will use this color. -
Help with getting button color.
I'm trying to make a little paint program. i want to be able to click on a color button and then assign the color of that button to a variable Color brushColor.
funny thing is, when i compile this, it tells me that
C:\java\javaprograms\TryPainting.java:21: getBackground() in java.awt.Component cannot be applied to (java.awt.Button)
brushColor = paintTheBrush(getBackground(source));
strange, getBackground is explicitly listed as a method that Button inherits from Component in the API.
any suggestions on a way to accomplish this?
thanks in advance,
jason
------code follows-------
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
//colored buttons of "paint"
class OilPaint extends Button{
Color brushColor = Color.white;
OilPaint(String label, Color color) {
setLabel(label);
setForeground(color);
setBackground(color);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Button source = (Button)e.getSource();
brushColor = getBackground(source);
public Color paintTheBrush(Color color) {
return color;
// canvas to paint on - this isn't working yet. can't even get the
// setSize to work, though it does compile.
class Canvas extends JPanel{
Canvas(){
setBackground(Color.white);
Dimension canSize = new Dimension(300,300);
setSize(canSize);
// displays the lsit of color button choices in a small panel at bottom
// of window
class ColorChoices extends JPanel{
ColorChoices() {
setBackground(new Color(220,255,255));
add(new OilPaint("paint",Color.blue));
add(new OilPaint("paint",Color.red));
add(new OilPaint("paint",Color.green));
add(new OilPaint("paint",Color.white));
add(new OilPaint("paint",Color.black));
//this is the main class of the program TryPainting.java
class TryPainting {
public static void main(String[] args) {
JFrame window = new JFrame();
Toolkit toolkit = window.getToolkit();
Dimension winSize=toolkit.getScreenSize();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(5,5,winSize.width/2,winSize.height/2);
Container content = window.getContentPane();
content.setLayout(new BorderLayout());
content.add("North",new Canvas());
content.add("South",new ColorChoices());
window.setVisible(true);duh.. thanks man, that did the trick. i'm pretty new at this. i really appreciate the help. i got stuck thinking of the getBackground() as a function, rather than a method. this oop stuff is wacky weird fun!
jason -
How to change font/ font color etc in a graphic object using JCombobox?
Hello
My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
Below is my code; perhaps you'll understand more looking at code.
public class main...
Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
ColorList = new JComboBox(Colors);
ColorList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
JComboBox cb = (JComboBox)ev.getSource();
Color colorType = (Color)cb.getSelectedItem();
drawingBoard.setBackground(colorType);
});;1) providing the GUI is correctly implemented with components
2) Combobox stores the colors in an array
3) ActionListener should do following job: (but cant get it right - that is where my problem is)
- once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
public class DrawingBoard extends JPanel {
private String message;
public DrawingBoard() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
message = "";
public void setMessage(String m) {
message = m;
repaint();
public void paintComponent(Graphics g) {
super.paintComponent(g);
//setBackground(Color.RED);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint
g2.drawString(message, 50, 50);
public void settingFont(String font) {
//not sure how to implement this? //Jcombobox should pass an item to this
//it should match against all known fonts in system then set that font to the graphics
private void settingFontSize(Graphics g, int f) {
//same probelm with above..
public void setBackgroundColor(Color c) {
setBackground(c);
repaint(); // still not sure if this done corretly.
public void setFontColor(Color c) {
//not sure how to do this part aswell.
//i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
My problems have been highlighted in the comments of code above.
Any help will be much appreciated thanks!!!It is the completely correct code
I hope that's what you need
Just put DrawingBoard into JFrame and run
Good luck!
public class DrawingBoard extends JPanel implements ActionListener{
private String message = "message";
private Font font = new Font("Serif", Font.PLAIN, 10);
private Color color = Color.RED;
private Color bg = Color.WHITE;
private int size = 10;
public DrawingBoard(){
JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
cbFont.setActionCommand("font");
JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
cbSize.setActionCommand("size");
JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
cbColor.setActionCommand("color");
JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
cbBG.setActionCommand("bg");
add(cbFont);
cbFont.addActionListener(this);
add(cbSize);
cbSize.addActionListener(this);
add(cbColor);
cbColor.addActionListener(this);
add(cbBG);
cbBG.addActionListener(this);
public void setMessage(String m){
message = m;
repaint();
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(bg);//set background color
g2.fillRect(0,0, getWidth(), getHeight());
g2.setColor(color);//set text color
FontRenderContext frc = g2.getFontRenderContext();
TextLayout tl = new TextLayout(message,font,frc);//set font and message
AffineTransform at = new AffineTransform();
at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
g2.fill(tl.getOutline(at));
public void actionPerformed(ActionEvent e){
JComboBox cb = (JComboBox)e.getSource();
if (e.getActionCommand().equals("font")){
font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
}else if (e.getActionCommand().equals("size")){
size = ((Integer)cb.getSelectedItem()).intValue();
}else if (e.getActionCommand().equals("color")){
color = (Color)cb.getSelectedItem();
}else if (e.getActionCommand().equals("bg")){
bg = (Color)cb.getSelectedItem();
repaint();
} -
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 to change color of selected label from list of labels?
My Problem is that I have a list of labels. RowHeaderRenderer is a row header renderer for Jtable which is rendering list items and (labels).getListTableHeader() is a method to get the list. When we click on the label this code is executed:
getListTableHeader().addMouseListener(new MouseAdapter()
public void mouseReleased(MouseEvent e)
if (e.getClickCount() >= 1)
int index = getListTableHeader().locationToIndex(e.getPoint());
try
if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
AcknowledgeEvent ackEvent = new AcknowledgeEvent(
this, (ae_AlertEventInfo)theAlerts.values().toArray()[index]);
fireAcknowledgeEvent(ackEvent);
((HeaderListModel)listModel).setElementAt(ACK, index);
catch(Exception ex) {;}
Upon mouse click color of the label should be changed. For some period of time ie. Upto completion of fireAcknowledgeEvent(ackEvent);
This statement is calling this method:
public void handleAcknowledgeEvent(final AcknowledgeEvent event)
boolean ackOk = false;
int seqId = ((ae_AlertEventInfo)event.getAlertInfo()).sequenceId;
if (((ae_AlertEventInfo)event.getAlertInfo()).ackRequiredFlag)
try
// perform call to inform server about acknowledgement.
ackOk = serviceAdapter.acknowledge(seqId,
theLogicalPosition, theUserName);
catch(AdapterException aex)
Log.error(getClass(), "handleAcknowledgeEvent()",
"Error while calling serviceAdapter.acknowledge()", aex);
ExceptionHandler.handleException(aex);
else
// Acknowledge not required...
ackOk = true;
//theQueue.buttonAcknowledge.setEnabled(false);
final AlertEventQueue myQueue = theQueue;
if (ackOk)
Object popupObj = null;
synchronized (mutex)
if( hasBeenDismissed ) { return; }
// mark alert event as acknowledged (simply reset ack req flag)
ae_AlertEventInfo info;
Iterator i = theAlerts.values().iterator();
while (i.hasNext())
info = (ae_AlertEventInfo) i.next();
if (info.sequenceId == seqId)
// even if ack wasn't required, doesn't hurt to set it
// to false again. But it is important to prevent the
// audible from playing again.
info.ackRequiredFlag = false;
info.alreadyPlayed = true;
// internally uses the vector index so
// process the queue acknowledge update within
// the synchronize block.
final ae_AlertEventInfo myAlertEventInfo = event.getAlertInfo();
SwingUtilities.invokeLater(new Runnable()
public void run()
myQueue.acknowledge(myAlertEventInfo);
myQueue.updateAcknowledgeButtonState();
// here we should stop playing sound
// if it is playing for this alert.
int seqId1;
if (theTonePlayer != null)
seqId1 = theTonePlayer.getSequenceId();
if (seqId1 == seqId)
if (! theTonePlayer.isStopped())
theTonePlayer.stopPlaying();
theTonePlayer = null;
// get reference to popup to be dismissed...
// The dismiss must take place outside of
// the mutex... otherwise threads potentially
// hang (user hits "ok" and is waiting for the
// mutex which is currently held by processing
// for a "move to summary" transition message.
// if the "dismiss" call in the transition
// message were done within the mutex, it might
// hang on the dispose method because the popup
// is waiting for the mutex...
// So call popup.dismiss() outside the mutex
// in all cases.
if(event.getSource() instanceof AlertEventPopup)
popupObj = (AlertEventPopup)event.getSource();
else
popupObj = thePopups.get(event.getAlertInfo());
thePopups.remove(event.getAlertInfo());
SwingUtilities.invokeLater(new Runnable()
public void run()
// search vector elements to determine icon color in main frame
String color = getColor();
fireUpdateEvent(new UpdateEvent(this, blinking, color));
// Call dismiss outside of the mutex.
if (popupObj !=null)
if(popupObj instanceof AlertEventPopup)
((AlertEventPopup)popupObj).setModal(false);
((AlertEventPopup)popupObj).setVisible(false); // xyzzy
((AlertEventPopup)popupObj).dismiss();
else
// update feedback... ack failed
SwingUtilities.invokeLater(new Runnable()
public void run()
myQueue.setInformationMessage("Acknowledge failed to reach server... try again");
return;
Code for RowHeaderRenderer is:
class RowHeaderRenderer extends JLabel implements ListCellRenderer
JTable theTable = null;
ImageIcon image = null;
RowHeaderRenderer(JTable table)
image = new ImageIcon(AlertEventQueue.class.getResource("images" + "/" + "alert.gif"));
theTable = table;
JTableHeader header = table.getTableHeader();
setOpaque(true);
setHorizontalAlignment(LEFT);
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
public Component getListCellRendererComponent( JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
int level = 0;
try
level = Integer.parseInt(value.toString());
catch(Exception e)
level = 0;
if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
this.setHorizontalAlignment(JLabel.CENTER);
this.setVerticalAlignment(JLabel.CENTER);
setIcon(image);
else
setBorder(BorderFactory.createLineBorder(Color.gray));
setText("");
setIcon(null);
return this;
I tried but when i am clicking a particular label, the color of all labels in the List is being changed. So can you please assist me in changing color of only the label that is selected and the color must disappear after completion of Upto completion of fireAcknowledgeEvent(ackEvent);im a bit confused with the post so hopefully this will help you, if not then let me know.
I think the problem is that in your renderer your saying
setBackground(header.getBackground());which is setting the backgound of the renderer rather than the selected item, please see an example below, I created a very simple program where it adds JLabels to a list and the renderer changes the colour of the selected item, please note the isSelected boolean.
Object "value" is the currentObject its rendering, obviously you may need to test if its a JLabel before casting it but for this example I kept it simple.
populating the list
public void populateList(){
DefaultListModel model = new DefaultListModel();
for (int i=0;i<10;i++){
JLabel newLabel = new JLabel(String.valueOf(i));
newLabel.setOpaque(true);
model.addElement(newLabel);
this.jListExample.setModel(model);
this.jListExample.setCellRenderer(new RowHeaderRenderer());
}the renderer
class RowHeaderRenderer extends JLabel implements ListCellRenderer
JTable theTable = null;
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus){
JLabel aLabel = (JLabel)value;
if (isSelected){
aLabel.setBackground(Color.RED);
}else{
aLabel.setBackground(Color.GRAY);
return aLabel;
}
Maybe you are looking for
-
Apple 5C voicemail doesn't work even after Apple Support
About a month ago, I purchased an iPhone 5C and the voicemail wouldn't set up. I called Apple support and they helped me upgrade to iOS 7.0.4 and the newest version of my carrier, Verizon. They then helped me call my own number and set up my personal
-
Grouping Key Figures via Web item?
Hi, in our webtemplates we would like to split the key figures (part of a structure) into two web items. Is it possible to split key figures, all part of one key figure structure, over two web items. Which webitem can handle this? Or does it require
-
i loaded the newest version of itunes and now neither my windows 7 computer nor itunes recognizes my ipod
-
Tracking of Changes in Material Determination type or Material Substitution
Hi Gurus, Can anybody suggest how to keep track of the changes made in VB11/VB12/VB13 which is for Material Determination type Maintenance? Is there any TCODE or tables for tracking the above changes?? Thanks in advance VIJAYB.
-
Invoke SaveAs dialog using a JSP
Hi all, Can anyone tell me how to invoke the SaveAs dialog window from a JSP so that the user can save a file? Thanks in advance, Graham