I'm doing a project where i need some custom swing components. So far I have made a new button with a series of images (the Java Metal look doesn't fit with my UI at all). Ive implemented MouseListener on this new component and this is where my problem arises. My widget changes image on hover, click etc except my MouseListener picks up mouse entry into a the entire GridLayout container instead of into the image. So I have an image of about 200*100 and the surrounding container is about 400*200 and the mouseEntered method is fired when it enters that GridLayout section (even blank space parts of it) instead of over the image. How can I make it so that it is only fired when I hover over the image? Ive tried setting size and bounds and other attributes to no avail.
EDIT: Here's a demonstration of my issue. As you can see (sort of, colors are very similar) the bottom right button is highlighted just by entering its section of the GridlLayout. I only want it highlighted when I'm over the image actual, not the GridLayout section.
I Won't add the MouseListener methods because they just involve switching the displayed image.
public customWidget()
{
this.setLayout(new FlowLayout());
try {
imageDef=ImageIO.read(new File("/home/x101/Desktop/buttonDef.png"));
imageClick=ImageIO.read(new File("/home/x101/Desktop/buttonClick.png"));
imageHover=ImageIO.read(new File("/home/x101/Desktop/buttonHover.png"));
current=imageDef;
} catch (IOException e)
{
e.printStackTrace();
}
this.addMouseListener(this);
}
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(current, 0, 0, current.getWidth(), current.getHeight(), null);
}
EDIT: added code section
As an alternative, consider the The Button API, which includes the method setRolloverIcon() "to make the button display the specified icon when the cursor passes over it."
Addendum: For example,
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonIconTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private static void createAndShowGui() {
String base = "http://download.oracle.com/"
+ "javase/tutorial/uiswing/examples/components/"
+ "RadioButtonDemoProject/src/components/images/";
ImageIcon dog = null;
ImageIcon pig = null;
try {
dog = new ImageIcon(new URL(base + "Dog.gif"));
pig = new ImageIcon(new URL(base + "Pig.gif"));
} catch (MalformedURLException ex) {
ex.printStackTrace(System.err);
return;
}
JFrame frame = new JFrame("Rollover Test");
JPanel panel = new JPanel();
panel.add(new JLabel(dog));
panel.add(new JLabel(pig));
JButton button = new JButton(dog);
button.setRolloverIcon(pig);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I assume your image contains ONLY 4 'customWidget' objects (in a 2x2 grid).
Your code is working as I would expect. Your MouseListener methods are responding to MouseEvents for 'customWidget' (not the image drawn in 'customWidget'), which is sized to take up 1/4 of the image, so they will respond when it enters the enlarged area. The error is actually in your Test program, because you are allowing the custom button widget to be larger than the image.
If you want a Test program that provides an image similar to yours, you should create a larger grid (say 4x4), and then only place your buttons in every other grid node. Place an empty component into the gaps.
Although I won't answer to your particular question, I hope this helps:
If the components just look wrong maybe you should reuse Swing components and just write a custom Look&Feel or theme.
It would certainly help ensuring the look of the application is consistent and at least you are using the right tool for the task you want to accomplish.
As a sidenote, be aware that Java comes with multiple Look&feels, including Look&Feels made to mimic the native OS theme.
See: http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
Related
I want do design a simple login format and in order to do so I want two JTextFields for Username/Password and a Login Button. The Login button is display as expected but when I add the JTextField, nothing shows in my JFrame. Would be nice if someone could help a beginner out...
Here's my code (I know it's ugly but this is just a "code sketch"):
package bucketlistpackage;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GameFrame extends JFrame {
public GameFrame(String title) {
super(title); //sets title of frame
startFrame(); //sets details of main frame
final Container logincont = getContentPane(); //creates content pane
JFrame loginframe = new JFrame();
usernameField(loginframe);
loginButton(loginframe);
logincont.add(loginframe);
}
private void usernameField(JFrame loginframe) {
JTextField usernameF = new JTextField("Username", 1);
usernameF.setBounds(50, 50, 50, 20);
loginframe.add(usernameF);
usernameF.setVisible(true);
}
private void startFrame() {
this.setSize(1000, 1000);
this.setVisible(true);
}
private void loginButton(Container cont) {
JButton loginB = new loginButton();
loginB.setSize(300, 150);
loginB.setText("Login");
cont.add(loginB);
}
}
The problem lies on how you are adding component to one another in your case.
You are adding a JFrame to a Container, when in all case it should be the other way around.
The other problem is that you are not using Layouts to manage the components positions on the JFrame.
Another problem as well is that you are not refreshing the windows after adding all the stuff on it.
A bit of a resume on how Java works with native UIs:
Java creates a new thread for the UI. So if you open the debugger you will see AWT threads as well as the main threads and others. This means that you have to manage this in a correct way, because after the application starts SWING and the functions you determine for reactions will lay the ground on how it will behave. Your main thread will die, but the visual threads will keep active.
If you are just starting to program I would encourage you to practice a bit more native java language before moving to SWING or AWT. This libraries can be really painful and tricky to use.
The other thing is SWING library follows a hierarchy for the components:
JFrame > JPanels > Components
In your code you have already worked with all of them but in a disorganized way. JFrame is the main application window, where the graphics will be displayed (can also be a Canvas or whatever class you want to use for that matter). JPanels are organizers, you can use different layouts to organize whatever is inside it. And finally the Components are well... everything! A component can be a JTextField, but it can also be a JPanel, or JButton.
The idea with SWING is to create multiple Panels and organize the end components inside them, using the help of the different layouts to see whats the best approach to make them attractive in many different window sizes.
Finally, if you are using Eclipse, there is a plugin called WindowBuilder which might help you. I don't recommend you using it if you are very new to Java since it will make you depend a lot on it instead of learning how to actually code with SWING.
Hope this helps!!!
Btw, to fix the code above I would do something like this:
public GameFrame(String title) {
super(title); //sets title of frame
startFrame(); //sets details of main frame
final Container logincont = getContentPane(); //creates content pane
logincont.setLayout(new BorderLayout());
usernameField(logincont, BorderLayout.NORTH);
loginButton(logincont, BorderLayout.CENTER);
this.revalidate();
this.repaint();
}
private void usernameField(Container loginframe, String direction) {
JTextField usernameF = new JTextField("Username");
// usernameF.setBounds(50, 50, 50, 20);
loginframe.add(usernameF, direction);
usernameF.setVisible(true);
}
private void startFrame() {
this.setSize(1000, 1000);
this.setVisible(true);
}
private void loginButton(Container cont, String direction) {
JButton loginB = new JButton();
loginB.setSize(300, 150);
loginB.setText("Login");
cont.add(loginB, direction);
}
edit// my question is simpler than the other one so please just answer here. the other question looks too complicated for me to understand.
I want to add an image to a panel, but not sure how it's done. I don't want to do it from the design page because I didn't Design my panel I only coded it to show up. so does anyone know what code I need to add for an image to show up on there? and where do I save the image so that it can be included. here is the code I've done so far
JFrame frame = new JFrame("JButton");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("London");
panel.add(button);
JLabel label = new JLabel("Click", JLabel.CENTER);
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters
}
}
All you need to do is,
Read image file.
Draw image to background with help of Graphics object.
just replace JPanel panel = new JPanel(); with below code.
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Image image = null;
try {
image = ImageIO.read(new URL("https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"));
} catch (IOException e) {
e.printStackTrace();
}
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
Alright, there are 2 ways to add your image:
Using custom painting by overriding JPanel#paintComponent(...) method.
Using a JLabel to display the image and applying to it various layout managers to get the desired GUI.
I'm going to expand on how to use the 1st way with some comments in the code, the original idea was given in this answer so, be sure to give credits to the author.
You need to either:
Create a custom JPanel object
Create a class that extends JPanel
In any case you need to override the paintComponent(...) method.
Later, in that paintComponent() method you need to draw the image using Graphics#drawImage(...) method. This will make the JPanel to draw the image as the background.
After that you should override your JPanel's getPreferredSize() method, so you can call JFrame#pack(), which will resize your JFrame's size to its preferred size (which is the minimum size where all your components are visible).
After doing that, you can easily add components as you've always done:
panel.add(...);
And the second way is to make a JLabel to act as a Container, where you can add more Components to it (just like you do in a JPanel) (As shown in this answer)
The way to do this is:
Create a JLabel with an ImageIcon
Set its layout manager
Add components to it
Depending on which one you choose you have some differences:
Using the custom painting option, you need to take care of the preferred size of your container but you have more control over your component. However the image will fill all the space available on the window.
Using the JLabel option you can simply call pack() on your JFrame and it will resize to the image size, but if your image is too big your JFrame will be the same size too. If you resize your window to be shorter the image will be cropped and show "white" space if you make your window bigger.
This is how the image looks like with the 2 options, on the left the custom painting, on the right the label approach. At first they both look the same...
But... If we resize the window, this is what we get:
I like the custom painting approach more, but it depends on your needs and likes.
The code that produces the above output is:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JPanelWithBackgroundImageExample {
private JFrame frame; //Our window
private JPanel panel; //The panel where we're going to draw the background image
private Image image;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JPanelWithBackgroundImageExample().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
try {
image = ImageIO.read(new URL("https://i.stack.imgur.com/XZ4V5.jpg")); //We read the image from the Internet
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
panel = new JPanel() { //We need to open the curly braces so we can change the default behavior of the JPanel
/*
* This method is the one that paints the background, by default it paints it with gray color,
* so, we need to tell it to draw an image instead. (This method belongs to JPanel already, so we need to add
* "#Override" before it, so the compiler knows we're overriding it
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //Never forget this line or you could break the paint chain
/*
* This method belongs to the Graphics class and draws an image, this is what we want the JPanel to draw as our background
* The parameters are: the image to be drawn, the starting position (x, y) coords, the width and height and the observer
*/
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
}
/*
* This method is part of the JPanel, we're overriding it's preferred size and return the size we want
*/
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
};
JLabel label = new JLabel(new ImageIcon(image)); //We create a JLabel that will act as a container for our components
panel.setBorder(BorderFactory.createLineBorder(Color.WHITE)); //We create a border just for visibility of both ways
label.setBorder(BorderFactory.createLineBorder(Color.WHITE)); //We create a border just for visibility of both ways
label.setLayout(new BoxLayout(label, BoxLayout.PAGE_AXIS)); //We set the layout manager for the label
label.add(new JLabel("I'm a label inside a label")); //We add a new label to our label (that is acting as a container)
label.add(new JButton("I'm a button inside a label")); //We add a button to our label (that is acting as a container)
//You can add your components to the panel, as you always do it
panel.add(new JButton("HEY! I'm a button!")); //We add a button to our jpanel
panel.add(new JLabel("Click the button next to me! :D")); //We add a label to our jpanel
frame.add(panel, BorderLayout.WEST); //We add the pane which has a size of 300 x 200 to the left part of our JFrame
frame.add(label, BorderLayout.EAST); //We add the label (which acts as a container / jpanel) to the right part of our JFrame
frame.pack(); //We pack the frame, so it takes its preferred size (and as we only added a single component to it (the JPanel)
//As the panel has a size of 300 x 200, the frame will also have this size
frame.setVisible(true); //We set the visibility of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Now, as a general tip, place your program on the Event Dispatch Thread (EDT) by changing your main() method as follows:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Your constructor here
}
});
}
And now, to answer your question in the comments:
everything works except the image because I don't have that image. so I copied an image url from google and pasted it in and it didn't appear? what can I do
Well, I think you took the code from the linked answer and changed this line:
frame.setContentPane(new JLabel(new ImageIcon("C:/Users/Frakcool/workspace/StackOverflowProjects/src/test/Air.jpg")));
To something like this:
frame.setContentPane(new JLabel(new ImageIcon("https://i.stack.imgur.com/XZ4V5.jpg")));
Well in that case, it's obvious that the code won't work that way, Swing doesn't know how to interpret a http in a String, but URL class does, and thus, you should change the above line like:
frame.setContentPane(new JLabel(new ImageIcon(new URL("https://i.stack.imgur.com/XZ4V5.jpg"))));
And import:
import java.net.URL;
In your class.
I hope this helps you in understanding how the code works, if not, well, I think you need to put more effort in understanding it.
As for testing-reasons I tried to open a JDialog window with the panel and its contents of the main application frame. As I already had anything in there I wanted to see if I could simply set the JDialogs contentPane to the one I passed over. So in simplyfied form this came together:
testsforSO.java :
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class testsforSO extends JFrame {
private static final long serialVersionUID = -3890178393751567629L;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testsforSO frame = new testsforSO();
frame.setSize(300, 300);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public testsforSO() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("I am the Frame");
getContentPane().setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setLayout(null);
JButton btnRestart = new JButton("Restart");
btnRestart.setBounds(10, 10, 50, 50);
btnRestart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
testsforSO.main(null);
dispose();
}
});
panel.add(btnRestart);
getContentPane().add(panel);
repaint();
// -----------DELETE These comments-------------
// JDialog myDialg = new JDialog(this);
// myDialg.setContentPane(panel);
// myDialg.setVisible(true);
// myDialg.setSize(300,300);
// myDialg.setLocation(new Point(250, 250));
// myDialg.setTitle("I am Dialog from within the script");
myDialog.main(panel);
}
}
and myDialog.java :
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.JDialog;
public class myDialog extends JDialog {
private static final long serialVersionUID = 7079322237622743228L;
public static void main(Container myContainer) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
myDialog frame = new myDialog(myContainer);
frame.setVisible(true);
frame.setContentPane(myContainer);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public myDialog(Container myContainer) {
setContentPane(myContainer);
getContentPane().setLayout(null);
setBounds(200,200,200,200);
}
}
When starting the main frame I assumed it would contain the restarting button as well as the dialog does. But interestingly it was only the dialog with the button.
However when hitting it, the main frame properly restarted, a second dialog was set up and it contained the button again. This time however the main frame had the button as well, just without any function. Clicking on it does absolutely nothing.
Then I tried further and checked if that behaviour would change if I added the dialog directly into the main applications code (see the commented lines) and, starting the application once again only the dialog in its own class showed the button. Even hitting this one now restarted properly but the button won't show up on any other window except the lonely declared dialog.
What am I missing here and how could I refactor my code to work properly if even at all in this manner?
Understand that Swing components can only be present in one container, and while you may see the visual residue of a component in a container, the actual component is only present in the last container added to.
Myself, if I wanted dialog and jframe to have the same content pane components, I'd create a factory method to create the contentPane, and then use it to create two unique but identical contentPanes.
Also, I'd be remiss if I didn't mention something about your use of null layouts. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For instance, when I ran your code, this is the dialog that I saw:
You hard coded the button's size to be too small to show its text on my platform. If you had used layout managers, and called pack() on the top-level window, the button would show appropriately.
I am trying to create a simple JFrame menu where there is a nice background, which works, along with some text. The text is a bit buggy. Here is how it looks (http://imgur.com/nRpzA30)
As you can see, only one line of the text appears not the second line.
Along with that. Two GUI's appear when I run the program. One is completley empty, and one looks like the picture above.
Finally I can't use the method logo.setHorizontalAlignment(JLabel.NORTH); without getting an error, same with a few others. The two I tested and worked were only .CENTER, and .LEFT.
Any help would be great!
Oh and almost forgot, here's my code :)
package character;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
/**
* Created by Niknea on 6/28/14.
*/
public class characterSelector extends JFrame{
JPanel cselectorText;
JFrame cselectorButtons;
JLabel logo, characterName, label;
JButton previous, next;
public characterSelector(String title){
super(title);
this.createCharacterSelector();
this.setSize(1920, 1033);
this.setResizable(true);
this.setVisible(true);
}
public void createCharacterSelector(){
try {
label = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/resources/Grass_Background.jpg"))));
cselectorButtons = new JFrame();
logo = new JLabel("SoccerKidz [REPLACE W/ COOL LOGO]");
characterName = new JLabel("<Character Name>");
logo.setPreferredSize(new Dimension(50, 50));
logo.setFont(new Font(logo.getFont().getName(), Font.HANGING_BASELINE, 50));
characterName.setFont(new Font(characterName.getFont().getName(), Font.HANGING_BASELINE, 50));
cselectorButtons.add(logo);
cselectorButtons.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cselectorButtons.setContentPane(label);
cselectorButtons.setLayout(new BorderLayout());
characterName.setForeground(Color.CYAN);
characterName.setHorizontalAlignment(JLabel.CENTER);
cselectorButtons.add(characterName);
logo.setForeground(Color.CYAN);
logo.setHorizontalAlignment(JLabel.LEFT);
cselectorButtons.add(logo);
cselectorButtons.pack();
cselectorButtons.setLocationRelativeTo(null);
cselectorButtons.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
Thanks again! :)
As you can see, only one line of the text appears not the second line.
You set the layout of cselectorButtons to BorderLayout. Then you add JLabel("<Character Name>");, which is fine. But then you add JLabel("SoccerKidz [REPLACE W/ COOL LOGO]");. Here's what's happening. With BorderLayout, when you just add(component), generally you want to specify a BorderLayout.[POSITION] as the second argument to the add. If you don't, every component that you add, without the position specified, will be added the the BorderLayout.CENTER implicitly by default. The problem with this is each position can only have one component. So in your case, the first label gets kicked out the center, only showing the second one you added.
Two GUI's appear when I run the program. One is completley empty, and one looks like the picture above.
When look at your code. Your class is a JFrame in which you add nothing to, and this.setVisible(true). And also you a JFrame cselectorButtons; in which you do add components and also cselectorButtons.setVisible(true);. Can you guess which one is the one you're seeing that's not empty. Don't extends JFrame. Just use the instance one you currently are using.
Finally I can't use the method logo.setHorizontalAlignment(JLabel.NORTH); without getting an error.
It doesn't take much to take a look at the API for JLabel. That being said, what makes you think aligning something horizontally, should include an option to position to the north. Doesn't make sense
public void setHorizontalAlignment(int alignment)
Sets the alignment of the label's contents along the X axis.
Parameters:
alignment - One of the following constants defined in SwingConstants: LEFT, CENTER (the default for image-only labels), RIGHT, LEADING (the default for text-only labels) or TRAILING.
I suggest you take a look at Layout out Components Within a Container and A Visual Guide to Layout Managers for other possibly layout managers you can use, if BorderLayout doesn't suit you. Also keep in mind you can nest different panels with different layout managers to get your desired result. But first you need to learn how they work.
UPDATE
I made some changes, which works. I'm also looking at your pastebin code, and can't really see any difference. You may want to investigate my code to try and look for differences
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
* Created by Niknea on 6/28/14.
*/
public class CharacterSelector {
JPanel cselectorText;
JFrame cselectorButtons;
JLabel logo, characterName, label;
JButton previous, next;
public CharacterSelector() {
createCharacterSelector();
}
public void createCharacterSelector() {
try {
label = new JLabel(new ImageIcon(ImageIO.read(getClass()
.getResource("/resources/Grass_Background.jpg"))));
cselectorButtons = new JFrame();
logo = new JLabel("SoccerKidz [REPLACE W/ COOL LOGO]");
characterName = new JLabel("<Character Name>");
logo.setPreferredSize(new Dimension(50, 50));
logo.setFont(new Font(logo.getFont().getName(),
Font.HANGING_BASELINE, 50));
characterName.setFont(new Font(characterName.getFont().getName(),
Font.HANGING_BASELINE, 50));
cselectorButtons.add(logo);
cselectorButtons.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cselectorButtons.setContentPane(label);
cselectorButtons.setLayout(new BorderLayout());
characterName.setForeground(Color.CYAN);
characterName.setHorizontalAlignment(JLabel.CENTER);
cselectorButtons.add(characterName);
logo.setForeground(Color.CYAN);
logo.setHorizontalAlignment(JLabel.LEFT);
cselectorButtons.add(logo, BorderLayout.NORTH);
cselectorButtons.pack();
cselectorButtons.setLocationRelativeTo(null);
cselectorButtons.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new CharacterSelector();
}
});
}
}
Maybe i have encountered a bug or more probably doing something wrong ;)
I try to translate the content of a user drawn JPanel using a JScrollPanel. Inside the panel the drawing i would like to access the visible area through the Graphics class getClipBounds method to improve rendering performance.
Searching on SO brings a lot results referring to JScrollPane but none is mentioning a problem with the clip bounds. Google the same.
user drawn panel
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Content extends JPanel {
#Override
protected void paintChildren(Graphics g) {
super.paintChildren(g);
// intense clip bounds dependent rendering here
System.out.println(g.getClipBounds());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(2000,2000);
}
}
main frame setup
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
public class ClipBoundsIssue {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClipBoundsIssue window = new ClipBoundsIssue();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ClipBoundsIssue() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
Content content = new Content();
scrollPane.setViewportView(content);
}
}
to reproduce
Just run the code, move one of the scrollbars and inspect the console output of System.out. The following picture depicted scrolling the bar on the x axis.
actual System.out result
Which produced the following results
java.awt.Rectangle[x=0,y=0,width=416,height=244]
java.awt.Rectangle[x=416,y=0,width=16,height=244]
java.awt.Rectangle[x=432,y=0,width=15,height=244]
java.awt.Rectangle[x=447,y=0,width=16,height=244]
java.awt.Rectangle[x=463,y=0,width=15,height=244]
expected result
I would have expected to have the width of the bounds to keep the same. But it changes from 416 to 16.
The question now is
Does anybody know why this happens, or how it can be avoided??
discared WAs
A possible workaround would be to lookup the view port's view bounds. But if possible i would like to avoid the Content class making any such lookup. Another alternative would be to pass the information into the Content class, but this i would like to avoid as well.
I would have expected to have the width of the bounds to keep the same.
Why? It is so simple that it is hard to explain, but let me try.
When you scrolling, only small new portion if the JPanel is appearing if you scroll slowly.
The produced output is absolutely correct:
java.awt.Rectangle[x=0,y=0,width=416,height=244] Control is shown first time, you need to redraw it completely
java.awt.Rectangle[x=416,y=0,width=16,height=244] You scrolled to the right by 16 pixels, so only narrow strip of you control must be redrawn.
You must understand that these coordinates are related to your control which has size set to 2000x2000 pixels.
Try to scroll the window created with this code and you will see what I am talking about:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class ScrollPaneRepaintDemo extends JPanel {
public ScrollPaneRepaintDemo() {
setPreferredSize(new Dimension(2000,2000));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new JScrollPane(new ScrollPaneRepaintDemo()));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override protected void paintComponent(Graphics g) {
Rectangle clip = g.getClipBounds();
g.setColor(new Color(new Random().nextInt()));
g.fillRect(clip.x, clip.y, clip.width, clip.height);
}
}
By the way - it works so because of JPanel's internal implementation. If you extend JComponent instead, the whole viewport will be clipped. I add also that JPanel repaints completely when resizing, its optimizations are only for scrolling.