Changing JFrame Color
Hello ........
I Have an Application(JFrame) With several panels in its content pane at different times. I changes the background colors of all the panels say (blue). But there is an outline in gray around the frame (I suppose)
I have also used frame.setbackground(Color.blue);
But that doesnt change that color.
What can I do cause its kind of visible and doesnt look so nice when everything else is in another color.
Thanks
Shirantha.
Hi,
I found why there is no method to set the border in frame.
All other components in inherit from JComponent so they also get the
setBorder inherited.
But JFrame does not. JFrame is extended by Frame which is extended by Window. Window does not have a border or title bar and buttons.
So if I could do something so JFrame will not have a border, it might work.
But I still have no idea on this
Shirantha
Similar Messages
-
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 -
Changing background color in JTable, only changes one row at a time...
I'm trying to change the color of rows when the 5th column meets certain criteria. I think I'm very close, but I've hit a wall.
What's happening is the row will change color as intended when the text in the 5th column is "KEY WORD", but when I type "KEY WORD" in a different column it will set the first row back to the regular colors. I can easily see why it's doing this, everytime something is changed it rerenders every cell, and the listener only checks the cell that was just changed if it met the "KEY WORD" condition, so it sets every cell (including the previous row that still meets the condition) to the normal colors. I can't come up with a good approach to changing the color for ALL rows that meet the condition. Any help would be appreciated.
In this part of the CellRenderer:
if (isSelected)
color = Color.red;
else
color = Color.blue;
if (hasFocus)
color = Color.yellow;
//row that meets special conditions
if(row == specRow && col == specCol)
color = color.white; I was thinking an approach would be to set them to their current color except for the one that meets special conditions, but the two problems with that are I can't figure out how to getColor() from the table, and I'm not sure how I would initially set the colors.
Here's the rest of the relevant code:
public void tableChanged(TableModelEvent e)
int firstRow = e.getFirstRow();
int lastRow = e.getLastRow();
int colIndex = e.getColumn();
if(colIndex == 4)
String value = (String)centerTable.getValueAt(firstRow, colIndex);
// check for our special selection criteria
if(value.equals("KEY WORD"))
for(int j = 0; j < centerTable.getColumnCount(); j++)
CellRenderer renderer =
(CellRenderer)centerTable.getCellRenderer(firstRow, j);
renderer.setSpecialSelection(firstRow, j);
import javax.swing.table.*;
import javax.swing.*;
import java.awt.Component;
import java.awt.Color;
public 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.green;
if (isSelected)
color = Color.red;
else
color = Color.blue;
if (hasFocus)
color = Color.yellow;
if(row == specRow && col == specCol)
color = color.white;
//setForeground(color);
setBackground(color);
setText((String)value);
return this;
public void setSpecialSelection(int row, int col)
specRow = row;
specCol = col;
}If I'm still stuck and more of my code is needed, I'll put together a smaller program that will isolate the problem tomorrow.That worked perfectly for what I was trying to do, but I've run into another problem. I'd like to change the row height when the conditions are met. What I discovered is that this creates an infinite loop since the resizing triggers the renderer, which resizes the row again, etc,. What would be the proper way to do this?
Here's the modified code from the program given in the link. All I did was declare the table for the class, and modify the if so I could add the "table.setRowHeight(row, 30);" line.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
public class TableRowRenderingTip extends JPanel
JTable table;
public TableRowRenderingTip()
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data =
{"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
{"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
{"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
{"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
{"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
DefaultTableModel model = new DefaultTableModel(data, columnNames)
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Alternating", createAlternating(model));
tabbedPane.addTab("Border", createBorder(model));
tabbedPane.addTab("Data", createData(model));
add( tabbedPane );
private JComponent createAlternating(DefaultTableModel model)
JTable table = new JTable( model )
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
// Alternate row color
if (!isRowSelected(row))
c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
private JComponent createBorder(DefaultTableModel model)
JTable table = new JTable( model )
private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
private Border inside = new EmptyBorder(0, 1, 0, 1);
private Border highlight = new CompoundBorder(outside, inside);
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
JComponent jc = (JComponent)c;
// Add a border to the selected row
if (isRowSelected(row))
jc.setBorder( highlight );
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
public JComponent createData(DefaultTableModel model)
table = new JTable( model )
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
// Color row based on a cell value
if (!isRowSelected(row))
c.setBackground(getBackground());
String type = (String)getModel().getValueAt(row, 0);
if ("Buy".equals(type)) {
table.setRowHeight(row, 30);
c.setBackground(Color.GREEN);
if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
public static void createAndShowGUI()
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Table Row Rendering");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableRowRenderingTip() );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}Edited by: scavok on Apr 26, 2010 6:43 PM -
How can i change the color in textarea
Hi to all, i am making the chat application in java , i want to show the client message in different color in text area , i have only one window which shows both client and server messages . i am sending you my program can u tell me how to change the color.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class cwDraft extends JFrame {
static private JTextField enter;//user write text in this area
private JTextField ip;
static private JTextArea display;
JButton b1;
JButton connect;
static String s=" ";
static String s1=" ";
static String s2=" ";
static DatagramSocket socket;
static DatagramPacket packet;
cwDraft() {
super("chat server");
setSize(400, 300);
Container c = getContentPane();
//c.setLayout(new FlowLayout());-
display=new JTextArea();
display.setToolTipText("display area");
c.add(new JScrollPane(display),BorderLayout.CENTER);
ip=new JTextField("127.0.0.1",15);
ip.setToolTipText("enter ip here");
c.add(ip,BorderLayout.EAST);
enter=new JTextField(30);
enter.setToolTipText("enter message");
c.add(enter,BorderLayout.NORTH);
b1 = new JButton("Send");
b1.setToolTipText("send message");
b1.addActionListener(new B1Listener());
connect=new JButton("connect");
connect.setToolTipText("connect to other computer");
c.add(connect,BorderLayout.SOUTH);
connect.addActionListener(new ConnectListener() );
//enter=new JTextField();
c.add(b1,BorderLayout.WEST);
show();
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
} // constructor
public static void main(String[] args) {
new cwDraft();
try {
socket = new DatagramSocket(3082);
} catch(Exception ex) {
ex.printStackTrace();
do {
byte data[] = new byte[100];
packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
//display.append(s2);
} catch(Exception ex) {
ex.printStackTrace();
s1 = new String(packet.getData(), 0, packet.getLength());
//System.out.println(s);
display.append(packet.getAddress() +"says"+ s1 +"\n");
} while(true);
} // main
private class B1Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
s = enter.getText();
byte data[] = s.getBytes();
try {
// packet1 = new DatagramPacket(data, data.length);
packet = new DatagramPacket(data, data.length, InetAddress.getByName(ip.getText()), 3082);
socket.send(packet);
display.append(packet.getAddress() +"says"+ s +"\n");
} catch(Exception ex) {
ex.printStackTrace();
//enter.setText(s2);
} // actionPerformed
} // B1Listener
private class ConnectListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//String s1=" ";
byte data[]=s.getBytes();
try {
packet = new DatagramPacket(data, data.length, InetAddress.getByName(ip.getText()), 3082);
display.append("connected to:" + packet.getAddress() +"\n");
catch(Exception ex) {
ex.printStackTrace();
} // classimport javax.swing.*;
import javax.swing.text.*;
import java.awt.Color;
public class MultiColouredText extends JFrame {
public MultiColouredText() {
StyledDocument doc = new DefaultStyledDocument();
JTextPane pane = new JTextPane(doc);
pane.setEditable(false);
pane.setFont(new java.awt.Font("Verdana", 0 , 16));
MutableAttributeSet mas = new SimpleAttributeSet();
try {
StyleConstants.setForeground(mas, Color.yellow);
StyleConstants.setBackground(mas, Color.blue);
doc.insertString(doc.getLength(), " Hello ", mas);
StyleConstants.setForeground(mas, Color.blue);
StyleConstants.setBackground(mas, Color.yellow);
doc.insertString(doc.getLength(), " World ", mas);
StyleConstants.setForeground(mas, Color.red);
StyleConstants.setBackground(mas, Color.green);
doc.insertString(doc.getLength(), " And ", mas);
StyleConstants.setForeground(mas, Color.green);
StyleConstants.setBackground(mas, Color.red);
doc.insertString(doc.getLength(), " Farewell ", mas);
catch (Exception ignore) {}
getContentPane().add(pane);
setSize(250,56);
show();
public static void main(String[] args) {
new MultiColouredText();
} -
How to change button colors in a loop?
I am working on a task that should imitate an elevator. I have two vertical
rows of round buttons "Up" and "Down" When a circle is selected randomly by
the program, the circle becomes yellow and the elevator moves to that
button.
Here is what I did:
1. created a class Circle where I save buttons' parameters
2. saved Circle objects in an array
3. drew the buttons depending on their parameters
4. generated a random number, matched it with an array index and assigned
the object color to yellow.
Everything is fine except that I can't figure out how to change colors of my
buttons in a loop.
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Elevator3 extends JPanel
private int n = 40;
private int width = 200;
private int floors = 10;
private int interval = 1000;
private boolean selected = false;
private Circle[] buttons = new Circle[2*(floors-1)];
public Elevator3()
build();
JFrame frame = new JFrame("Elevator3");
setBackground(Color.WHITE);
setFont(new Font("SansSerif", Font.PLAIN, Math.round(n/3)));
frame.getContentPane().add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, n*(floors+2) );
frame.setVisible(true);
public void build()
Random r = new Random();
int buttonPick;
int timeUntilNextButton = r.nextInt(interval);
for (int k =0; ; k++)
if (timeUntilNextButton-- ==0)
buttonPick = r.nextInt(2*(floors-1));
//populate my buttons array here - how??
timeUntilNextButton = r.nextInt(interval);
//adding "Down" buttons
for (int i=1, count=0; i < floors; i++, count++)
if (count == buttonPick)
selected = true;
else
selected = false;
buttons[count]= new Circle(n*2, n*i, selected, Math.round(n/2));
//build an array of "Up" circles
for (int i=2, count=floors-1; i < floors+1; i++, count++)
if (count == buttonPick)
selected = true;
else
selected = false;
buttons[count]= new Circle(n, n*i, selected, Math.round(n/2));
public static void main(String[] args)
new Elevator3();
protected void paintComponent(Graphics g)
super.paintComponent(g);
//draw buttons
for (int i=0; i < buttons.length; i++)
g.setColor(buttons.getColor());
g.fillOval(buttons[i].getX(), buttons[i].getY(), buttons[i].getWidth(), buttons[i].getWidth());
class Circle
private int x;
private int y;
private Color c;
private boolean pressed;
private int width;
public Circle(int xCoordinate, int yCoordinate, boolean selected, int diameter)
x = xCoordinate;
y = yCoordinate;
pressed = selected;
width = diameter;
if (pressed)
c = Color.YELLOW;
else
c = Color.LIGHT_GRAY;
public Color getColor()
return c;
public int getX()
return x;
public int getY()
return y;
public int getWidth()
return width;hi,
am sorry, i couldn't make out what exactly the problem, but as ur subject line says...
may be the code give below will help you to change button colors in a loop..
for(int i = 0; i < button.length; i++){
int color1 = (int)(250*Math.random());
int color2 = (int)(250*Math.random());
int color3 = (int)(250*Math.random());
Color c = new Color(color1,color2,color3);
button[i] = new JButton("button name");
button.addActionListener(this);
//to check the r, g, b combination.
//System.out.println(c);
button[i].setBackground(c);
button[i].setForeground(Color.white);
//adding into the panel
panel.add(button[i]);
hope this would help you. -
How to change the color of a title bar
Hello !
I try to change the color from my title bars, but I fail.
I tried to change the activeCaption value to an other colour, but that didn�t work. Currently I use a own LAF and set it with UIManager.setLookAndFeel("dpg.beans.GuiWindowsLookAndFeel");
import javax.swing.UIDefaults;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
public class GuiWindowsLookAndFeel extends WindowsLookAndFeel {
protected void initSystemColorDefaults(UIDefaults table) {
String[] colors = {
"activeCaption", "#B0171F"
loadSystemColors(table, colors, false);
}I also used the complete stringarray from WindowsLookAndFeel and only changed that one color. Still no changes.
Any ideas ?import javax.swing.*;
import java.awt.*;
class Testing
public void buildGUI()
UIManager.put("activeCaption", new javax.swing.plaf.ColorUIResource(Color.YELLOW));
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame();
f.setSize(200,100);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
} -
Change the color of the text in textpane
please suggest me how to change the color of the selected text color in textpane in jpanel
class ComposeMailPanel extends JPanel implements ListSelectionListener, ActionListener, ItemListener
JFrame frame;
JTextPane jtextpane;
JButton bInsertPic;
JButton bBackgroundColor;
JButton bForegroundColor;
JFileChooser selectedFile;
JFileChooser insertIconFile;
JColorChooser backgroundChooser;
JColorChooser foregroundChooser;
JComboBox fontSize;
SimpleAttributeSet sas;
MutableAttributeSet sas1;
StyleContext sc;
DefaultStyledDocument dse;
JScrollPane mainScrollPane;
RTFEditorKit rtfkit;
JComboBox fontFamily;
MutableAttributeSet mas;
Color backgroundColor;
Color foregroundColor;
String SF = "";
public ComposeMailPanel()
setLayout(null);
bInsertPic = new JButton("Insert picture");
add(bInsertPic);
bInsertPic.setBounds(150,460,110,20);
bInsertPic.setBackground(new Color(0,139,142));
bInsertPic.setForeground(new Color(255,255,255) );
bInsertPic.setBorder(borcolor);
bInsertPic.addActionListener(this);
bForegroundColor = new JButton("Set foreground color");
add(bForegroundColor);
bForegroundColor.setBounds(270,460,130,20);
bForegroundColor.setBackground(new Color(0,139,142));
bForegroundColor.setForeground(new Color(255,255,255) );
bForegroundColor.setBorder(borcolor);
bForegroundColor.addActionListener(this);
fontFamily=new JComboBox();
combofontfamilyinitialize();
add(fontFamily);
fontFamily.setBounds(420,460,110,20);
fontFamily.setBackground(new Color(0,139,142));
fontFamily.setForeground(new Color(255,255,255) );
fontFamily.setBorder(borcolor);
fontFamily.addItemListener(this);
fontSize = new JComboBox();
add(fontSize);
fontSize.setBounds(550,460,40,20);
fontSize.setBackground(new Color(0,139,142));
fontSize.setForeground(new Color(255,255,255) );
fontSize.setBorder(borcolor);
fontSize.addItemListener(this);
combofontsizeinitialize();
sas = new SimpleAttributeSet();
sas1 = new SimpleAttributeSet();
sc = new StyleContext();
dse = new DefaultStyledDocument(sc);
rtfkit = new RTFEditorKit();
selectedFile = new JFileChooser();
insertIconFile = new JFileChooser();
backgroundChooser = new JColorChooser();
foregroundChooser = new JColorChooser();
JScrollPane scrollPane2 = new JScrollPane();
add(scrollPane2);
scrollPane2.setBounds(150,300,577,152);
jtextpane= new JTextPane();
scrollPane2.getViewport().add(jtextpane);
jtextpane.setBounds(150,300,572,150);
jtextpane.setDocument(dse);
jtextpane.setContentType( "text/html" );
jtextpane.setEditable( true );
jtextpane.setBackground(new Color(255,255,255));
//jtextpane.setFont(new Font( "Serif", Font.PLAIN, 12 ));
jtextpane.setForeground(new Color(0,0,0) );
setBackground(new Color(0,139,142));
}//constructor
public void combofontfamilyinitialize ()
GraphicsEnvironment ge1 = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] k = ge1.getAvailableFontFamilyNames();
fontFamily= new JComboBox(k);
public void combofontsizeinitialize ()
//This function fills the combo box with font sizes
fontSize.addItem("8");
fontSize.addItem("9");
fontSize.addItem("10");
fontSize.addItem("11");
fontSize.addItem("12");
fontSize.addItem("14");
public void setAttributeSet(AttributeSet attr)
//This function only set the specified font set by the
//attr variable to the text selected by the mouse
int xStart, xFinish, k;
xStart = jtextpane.getSelectionStart();
xFinish = jtextpane.getSelectionEnd();
k = xFinish - xStart;
if(xStart != xFinish)
dse.setCharacterAttributes(xStart, k, attr, false);
else if(xStart == xFinish)
//The below two command line updates the JTextPane according to what
//font that is being selected at a particular moment
mas = rtfkit.getInputAttributes();
mas.addAttributes(attr);
//The below command line sets the focus to the JTextPane
jtextpane.grabFocus();
public void actionPerformed(ActionEvent ae1)
JComponent b = (JComponent)ae1.getSource();
String str3 = null;
frame = new JFrame();
if(b == bInsertPic)
System.out.println("inside insertpic");
insertIconFile.setDialogType(JFileChooser.OPEN_DIALOG);
insertIconFile.setDialogTitle("Select a picture to insert into document");
if(insertIconFile.showDialog(frame,"Insert") != JFileChooser.APPROVE_OPTION)
System.out.println("inside icon");
return;
File g = insertIconFile.getSelectedFile();
ImageIcon image1 = new ImageIcon(g.toString());
jtextpane.insertIcon(image1);
jtextpane.grabFocus();
else if(b == bForegroundColor)
foregroundColor = foregroundChooser.showDialog(frame, "Color Chooser", Color.white);
if(foregroundColor != null)
String s1=jtextpane.getSelectedText();
StyleConstants.setForeground(sas, foregroundColor);
setAttributeSet(sas);
public void itemStateChanged(ItemEvent ee5) {
JComponent c = (JComponent)event.getSource();
boolean d;
if(c == fontFamily)
String j = (String)fontFamily.getSelectedItem();
StyleConstants.setFontFamily(sas, j);
setAttributeSet(sas);
else if(c == fontSize)
String h = (String)fontSize.getSelectedItem();
int r = Integer.parseInt(h);
StyleConstants.setFontSize(sas, r);
setAttributeSet(sas);
thanks in advanceLearn how to use the forum correctly by posting formatted code.
Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html]Text Component Features. -
Trying to change the color of a single cell
hi, I am trying to change the color of a single cell when mouse moves over it, but couldn't do it. i even tried my own renderer, but it doesn't work. can anybody help ?
Here is what I am trying to do. I am displaying some data in a java JTable retrieved from a table in database. What is needed is when user moves his mouse over any cell in the third column, the cursor should change to hand cursor and possibly the background color should also change, to indicate the user that this cell is clickable. I have to show some other report when user clicks any cell in column three. The code follows as
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import javax.sql.rowset.*;
import javax.swing.table.*;
public class MouseMotionInTable extends JFrame
public static void main(String[] args)
MouseMotionInTable f = new MouseMotionInTable();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
int w = dim.width;
int h = dim.height;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds((w-600)/2, (h-300)/2, 600, 300);
f.setVisible(true);
MouseMotionInTable()
Connection con = null;
CachedRowSet crs = null;
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:FMS", "", "");
Statement st = con.createStatement();
String query = "SELECT ItemName, Alias, ItemReOrderQuty, ItemMeasure FROM ItemInfo";
ResultSet rs = st.executeQuery(query);
crs = new com.sun.rowset.CachedRowSetImpl();
crs.populate(rs);
st.close();
catch (SQLException e)
e.printStackTrace();
catch (ClassNotFoundException e)
e.printStackTrace();
finally
if(con != null)
try
con.close();
catch (SQLException e)
e.printStackTrace();
DBTableModel model = new DBTableModel(crs);
table = new JTable(model);
JPanel center = new JPanel();
center.setLayout(new BorderLayout());
center.add(new JScrollPane(table), BorderLayout.CENTER);
add(center, BorderLayout.CENTER);
table.addMouseMotionListener(new MouseMotionAdapter()
public void mouseMoved(MouseEvent me)
int col = table.columnAtPoint(new Point(me.getX(), me.getY()));
int row = table.rowAtPoint(new Point(me.getX(), me.getY()));
if(col == 2)
Object val = table.getValueAt(row, col);
boolean isSelect = table.isCellSelected(row, col);
boolean focus = table.isCellSelected(row, col);
TableCellRenderer cellRender = table.getCellRenderer(row, col);
Component comp = cellRender.getTableCellRendererComponent(table, val, isSelect, focus, row, col);
comp.setCursor(new Cursor(Cursor.HAND_CURSOR));
comp.setBackground(Color.yellow);
private JTable table;
class DBTableModel extends AbstractTableModel
ResultSet rs;
ResultSetMetaData rsMeta;
DBTableModel(ResultSet rs)
try
this.rs = rs;
rsMeta = rs.getMetaData();
catch(SQLException e)
e.printStackTrace();
public int getColumnCount()
try
return rsMeta.getColumnCount();
catch(SQLException e)
e.printStackTrace();
return -1;
public String getColumnName(int c)
try
return rsMeta.getColumnName(c+1);
catch(SQLException e)
e.printStackTrace();
return "";
public int getRowCount()
try
rs.last();
return rs.getRow();
catch(SQLException e)
e.printStackTrace();
return -1;
public Object getValueAt(int r, int c)
try
rs.absolute(r+1);
return rs.getObject(c+1);
catch(SQLException e)
e.printStackTrace();
return "";
public boolean isCellEditable(int r, int c)
return false;
public Class getColumnClass(int c)
return getValueAt(0,c).getClass();
} -
How to change the color of the progress bar and string
Is their anyway to change the color of the progress bar and the string which shows the progress of the bar. The current color of the bar is purple and i would like it to be red or blue so that it stands out against the background of the JFrame i am using. I dont want to change the color of the JFrame
Thanks in advanceimport java.awt.*;
import javax.swing.*;
public class ProgressEx {
public static void main(String[] args) {
UIManager.put("ProgressBar.background", Color.WHITE);
UIManager.put("ProgressBar.foreground", Color.BLACK);
UIManager.put("ProgressBar.selectionBackground", Color.YELLOW);
UIManager.put("ProgressBar.selectionForeground", Color.RED);
UIManager.put("ProgressBar.shadow", Color.GREEN);
UIManager.put("ProgressBar.highlight", Color.BLUE);
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar pb1 = new JProgressBar();
pb1.setStringPainted(true);
pb1.setValue(50);
JProgressBar pb2 = new JProgressBar();
pb2.setIndeterminate(true);
Container cp = f.getContentPane();
cp.add(pb1, BorderLayout.NORTH);
cp.add(pb2, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
} -
Can it is possible to change the color of JButton???
dear
when i click the JButton the GRAY color is shown because
i use the setContentAreaFilled(true); it is necessary for me
but i want to change this color how can i do
i also used the setBackGround and setForeground
but when click the GRAY is not changed how can i do thisI find this program handy:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class Listing {
public static void main(String[] args) throws Exception {
UIDefaults defs = UIManager.getLookAndFeelDefaults();
ArrayList list = new ArrayList();
for(Iterator i = defs.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (value instanceof Color)
list.add(key);
Collections.sort(list);
JPanel panel = new JPanel(new GridLayout(0,1));
for(int i=0; i<list.size(); ++i) {
Object key = list.get(i);
String text = key.toString();
Color color = defs.getColor(key);
JLabel label = new JLabel(text, new ColorIcon(color), JLabel.LEFT);
panel.add(label);
JFrame f = new JFrame("Listing");
f.getContentPane().add(new JScrollPane(panel));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(f.getWidth(), 600);
f.setLocationRelativeTo(null);
f.setVisible(true);
class ColorIcon implements Icon {
public static final int ICON_WIDTH = 20;
public static final int ICON_HEIGHT = 16;
private Color color;
public ColorIcon(Color color) {
this.color = color;
public int getIconWidth() {
return ICON_WIDTH;
public int getIconHeight() {
return ICON_HEIGHT;
public void paintIcon(Component c, Graphics g, int x, int y) {
if (color != null) {
Color old = g.getColor();
g.setColor(color);
g.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
g.setColor(old);
}I think you are referring to "Button.select". To change it for all buttons, call:
UIManager.put("Button.select", Color.YELLOW); //etc... -
Changing a color for the whole Application
Hi,
Is there a way to change the color, default purple of swing to some other color(say green) for the whole application without using themes? Is it possible through UIManager.put()?
Regards
SridharThanks Michael,
I just modified your code to fit my needs.
import java.awt.*;
import javax.swing.*;
import java.util.Enumeration;
class ApplicationColor
public ApplicationColor()
setApplicationColor(new Color(88, 140, 165));
JFrame frame = new JFrame();
frame.setLocation(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel(new BorderLayout());
String[] temp = {"abc","123"};
JComboBox cbo = new JComboBox(temp);
JButton btn = new JButton("I'm a button");
jp.add(new JLabel("I'm a label"),BorderLayout.NORTH);
jp.add(cbo,BorderLayout.CENTER);
jp.add(btn,BorderLayout.SOUTH);
frame.getContentPane().add(jp);
frame.pack();
frame.setVisible(true);
public void setApplicationColor(Color color)
Enumeration enum = UIManager.getDefaults().keys();
while(enum.hasMoreElements())
Object key = enum.nextElement();
Object value = UIManager.get(key);
Color jfcBlue = new Color(204, 204, 255);
Color jfcBlue1 = new Color(153, 153, 204);
if (value instanceof Color)
if(value.equals(jfcBlue) || value.equals(jfcBlue1)){
UIManager.put(key, color);
public static void main(String[] args){new ApplicationColor();}
}Sridhar -
Change the color of text in the title bar
Hi,
I have a JFrame. I want to be able to change the color of the text in the title bar. Do any of you know how to do this ?
Please let me know.
Thanks
SangeethaIf you are using Windows, you do it through the Control Panel tool for customizing your desktop display. If you are using some other system, I don't know. You can't do it from your Java program.
-
How to remove and change the color of Java cup and border
Hi to all,
How to remove and change the color of Java cup and border.
Thanks in advance
khiz_engThis is just an Image. You would need to create your own image and call setIconImage(Image) on your JFrame.
-
Can't change the color of a JButton when selected
I'm unable to change the color of a JButton with the following code:
UIManager.put("Button.select", Color.cyan);
SwingUtilities.updateComponentTreeUI(this);
This works just fine with 1.2.2 but when I use 1.3.1 the JButton turns gray instead of cyan. What changed between these versions?Hello,
I tested the following code and it works on JDK1.3.1:
import java.awt.*;
import javax.swing.*;
public class RedButton {
public static void main(String args[]) {
JFrame frame = new JFrame("Red");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
Container c = frame.getContentPane();
JButton defaultColor =
new JButton("Default Colors");
c.add(defaultColor, BorderLayout.NORTH);
UIManager.put("Button.background",
Color.RED);
JButton red =
new JButton("Red");
c.add(red, BorderLayout.SOUTH);
frame.setSize(200, 100);
frame.show();
You also can use one of the following properties, instead of background:
Button.background
Button.border
Button.darkShadow
Button.focusInputMap
Buton.font
Button.foreground
Button.highlight
Button.light
Button.margin
Button.shadow
Button.textIconGap
Button.textShiftOffset
So, as you can see, there is no select Option.
Maybe you are looking for
-
Question about image quality! *please help*
Hello everyone! I'm actually a beginner at FCP, so sorry if this question sounds kinda dumb: I just shot a video in a DVX100, and imported it onto FCP. When I play the video on the viewer, the quality of the image looks just fine. When I put it on th
-
Strange output from format command
Hi, We have a Sun V480 running Solaris 8. We have installed 2 SG-XPCI2FC-QF2 fibercards. They are connected to an EVA3000 system. SFS newest version are also installed. Have configured the cards with the cfgadm command. But when i run a format comman
-
Problem charging 0MATERIAL INFOOBJECT Hierarchy from R/3 into BW
Hi everyone, I'm having this problem when trying to load data into this infoobject's hierarchy. The problem is that i'm recieving an information IDOC with status 8. it's message says that the table that the process is trying to get the data from in
-
I have been going through procedure to create a File - Mail scenario. I was going through the SDN TV link for the same and it is told that no target DT creation is required and need to download from market place. https://www.sdn.sap.com/irj/servlet/p
-
Wage type missing on remuneration statement
Hello Experts, We made a bonus pay on Jan. through off-cycle payroll. On the remuneration statement we can not see this wage type. But we know it has been created because the Annual gross cumulation is correct. Does any one know in which table the wa