I am struggeling with a little exercise I teached myself: I have a JPanel with an image drawn by g.paint(). On this JPanel I have another JPanel (componentsPanel) that contains the actual content: a JList and a JLabel that I want to be transparent, so only the content is visible (no background of those elements)
Here are my classes:
The JPanel and its components
private void initializeNormalPanel() {
normalPanel = new JPanel() {
#Override
public void paint(Graphics g) {
super.paint(g);
Image i, scaled = null;
try {
i = ImageIO.read(new URL("image-from-url"));
scaled = i.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(scaled, 0, 0, null);
}
};
CustomListModel listModel = new CustomListModel();
//m1-m10 is the sample data
listModel.addElement(m1);
listModel.addElement(m2);
listModel.addElement(m3);
listModel.addElement(m4);
listModel.addElement(m5);
listModel.addElement(m6);
listModel.addElement(m7);
listModel.addElement(m8);
listModel.addElement(m9);
listModel.addElement(m10);
JList list = new JList(listModel) {
#Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
};
list.setCellRenderer(new CustomListCellRenderer());
ComponentListener l = new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
list.setFixedCellHeight(10);
list.setFixedCellHeight(-1);
}
};
list.addComponentListener(l);
normalPanel.setVisible(true);
normalPanel.setLayout(new BoxLayout(normalPanel, BoxLayout.PAGE_AXIS));
JPanel componentsPanel = new JPanel(new BorderLayout());
JLabel timeLabel = new JLabel("Aktuelle Zeit", SwingConstants.CENTER);
displayCurrentTime(timeLabel);
list.setOpaque(false);
componentsPanel.add(list, BorderLayout.WEST);
componentsPanel.add(timeLabel, BorderLayout.NORTH);
list.setOpaque(false);
timeLabel.setOpaque(false);
timeLabel.setFont(new Font("Arial", Font.PLAIN, 25));
normalPanel.add(componentsPanel);
}
I also have a custom ListCellRenderer:
#Override
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean hasFocus) {
final Meeting text = (Meeting) value;
lt.setText(pre + value.toString());
setOpaque(false);
return p;
}
I cannot manage to achieve my goal, I always see the background of the List and Label. I tried every combination of setOpaque true and false, can someone help me to get my components transparent?
custom painting is done by overriding paintComponent() not paint.
Don't do I/O in a painting method. You don't want to keep reading the image every time the component needs to be repainted.
A JLabel is transparent by default (other Swing components are not).
I always see the background of the List and Label.
normalPanel.add(componentsPanel);
I don't see where you make the componentsPanel transparent. So the background of the components panel will paint over top of the normalPanel.
Do you even need the componentsPanel? Why can't you just add the JLabel and JList directly to your normalPanel after setting the layout manager.
So first make sure it works with the JLabel since it is transparent by default. Once this works you know you have the proper layout. Then if the JList doesn't work you know you have a renderer issue.
Related
I'm developing a Java application that demands a customized button. I'm using Swing for the GUI and found myself limited to some tricky solutions.
Here's one I found (from this website). It's supposed to use a custom image for the button and make it round.
public class RoundButton extends JButton
{
private static final long serialVersionUID = 1L;
protected Shape shape, base;
public RoundButton()
{
this(null, null);
}
public RoundButton(Icon icon)
{
this(null, icon);
}
public RoundButton(String text)
{
this(text, null);
}
public RoundButton(Action a)
{
this();
setAction(a);
}
public RoundButton(String text, Icon icon)
{
setModel(new DefaultButtonModel());
init(text, icon);
if(icon==null) return;
setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
setBackground(Color.BLACK);
setContentAreaFilled(false);
setFocusPainted(false);
//setVerticalAlignment(SwingConstants.TOP);
setAlignmentY(Component.TOP_ALIGNMENT);
init_shape();
}
protected void init_shape()
{
if(!getBounds().equals(base))
{
Dimension s = getPreferredSize();
base = getBounds();
shape = new Ellipse2D.Float(0, 0, s.width-1, s.height-1);
}
}
#Override
public Dimension getPreferredSize()
{
Icon icon = getIcon();
Insets i = getInsets();
int iw = Math.max(icon.getIconWidth(), icon.getIconHeight());
return new Dimension(iw+i.right+i.left, iw+i.top+i.bottom);
}
#Override
protected void paintBorder(Graphics g)
{
init_shape();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground());
//g2.setStroke(new BasicStroke(1.0f));
g2.draw(shape);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
#Override
public boolean contains(int x, int y)
{
init_shape();
return shape.contains(x, y);
//or return super.contains(x, y) && ((image.getRGB(x, y) >> 24) & 0xff) > 0;
}
}
Here's some test code I wrote:
public class BtnTest extends JFrame
{
private static final long serialVersionUID = 1L;
private RoundButton btn;
public BtnTest()
{
init_components();
}
private void init_components()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setBackground(Color.BLACK);
setResizable(false);
btn = new RoundButton(
new ImageIcon("/path/to/file.png"));
btn.setBounds(50, 50, 50, 50);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("click");
}
});
add(btn);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BtnTest frame = new BtnTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
This is the result:
The problem is: the image's rendered away from the button location, so my ActionListener isn't triggered when I press the icon, but when the region inside the black circle (top left) is clicked. Can someone explain me why, and offer a solution?
PS: I'm in my first year of Java programming, so make it as simple as possible please.
PS2: JavaFX and other external solutions are out of question, this must be done pure Java.
The problem is: the image's rendered away from the button location,
What is happening is that you are adding the button to the frame without using a constraint. By default this means the component is added to BorderLayout.CENTER, which means the component will be sized to fill the entire frame.
Also, by default, when you paint an Icon in a JLabel, the Icon is centered in the spaced available to the label, so you see the Icon in the center of the frame. Try resizing the frame to see the Icon move.
However, you hard code the painting of the Border to be painted at the (0, 0) location of the label so it paints at the top/left.
The contains() method is also defined from the top/left of the component, so mouse detection only works from the top/left, not the center.
This means your button must always be painted at its "preferred size" in order for it to be painted properly and for the contains(...) method to work.
A simple way to demonstrate this is to use:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout( new FlowLayout() );
The FlowLayout does respect the preferred size of the button, so the Icon and Border will be painted properly.
Other options (instead of changing the layout of the frame) are to use a "wrapper" panel for the button. For example:
//add(btn);
JPanel wrapper = new JPanel(); // default to FlowLayout
wrapper.add( btn );
add( wrapper );
Now when you add the panel to the frame, the panel will grow in size, but the button will still be painted at its preferred size.
btn.setBounds(50, 50, 50, 50);
Also, not you should NOT be using this method. It is the job of the layout manager to set the size/location of the component. The above statement is effectively ignored.
MASSIVE EDIT: I added more descritpion and code.
I recently encounter a problem where a panel that I added to another panel won't display properly (only display a black dot instead of the image). The flow of the code is: the Menu class has a button panel. When the button start is press, the Menu remove the button panel, create a Board object(that implement panel) and add it to Menu. In Board constructor, an image is loaded (a .png), then a PlayerPanel (that implement panel) is added to the board panel. In PlayerPanl constructor, an image is loaded.
The plan is to make the menu repaint() method able to call Board paintcomponent. Board will then ask PlayerPanel to paintComponent. PlayerPanel paint his image, Board paint his image and that's it, both image should display.
public class Menu extends JFrame implements ActionListener
{
Board theBoard;
JPanel pnlButton = new JPanel();
JButton btnStart = new Jbutton("Start");
public Menu(String s)
{
pnlButton.add(btnStart);
super.add(pnlButton);
super.setLocation(0,0);
super.setSize(600, 500);
super.setResizable(false);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == btnStart)
{
theBoard = new Board ("TestBoard");
super.remove(pnlButton);
super.add(theBoard);
super.repaint();
}
}
}
public class Board extends JPanel
{
BufferedImage boardImage;
PlayerPanel playerPanel;
public Board (String boardName)
{
boardImage = Tools.loadImage(boardName);
playerPanel = new PlayerPanel();
this.add(playerPanel);
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(boardImage, 0, 200, null);
}
}
public class PlayerPanel extends JPanel
{
BufferedImage playerImage;
public PlayerPanel()
{
playerImage = Tools.loadImage("TestPlayer");
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(playerImage, 0, 0, null);
}
}
Both image load successfully as tested, but when the repaint() is call from the JFrame holding the Board panel, only the image in Board is painted, and the image in PlayerPanel is replace with a black dot.
Any help? Thanks!
Your problem seems to be due to the size of your PlayerPanel JPanel. Sometimes it helps to debug things by testing to see what size things are when they're rendered. For instance, if you change your Board paintComponent method to this:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (boardImage != null) {
g.drawImage(boardImage, 0, 200, null);
}
System.out.printf("Board size: [%d, %d]%n", getWidth(), getHeight());
System.out.printf("Player size: [%d, %d]%n", playerPanel.getWidth(), playerPanel.getHeight());
}
it will tell you exactly what the sizes are of itself and its constituent playerPanel.
To solve the issue, you could give Board a layout manager that expands its constituent components such as a BorderLayout. Another possible solution is to give PlayerPanel its own getPreferredSize() method override, especially if you want it to size itself to its image. e.g.,
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (playerImage != null) {
g.drawImage(playerImage, 0, 0, null);
}
}
Alternatively, you could use a JLabel that holds an ImageIcon rather than draw in the JPanel.
Note, you should swap views with a CardLayout rather than calling remove(...), add(...), revalidate(), repaint()
I'm trying to add a JScrollPane to an JPanel from a separate class. And thanks to some questions, which were asked so far, I could help myself create them. But my problem is still a little bit special.
I want to display an image on a JPanel and if the image is to large for the panel, I want to add scrollbars. But the scrollbars won't appear.
(When I set the ScrollPaneConstants to ****_SCROLLBAR_ALWAYS the frame of the bar appears, but without the bars to scroll).
I guess i have to connect the imagesize with the bars, so that they appear?
Some pieces of my code:
MainWindow
public class Deconvolutioner extends JFrame
{
Draw z;
Picturearea picturearea;
class Draw extends JPanel
{
public void paint(Graphics g)
{
}
}
public Deconvolutioner()
{
setTitle("Deconvolutioner");
setLocation(30,1);
setSize(1300,730);
super.setFont(new Font("Arial",Font.BOLD,11));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
this.setLayout(flow);
picturearea = new Picturearea();
picturearea.setLayout(new GridBagLayout());
JScrollPane scrollPane = new JScrollPane(picturearea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(1000, 664));
getContentPane().add(scrollPane, flow); // add scrollpane to frame
add(z = new Draw());
setVisible(true);
}
}
JPanel Class
public class Picturearea extends JPanel
{
BufferedImage image;
int panelWidth, panelHeight, imageWidth, imageHeight;
public Picturearea()
{
setBackground(new Color(210,210,210));
setBorder(LineBorder.createBlackLineBorder());
setVisible(true);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public void setPicture(BufferedImage picture)
{
try
{
image = picture;
}
catch (Exception e)
{
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(e.getMessage());
}
repaint();
}
}
Thanks for your time.
The problem is that the JScrollPane has no way to know if it should display scroll bars or not, since the Picturearea it contains doesn't tell anything about its preferred size (or rather, it returns the preferred size based on its layout and on the components it contains. But since it doesn't contain any component, the returned preferred size is probably (0, 0)).
I would simply use a JLabel instead of the custom Picturearea class. A JLabel can display an image just fine, and it returns the appropriate Dimension when asked for its preferred size.
You can create a JLabel first and then add the Label to JPanel picturearea before creating instance for JScrollPane .
Have a try and it will work.
Example code is as follows:
JLabel imageLabel = new JLabel(new ImageIcon("d:\\099.jpg"));
picturearea.add(imageLabel);**
JScrollPane scrollPane = new JScrollPane(picturearea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
I would like to display more than one image on the screen in the same JPanel.
A for loop iterates over each element in the array and displays their corresponding image, but only seems to keep the last image.
The code:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
public class GameGUI extends JFrame{
JPanel mainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
int arrayLength;
public GameGUI() {
super("Gameplay");
//Set size of the frame.
setSize(650, 580);
//Location inside frame.
setLocation(10, 8);
SwingUtilities.isEventDispatchThread();
The methods that contain each individual panel:
createMainPanel();
createCentrePanel();
createNorthPanel();
createSouthPanel();
createWestPanel();
createEastPanel();
setVisible(true);
}
//creating panels
public void createMainPanel() {
//here is the main panel which the others will be nested in.
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.red);
add(mainPanel);
}
public boolean createCentrePanel() {
JPanel CENTRE = new JPanel(new BorderLayout());
CENTRE.setBackground(Color.WHITE);
CENTRE.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(CENTRE, BorderLayout.CENTER);
return true;
}
This is the panel which i am using to print multiple images to the panel.
As you can see I have a for loop which is going through each item in the array and passing the value to the draw component. However it only seems to keep the last image on the screen eventhough each item in the array is being passed to it.
I have tried using repaint but it doesn't seem to work:
public boolean createNorthPanel() {
int[] array = {1, 8, 9, 10};
arrayLength = array.length;
int size = 0;
JPanel NORTH = new JPanel(new BorderLayout());
NORTH.setPreferredSize(new Dimension(100, 100));
NORTH.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(NORTH, BorderLayout.NORTH);
for (int i = 0; i < arrayLength; i++) {
NORTH.add(new drawPanel(array[i], size, arrayLength));
size = size + 30;
//repaint();
}
return true;
}
public boolean createSouthPanel() {
JPanel SOUTH = new JPanel(new BorderLayout());
SOUTH.setPreferredSize(new Dimension(100, 100));
// SOUTH.add(new drawPanel(2, 0));
// SOUTH.add(new drawPanel(5, 30));
SOUTH.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(SOUTH, BorderLayout.SOUTH);
SOUTH.add(buttonPanel, BorderLayout.EAST);
return true;
}
public boolean createWestPanel() {
JPanel WEST = new JPanel(new BorderLayout());
WEST.setPreferredSize(new Dimension(150, 100));
//WEST.add(new drawPanel(8, 0));
WEST.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(WEST, BorderLayout.WEST);
return true;
}
public boolean createEastPanel() {
JPanel EAST = new JPanel(new BorderLayout());
EAST.setPreferredSize(new Dimension(150, 100));
EAST.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(EAST, BorderLayout.EAST);
//EAST.add(new drawPanel(2, 0));
//EAST.add(new drawPanel(7, 60));
return true;
}
public static void main(String args[]){
new GameGUI();
}
}
Here is my class which draws the images on the screen
class drawPanel extends JPanel {
Image image = null;
int xPos;
public drawPanel(int x, int y, int length) {
xPos = y;
try {
File location = new File("src/Card_images/" + x + ".png");
image = ImageIO.read(location);
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
/*public Dimension getPreferredSize() {
return new Dimension(71, 96);
}*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//draws image to screen at positions displayed
g.drawImage(image, xPos, 0, this);
}
}
You only have a single drawImage() statement that is executed in you paintCompent() method so you only ever see the last image drawn.
See Custom Painting Approaches for two different ways to draw multiple objects. You will obviously need to customize for your requirements, but the basic concepts will be the same.
Edit:
The above does not apply to your question, but is still good to know when you do need to do some custom painting.
Sorry, because of the custom painting I misread your question. You are making the code too complex.
The first problem is that you changed the layout manager of the "north" panel to a BorderLayout. You can only add a single component to any location of a BorderLayout. So that is why the last component added gets painted. Just use the default FlowLayout for the panel. Although your code still won't work because your components don't have a preferred size.
So the solution to your problem is:
a) create a panel using a FlowLayout
b) Use a JLabel to display your images. There is no need to do custom painting!. Add the labels to the panel, then add this panel to your frame.
Now the layout manager can do its job and you don't need to worry about the details.
Also, use standard Java naming conventions. Your code is too hard to read because you don't follow the standards.
NORTH is not a proper variable name. It should be "north". An upper cased name indicates a final static variable.
use proper class names. Classes should start with an upper case character. "drawPanel" should be "DrawPanel".
I have a JPanel and I want do draw to this JPanel some very simple images (items). I want to use methods like DrawRect or DrawOval.. This panel will have a scrollbar. It should look like this.
I need to remove and add item (images) on a specific index. Can you help me please?
Start with a main JPanel which uses either a GridLayout or a vertical BoxLayout. Put this inside a JScrollPane. Inside the main JPanel, you'll want to have instances of JPanel which extend the regular paintComponent() method to do drawing with drawRect(), drawOval(), etc. This should get you started:
public JScrollPane buildScrollingContainerPanel()
{
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(containerPanel);
containerPanel.add(new MyPanel(true, false));
containerPanel.add(new MyPanel(false, true));
return (scrollPane);
}
private class MyPanel extends JPanel
{
private boolean drawRect;
private boolean drawOval;
public MyPanel(boolean drawRect, boolean drawOval)
{
super();
this.drawRect = drawRect;
this.drawOval = drawOval;
}
public void setDrawRect(boolean b)
{
drawRect = b;
repaint();
}
public void setDrawOval(boolean b)
{
drawOval = b;
repaint();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (drawOval)
{
g.setColor(Color.RED);
g.drawOval(16, 16, 16, 16);
}
if (drawRect)
{
g.setColor(Color.GREEN);
g.drawRect(32, 32, 16, 16);
}
}
}
to access children of the containerPanel, use containerPanel.getComponent(int) then cast to MyPanel.
you have look at
proper LayoutManager ( probably GridLayout)
you have look at JList with Icons