I used the following line of code to change a JFrame icon in IntelliJ on a Linux platform:
myFrame.setIconImage(IMAGE_CIRCLE_ICON_RED.getImage());
The icon is displayed however it is a transparent icon and it doesn't display as transparent. How can I make my frame icon render as a transparent icon?
Here is a link to the icon.
IconRedCircleTransparent
It looks like a red circle surrounded by a grey square. My frame is ocean blue.
It looks very much like this bug: [#JDK-6429220] Default LAF decorated frame does not support transparent icons - Java Bug System
import java.net.*;
import javax.swing.*;
public class TransparentIconTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon(
new URL("http://i.stack.imgur.com/AnvwU.png"));
f.setIconImage(icon.getImage());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Seems to work just fine here. Run the following source code. If you see transparency around the image, select the 'Yes' option in the option pane and you might see something like this as the output in the standard output stream.
This is the output here.
java.version: 1.7.0_25
java.runtime.version: 1.7.0_25-b17
java.vm.version: 23.25-b01
java.specification.vendor: Oracle Corporation
OK? true
This is the code used.
import java.awt.BorderLayout;
import java.net.URL;
import javax.swing.*;
public class TransparentPNG_2 {
private static String getPropertyString(String name) {
String eol = System.getProperty("line.separator");
String value = System.getProperty(name);
return String.format("%1s: \t%2s%3s", name, value, eol);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
JPanel ui = new JPanel(new BorderLayout());
URL url = new URL("http://i.stack.imgur.com/AnvwU.png");
ui.add(new JLabel(new ImageIcon(url)), BorderLayout.PAGE_START);
StringBuilder sb = new StringBuilder();
sb.append(getPropertyString("java.version"));
sb.append(getPropertyString("java.runtime.version"));
sb.append(getPropertyString("java.vm.version"));
sb.append(getPropertyString("java.specification.vendor"));
JTextArea output = new JTextArea(sb.toString().trim(), 4, 27);
ui.add(new JScrollPane(output));
int result = JOptionPane.showConfirmDialog(null, ui);
System.out.println(sb.toString());
System.out.println("OK? " + (result==JOptionPane.YES_OPTION));
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
SwingUtilities.invokeLater(r);
}
}
Related
Im a real novice at java coding and for just a little project I'd like the following code to be untouchable eg. anything behind the frame(and its contents) can be clicked on. But I don't know how to do it! I've searched everywhere but haven't found anything.
import java.awt.*;
import java.swing.*;
public class swag {
static Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
public static void main(String[] args)throws Exception{
JLabel lb = new JLabel();
lb.setFont(new Font("Century Gothic",Font.PLAIN,50));
lb.setHorizontalAlignment(SwingConstants.CENTER);
lb.setForeground(Color.WHITE);
lb.setBackground(Color.BLACK);
JFrame f = new JFrame();
f.setSize(dim.width,100);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.add(lb);
f.setVisible(true);
int r=255;int g=0;int b=0;
int a=80;int t=15;
while(true){
while(true){
lb.setText((System.currentTimeMillis()+""));
f.setBackground(new Color(r--,g++,0,a));
Thread.sleep(t);
if(r==0&&g==255){break;}
} while(true){
lb.setText((System.currentTimeMillis()+""));
f.setBackground(new Color(0,g--,b++,a));
Thread.sleep(t);
if(g==0&&b==255){break;}
} while(true){
lb.setText((System.currentTimeMillis()+""));
f.setBackground(new Color(r++,0,b--,a));
Thread.sleep(t);
if(b==0&&r==255){break;}
}}}
}//class
Note: haven't worked on efficiency yet :)
Read about the glass pane of JFrame. Using it you are able to show the UI components but block all user interactions.
Example:
public class FreezePane extends JComponent {
public FreezePane() {
// trap mouse, key, and focus events
addMouseListener( new MouseAdapter() );
addMouseMotionListener( new MouseMotionAdapter() );
addKeyListener( new KeyAdapter() );
addFocusListener( new FocusListener() {
// do not let any component take focus while visible
public void focusLost(FocusEvent e) {
requestFocusInWindow();
}
public void focusGained(FocusEvent e) {}
}
}
}
Then just set the glass pane and make it visible.
JFrame frame = new JFrame();
frame.setGlassPane( new FreePane() );
frame.getGlassPane().setVisible(true);
I'am using NetBeans and its WindowDesigner.
Having set focus to an JTextField I did two things in the Properties window:
First I set the TextField's disabledTextColor field to a red ( [0, 0, 51] ),
Second I set the TextField's enabled field to false.
Viewing the preview, nothing. Still plain gray.
Why is that and how can I change it?
you must have another issue, these basic Swing methods works for me
import java.awt.*;
import javax.swing.*;
public class InactiveBackgroundTest {
public JComponent makeUI() {
JTextField s0 = new JTextField("Very long Text");
s0.setEnabled(true);
s0.setForeground(Color.yellow);
s0.setBackground(Color.blue);
//UIManager.put("FormattedTextField.inactiveBackground", Color.RED);
JTextField s1 = new JTextField("Very long Text");
s1.setEnabled(false);
s1.setForeground(Color.yellow);
s1.setBackground(Color.blue);
s1.setDisabledTextColor(Color.yellow);
JTextField s2 = new JTextField("Very long Text");
s2.setEditable(false);
s2.setForeground(Color.yellow);
s2.setBackground(Color.blue);
s2.setDisabledTextColor(Color.yellow);
JPanel p = new JPanel();
p.setBackground(Color.black);
p.add(s0);
p.add(s1);
p.add(s2);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new InactiveBackgroundTest().makeUI());
f.setLocationRelativeTo(null);
f.pack();
f.setVisible(true);
}
}
I am creating a colour chooser and need to modify one of the colour chooser panels.
What I wanted was, I want to enter input values via the RGB fields to set the colour,The problem is the RGB values seem to be disabled is there a method within the api to turn on the RGB inputs to take a value?
Seems fine here.
import javax.swing.*;
class ColorChooserTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JColorChooser());
}
});
}
}
Is there anyway you can combine the RGB slider panel and the HSB panel?
Yes, apparently it is possible. Check this (very fragile, poorly laid out) example.
import java.awt.*;
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.border.*;
class ColorChooserTest2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JColorChooser cc = new JColorChooser();
AbstractColorChooserPanel[] panels = cc.getChooserPanels();
JPanel p = new JPanel();
panels[1].setBorder(
new TitledBorder(panels[1].getDisplayName()));
p.add(panels[1]);
panels[2].setBorder(
new TitledBorder(panels[2].getDisplayName()));
p.add(panels[2]);
JPanel gui = new JPanel(new BorderLayout(2,2));
gui.add(p, BorderLayout.CENTER);
gui.add(cc.getPreviewPanel(), BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
Javadoc for JPopupMenu constructor says the following:
JPopupMenu
public JPopupMenu(String label)
Constructs a JPopupMenu with the specified title.
Parameters:
label - the string that a UI **may** use to display as a title for the popup menu.
Key word being "may". Evidently in the default UI, such titles are ignored when creating a popup menu. I very much want such titles in some of my popup menus to be used regardless of whether or not the L&F thinks I should. I can't find the hook to make it so. Evidently, this is buried deep in the UI code somewhere. Is there a way to override this default?
Failing that, I have tried adding a disabled menu item as the first item of the menu. Trouble with that is then I lose control of its rendering, and it renders in the "greyed out" style instead of appearing as the important title. If I don't disable it, then it renders as I want, but is selectable, which a title would not be.
So bottom line, how do I either force the UI to display my title, or failing that, how do I add a non-selectable menu item at the top of the menu that I have full rendering control over?
I had similar problem (I mean the original question). I solved it this way:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
public class LabeledPopupMenu extends JPopupMenu
{
private String originalLabelText = null;
private final JLabel label;
private static String replaceHTMLEntities(String text)
{
if (-1 != text.indexOf("<") ||
-1 != text.indexOf(">") ||
-1 != text.indexOf("&"))
{
text = text.replaceAll("&", "&");
text = text.replaceAll("<", "<");
text = text.replaceAll(">", ">");
}
return text;
}
public LabeledPopupMenu()
{
super();
this.label = null;
}
public LabeledPopupMenu(String label)
{
super();
originalLabelText = label;
this.label = new JLabel("<html><b>" +
replaceHTMLEntities(label) + "</b></html>");
this.label.setHorizontalAlignment(SwingConstants.CENTER);
add(this.label);
addSeparator();
}
#Override public void setLabel(String text)
{
if (null == label) return;
originalLabelText = text;
label.setText("<html><b>" +
replaceHTMLEntities(text) +
"</b></html>");
}
#Override public String getLabel()
{
return originalLabelText;
}
}
I have tested it ony on Mac with default L&F, but it worked for me:
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.setVisible(true);
LabeledPopupMenu myPopup = new LabeledPopupMenu("Say & <something>");
myPopup.add(new JMenuItem("Sample item"));
myPopup.show(frame, 50, 50);
}
JPopup is very strange Container, didn't work me
1) public JPopupMenu(String label)
2) didn't work me alignment for JLabel, please maybe somebody can test text justify by using Html
3) not possible shows JComboBox dropdown popup is same time with JPopup (doesn't matter if is JPopup light or heavyweight)
4) and another (not important for basic Swing) tested Java5 and 6 with various LaF
import java.awt.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.*;
import javax.swing.plaf.*;
import org.pushingpixels.substance.api.skin.SubstanceOfficeSilver2007LookAndFeel;
class MyPopupMenuListener implements PopupMenuListener {
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
System.out.println("Canceled");
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Invisible");
}
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Visible");
}
}
public class PopupMenuListenerDemo {
public static void main(final String args[]) {
final JFrame frame = new JFrame("PopupSample Example");
/*SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(new SubstanceOfficeSilver2007LookAndFeel());
SwingUtilities.updateComponentTreeUI(frame);
} catch (UnsupportedLookAndFeelException e) {
throw new RuntimeException(e);
}
}
});
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
System.out.println(info.getName());
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}*/
UIResource res = new BorderUIResource.LineBorderUIResource(Color.red);
UIManager.put("PopupMenu.border", res);
JPopupMenu popupMenu = new JPopupMenu("Title");
//force to the Heavyweight Component or able for AWT Components
popupMenu.setLightWeightPopupEnabled(false);
PopupMenuListener popupMenuListener = new MyPopupMenuListener();
popupMenu.addPopupMenuListener(popupMenuListener);
JLabel lbl1 = new JLabel("My Title");
lbl1.setHorizontalAlignment(SwingConstants.CENTER);
popupMenu.add(lbl1);
JTextField text = new JTextField("My Title");
text.setHorizontalAlignment(SwingConstants.CENTER);
popupMenu.add(text);
String[] list = {"1", "2", "3", "4",};
JComboBox comb = new JComboBox(list);
popupMenu.add(comb);
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
popupMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find");
popupMenu.add(findMenuItem);
JButton btn = new JButton();
JLabel lbl = new JLabel("My Title");
lbl.setHorizontalAlignment(SwingConstants.CENTER);
btn.setComponentPopupMenu(popupMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(btn, BorderLayout.CENTER);
frame.add(lbl, BorderLayout.NORTH);
frame.setSize(350, 150);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(true);
}
});
}
}
5 and terrible alignment for JLabel if there is added JComboBox :-) brrrrr !!!!
Wasn't even aware of that feature :-)
Digging a bit, it turns out that MotifLookAndFeel is the only of the core LAFs which support a title in the popup. It's realized by a custom border. Which you can do as well:
JPopupMenu popup = new JPopupMenu("My Label");
popup.add("dummy menu item");
Border titleUnderline = BorderFactory.createMatteBorder(1, 0, 0, 0, popup.getForeground());
TitledBorder labelBorder = BorderFactory.createTitledBorder(
titleUnderline, popup.getLabel(),
TitledBorder.CENTER, TitledBorder.ABOVE_TOP, popup.getFont(), popup.getForeground());
popup.setBorder(BorderFactory.createCompoundBorder(popup.getBorder(),
labelBorder));
JComponent comp = new JPanel();
comp.setComponentPopupMenu(popup);
Note: as far as I can see, there is no safe way to detect whether or not the LAF handles the title itself (which would result in doubling it)
I'm completely new to Linux and have been trying to get my (Windows built) Java Swing projects to work correctly on XUbuntu on a separate machine from executable jar files I built.
I've reduced the problem to a minimum amount of code
import java.awt.Dimension;
import javax.swing.*;
public class JFrameTest extends JFrame {
public JFrameTest(String title) {
super(title);
JLabel lab = new JLabel("Label");
this.getContentPane().add(lab);
this.setMinimumSize(new Dimension(200, 200));
this.pack();
this.setVisible(true);
}
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JFrameTest frame = new JFrameTest("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
On Windows I see:
In Xubuntu I just see a grey box and the label, not the Title or close icons etc. I also have to kill (-9) the jvm after I've ctrl zedded from the command line. I launched it with java -jar filename.jar
My Linux machine is running Xubuntu 11. I've installed the sun Java 6_24 JRE. I Googled for this and found something similar relating to Compziz(?) but this was allegedly fixed a while back. I'm a bit stuck now. I have got one Swing app that works OK in that it responds to buttons OK but still doesn't show the Title etc. Any help would be much appreciated.
I don't use Xubuntu, but the general rule is that any code that updates a GUI should be executed on the Event Dispatch Thread. See the section from the Swing tutorial on Concurrency.
The examples from the Swing tutorial all use a format like this:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
add( new JLabel("Label") );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Suggestion: Start the GUI on the EDT. Vis.
import java.awt.Dimension;
import javax.swing.*;
public class JFrameTest extends JFrame {
public JFrameTest(String title) {
super(title);
JLabel lab = new JLabel("Label");
this.getContentPane().add(lab);
this.setMinimumSize(new Dimension(200, 200));
this.pack();
this.setVisible(true);
}
public static void main(String args[]) {
// Costruct & show the GUI on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JFrameTest frame = new JFrameTest("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
For more information see Concurrency in Swing.