I have an applet I have written that has a JLabel (containing an ImageIcon) and a custom ImagePanel inside a JPanel. For some reason the JLabel NEVER shows up in safari and firefox on mac os on first run/load but on other OSes (windows,linux) it appears fine. Now in the same applet there's a button that flips the image to another image. On safari/firefox on mac os, when the button is clicked, the second image shows, the when clicked again, the first image now appears!! Any idea what could be causing this issue? Even on safari for windows the applet works fine.. i.e. first image loads and appears.
UI code
public void createUI(){
mainpanel = new JPanel();
mainpanel.setMaximumSize(new Dimension(154, 212));
mainpanel.setMinimumSize(new Dimension(154, 212));
mainpanel.setName("mainPanel");
mainpanel.setLayout(new BorderLayout());
lcdpanel = new ImagePanel(bgLcdImage);
lcdpanel.setBounds(22, 22, 110, 28);
bgImage = Toolkit.getDefaultToolkit().createImage(bytes);//BufferedImage
label = new JLabel(new ImageIcon(bgImage));
mainpanel.add(lcdpanel);
mainpanel.add(label);
mainpanel.invalidate();
getContentPane().add(mainpanel);
repaint();
}
Button click code
private void flipImage()
{
label.setIcon(new ImageIcon(backImg));
label.repaint();
lcdpanel.setVisible(false);
lcdpanel.repaint();
mainpanel.repaint();
this.repaint();
}
Any help would be appreciated.Thanks
I even made the jlabel as a imagepanel, set the layout of jpanel to null
Setting the layout to null is the worst thing you can do. That will generally cause more problems than solve a problem.
The issue is not where i want the jlabel to be shown but WHY its not showing on Mac OS X firefox/safari browsers when it shows on windows/linux firefox/safari browsers.
How do we know when only a few lines of code are posted? Post a proper SSCCE when you have a problem.
On safari/firefox on mac os, when the button is clicked, the second image shows, the when clicked again, the first image now appears!!
The general format when adding/removing components on a visible GUI is to do:
panel.add(...);
panel.revalidate();
panel.repaint(); // sometimes needed
You never need to invoke repaint when you change the property of a component. Swing is smart enough to do the repaint for you.
label.setIcon(new ImageIcon(backImg));
//label.repaint();
Related
I have a slightly complicated JavaFX GUI with the following component structure (simplified) as shown below. You will see that a SwingNode is used to contain the main bulk of the application, but I cannot tell you the design principle behind this since I didn't write the original code.
I am aware of various cautions about occasional odd behaviour when Swing & JavaFX are mixed, but there isn't the time at present to re-write the UI. The application is built to run on a Windows 7/8/10 platform, and what I'm seeing is as follows:
(a) On three different platforms I've tested (Windows XP native, Windows 7 VM, Windows 8 VM, different size monitors), when the application's Windows "maximize" decoration is clicked, the application resizes OK (by which I mean it is slightly jumpy and delayed, but the actual repainting to fill the screen is done correctly).
(b) However, on one further platform, the 'maximize' causes the entire content of the Stage to go white, and doesn't repaint properly until, say, a menu or one of its items is clicked. The machine in question is a Dell Optiplex 64-bit Windows 7 Pro SP1 with a DVI monitor of 1920 x 1080 sourced from an Intel HD Graphics 4600. ClearType is set to ON, and the version of Java is 1.8.0_73_b02.
There is one further question on SO regarding this issue, but it was created in June 2015 and never answered, so I'm not sure what to think.
Has anyone else come across this issue and/or feels able to comment on what might be causing it ? Is there some sort of 'revalidate/repaint' code, or JavaFX equivalent, which might be worth me trying as a workaround ?
public class Main extends Application
{
private SwingNode mainSwingNode = new SwingNode();
private JPanel mainPanel = new JPanel();
public void start(Stage primaryStage) throws Exception
{
BorderPane parent = new BorderPane(mainSwingNode);
Scene scene = new Scene(parent, 1024, 768);
// Build Swing components
SwingUtilities.invokeLater(() ->
{
createAndShowGUI();
mainSwingNode.setContent(mainPanel);
});
primaryStage.setScene(scene);
primaryStage.show();
}
public void createAndShowGUI()
{
mainPanel.setLayout(new BorderLayout());
// Setup canvas area & canvas rulers
mCanvasTabbedPane.setPreferredSize(new Dimension(800,600));
mainPanel.add(mCanvasTabbedPane, BorderLayout.CENTER);
menubar.initForActionsMap(menuActionsMap);
// Listen for property changes for site to enable/disable menus
ProjSingleton.getInstance().addPropertyChangeListener(menubar);
mainPanel.add(menubar, BorderLayout.NORTH);
// Setup show/hide sidebar button
btnShowSidebar = new JButton(menuActionsMap.get(ShowSidebarAction.class));
menubar.add(Box.createHorizontalGlue());
menubar.add(btnShowSidebar);
btnShowSidebar.setOpaque(false);
btnShowSidebar.setAlignmentX(JComponent.RIGHT_ALIGNMENT);
btnShowSidebar.setBorder(new EmptyBorder(new Insets(2,2,2,2)));
// Add site manager toolbar
sidebar.setLayout(new GridLayout(2, 0));
sidebar.setAlignmentX(JComponent.RIGHT_ALIGNMENT);
sidebar.add(siteManagementPanel);
sidebar.add(new JScrollPane(layerManagerView));
mainPanel.add(sidebar, BorderLayout.EAST);
Main.statusBar = new StatusBar();
Main.statusBar.setCanvasTabbedPane(mCanvasTabbedPane);
mainPanel.add(Main.statusBar, BorderLayout.SOUTH);
mainPanel.setVisible(true);
}
....
....
}
I have an Applet program, which can be run from Eclipse directly for testing. I am setting window size of this Applet. But, I am seeing sometimes the applet opens with smaller window rather than the actual window size is set, and sometimes it opens with the proper set size setSize(550, 650);
I couldn't get fix for why sometimes it opens with the smaller window. Could someone advise me to fix this issue?
public class HomeApplet extends Applet implements ActionListener
{
public void init() {
titleStr = "Welcome to Application Home page!";
connectBtn = new Button("Submit");
connectBtn.addActionListener(this);
add(connectBtn);
connectBtn.setBounds(100, 120, 90, 20);
connectBtn.setEnabled(true);
setLayout( null );
setSize(550, 650);
sharedImage = new ImageIcon("sameer15.jpg" ).getImage();
}
public void paint (final Graphics g)
{
//super.paint(g);
int x = getSize().width;
int c1 = x/2;
Font titleFont = new Font("Arial", Font.BOLD, 20);
g.setFont(titleFont);
g.drawString(titleStr, c1-170, 20);
Font connectFont = new Font("Arial", Font.BOLD, 15);
g.setFont(connectFont);
g.drawString(connectStr, c1-190, 80);
g.drawImage(sharedImage, 100, 100, this);
System.out.println("drawImage");
}
}
Could someone advise me to fix this issue?
That applet can be tested in AppletViewer by including an applet element in a code block at the top of the source code.
I.E. change:
public class HomeApplet extends Applet implements ActionListener
To something like:
/* <applet code=HomeApplet width=550 height=650></applet> */
public class HomeApplet extends Applet implements ActionListener
Then to compile and run:
prompt> javac HomeApplet.java
prompt> appletviewer HomeApplet.java
Note
setSize(550, 650);
This is just plain wrong for an applet. The size of an applet should be set in HTML or by other means. The applet (which is effectively a guest in a web page), does not have the right to resize itself (that would be like your guest visiting, and knocking out a wall for 'a little more space').
Questions
These are not rhetorical questions. Another way to put that is: I expect to see answers to these questions.
Why code an applet? If it is due to spec. by teacher, please refer them to Why CS teachers should stop teaching Java applets.
Why AWT rather than Swing? See my answer on Swing extras over AWT for many good reasons to abandon using AWT components.
Future problems
sharedImage = new ImageIcon("sameer15.jpg" ).getImage();
You'll begin to discover just how wrong this is when you see AccessControlException in the Java Console when testing in Applet Viewer from the command line, or embedded in a web page. ..But we can deal with that in a separate Q&A. ;)
The simple answer in Eclipse is:
If you have multiple java classes open and you "run" the program from a class other than the one with init() and setSize(550,650) then the window will default to small.
Open the class with the setSize() and run it from there. Problem solved.
This drove me nuts until I figured it out.
I am trying to make a JTabbedPane in Java 7 on OSX that has tabs positioned to the left with their text horizontal (instead of vertical). However, with the code:
import javax.swing.*;
import java.awt.Dimension;
class Probs extends JDialog {
JTabbedPane options = new JTabbedPane();
Probs(JFrame owner) {
//main constructor
super(owner, "User Preferences", true);
//set the tabs to be left aligned
options.setTabPlacement(JTabbedPane.LEFT);
//construct the authorization panel
JPanel authorization = new JPanel();
authorization.add(new JLabel("test"));
options.addTab("test", authorization);
add(options);
setSize(new Dimension(300,300)); //should use pack here
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
JFrame test = new JFrame();
new Probs(test);
test.dispose();
}
}
I get a dialog box which looks like: this image
I would like the tab text to be horizontal (the 'test' title on the tab be oriented horizontally instead of vertically).
I searched around on Google for a while and have only run into occurrences wherein people wanted to achieve vertical text on their tabs, I could not manage to locate any in which people wanted to have horizontal text (what I am trying to achieve).
In particular, I am trying to achieve something which exactly looks like the image mentioned in the first post of this question. It is basically the exact opposite of that question because the person in that tab started with what I am trying to achieve (I believe). Basically, I am trying to determine how to create the image displayed in the first post of that question.
Can someone please tell me how to have left-oriented tabs while preserving horizontal tab titles (as opposed to vertical)?
Thank you for your time and assistance.
Again, since I can't replicate the problem, Try this suggestion:
JPanel authorization = new JPanel();
authorization.add(new JLabel("test"));
options.addTab("", authorization);
JLabel labTab2 = new JLabel("test"); // create a label
options.setTabComponentAt(0, labTab2); // set it to the component
The alignment is determined by your operating system. If you want to change the alignment of the tab text, you have to change the look and feel of your swing application. This worked for me. See here.
The system look and feel at MacOSX didn't support what you want in JTabbedPane. You must create a customized JComponent to do this or to set the look and feel of your application to cross platform (java metal) as stated before by #MonkeySupersonic.
I suggest the readings:
Apple Java Development Guide (section: User Interface Toolkits for Java) - https://developer.apple.com/library/content/documentation/Java/Conceptual/Java14Development/04-JavaUIToolkits/JavaUIToolkits.html
mac User Interface Guidelines - https://developer.apple.com/macos/human-interface-guidelines
When I run the code it just opens an empty window
I also important whatever is necessary
relevant parts of the code:
public class Game extends JFrame implements ActionListener,KeyListener{
private JLabel background;
....
public Game(){
background=new JLabel(new ImageIcon("/graphics/board.gif"));
...
this.add(background);
this.setSize(800,600);
this.setVisible(true);...
I tried adding the JLabel to a JPanel and then add it to the frame but it still shows nothing in the window
Originally the code was:
JLabel background = new JLabel("/graphics/board.gif");
This would not set the image at the path described, Suggest that the following method is used (this could be simplified to just use a different JLabel constructor but steps shown for clarity)
Create and load the image and then set the icon for the Label As follows
ImageIcon icon = new ImageIcon("/graphics/board.gif");
JLabel background = new JLabel();
background.setIcon(icon);
Link to ImageIcon Java Doc
It is important to set in the layout the order in which the elements are displayed , maybe you have something that is displayed over the label..
I'm guessing you have a directory structure something like:
-c:\java
- source (for source and class files)
- graphic (for your images)
background=new JLabel(new ImageIcon("/graphics/board.gif"));
Don't specify the leading "/" in the file name. That tells Java to look at the root of the C drive, not at the directory where your class is executing from.
Also, don't use:
this.setSize(800,600);
The image does not stretch to fill the size of the frame. Intead you should be using:
this.pack();
so the frame will be the size of the image.
I have the following code to make a custom looking JButton
ImageIcon icon = createImageIcon(
CommonUtils.class.getClassLoader().getResource("images/wright.png")
);
RightSlide.setIcon( icon );
ImageIcon icon2 = createImageIcon(
CommonUtils.class.getClassLoader().getResource("images/right_selected.png")
);
RightSlide.setPressedIcon( icon2);
RightSlide.setSelectedIcon(icon2);
RightSlide.setRolloverEnabled(true); // turn on before rollovers work
RightSlide.setRolloverIcon(icon2);
RightSlide.setBorderPainted(false);
RightSlide.setFocusPainted(false);
RightSlide.addActionListener(new ActionListener(){
The code generates a custom button. The button behaves as expected when hover over, pressed, clicked, and selected. This works on MacOS and Linux (Ubuntu). But the same code has a light blue background on Windows. Where does this come from and how do I get rid of it ?
Thanks
I think that you missing JButton#setContentAreaFilled(false); example here