Is there a way to create a JButton with your own button graphic and not just with an image inside the button?
If not, is there another way to create a custom JButton in java?
When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.
Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.
Here are the basic steps:
Create a class that extends JComponent
Call parent constructor super() in your constructors
Make sure you class implements MouseListener
Put this in the constructor:
enableInputMethods(true);
addMouseListener(this);
Override these methods:
public Dimension getPreferredSize()
public Dimension getMinimumSize()
public Dimension getMaximumSize()
Override this method:
public void paintComponent(Graphics g)
The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.
And finally, the source code. In case I missed anything.
Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates.
Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text.
package test;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MyButton extends JButton {
private static final long serialVersionUID = 1L;
private Color circleColor = Color.BLACK;
public MyButton(String label) {
super(label);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension originalSize = super.getPreferredSize();
int gap = (int) (originalSize.height * 0.2);
int x = originalSize.width + gap;
int y = gap;
int diameter = originalSize.height - (gap * 2);
g.setColor(circleColor);
g.fillOval(x, y, diameter, diameter);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += size.height;
return size;
}
/*Test the button*/
public static void main(String[] args) {
MyButton button = new MyButton("Hello, World!");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
frame.setVisible(true);
}
}
Note that by overriding paintComponent that the contents of the button can be changed, but that the border is painted by the paintBorder method. The getPreferredSize method also needs to be managed in order to dynamically support changes to the content. Care needs to be taken when measuring font metrics and image dimensions.
For creating a control that you can rely on, the above code is not the correct approach. Dimensions and colours are dynamic in Swing and are dependent on the look and feel being used. Even the default Metal look has changed across JRE versions. It would be better to implement AbstractButton and conform to the guidelines set out by the Swing API. A good starting point is to look at the javax.swing.LookAndFeel and javax.swing.UIManager classes.
http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html
http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html
Understanding the anatomy of LookAndFeel is useful for writing controls:
Creating a Custom Look and Feel
You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:
try {
SynthLookAndFeel synth = new SynthLookAndFeel();
Class aClass = MainFrame.class;
InputStream stream = aClass.getResourceAsStream("\\default.xml");
if (stream == null) {
System.err.println("Missing configuration file");
System.exit(-1);
}
synth.load(stream, aClass);
UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
System.err.println("Bad configuration file");
pe.printStackTrace();
System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
System.err.println("Old JRE in use. Get a new one");
System.exit(-3);
}
From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.
The xml file might look like this:
<synth>
<style id="button">
<font name="DIALOG" size="12" style="BOLD"/>
<state value="MOUSE_OVER">
<imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
<insets top="2" botton="2" right="2" left="2"/>
</state>
<state value="ENABLED">
<imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
<insets top="2" botton="2" right="2" left="2"/>
</state>
</style>
<bind style="button" type="name" key="dirt"/>
</synth>
The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").
And a couple of useful links:
http://javadesktop.org/articles/synth/
http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html
I'm probably going a million miles in the wrong direct (but i'm only young :P ). but couldn't you add the graphic to a panel and then a mouselistener to the graphic object so that when the user on the graphic your action is preformed.
I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit javax.swing.AbstractButton and create your own. Should be pretty simple to wire something together with their existing framework.
Related
I'm developing a software which paints 2 different JPanel for my GUI: a score and a mast guitar. The score is a class which extends JPanel and has paintComponent() method like this:
public class PanelPartitura extends JPanel implements MouseListener{
public void paintComponent(Graphics comp){
super.paintComponent(comp);
comp2D = (Graphics2D)comp;
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
paintBackground();
paintStave();
paintNotes();
[...]
}
}
The mast guitar is a class as well:
public class PanelGuitarra extends JPanel implements MouseListener
public void paintComponent(Graphics comp){
super.paintComponent(comp);
comp2D = (Graphics2D)comp;
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//Then I call secondary methods to paint it:
paintBackground();
PaintPoints();
}
[...]
}
It still works fine. I add the class PanelPartitura to a JScrollPane in order to scroll when it's playing:
partitura = new PanelPartitura();
JScrollPartitura = new JScrollPane(partitura, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
Both JPanels mix each others painted components when the software is playing and scrolling. I would like to ask, if somebody has a clue about what on earth is going on? In my opinion:
It could be because I separated the painting methods as we've seen above:
paintBackground();
paintStave();
paintNotes();
then, when the software starts to paint, it paints some parts of the first JPanel (paintBackground() for example) and then some parts of the mast guitar (paintBackground()), then it changes again and the result is a mixture of both.
I think this is because it mixes different parts every time, I mean it doesn't behave in the same way every time it plays.
I really don't want this to be happening, so let me ask you: how can I make atomic methods to be sure this wouldn't be the problem?
I missunderstood the scroll method. I scroll on this way:
//the note playing currently position is saved in positionBar
positionBar = 150 + 50*PGuitarra.composicion.getAcordeSeleccionado().getPosicionXAcorde();
//horizontalScrollBar is moved to this position
PGuitarra.JScrollPartitura.getHorizontalScrollBar().setValue(positionBar);
I see that your paint methods are not using the same Graphics object (at the JPanel scope). Could that be the reason? And if it is, try passing comp (the Graphics object) as a parameter to paintBackground, paintStave and paintNotes.
I have a JScrollPane displaying (as its viewport view) MyPanel, a subclass of JPanel.
MyPanel implements custom painting by overloading paintComponent. The total size of the displayable content of MyPanel is generally quite wide (meaning 50x to 200x wider than the size of the JScrollPane viewport) and using a Timer, I scroll horizontally to view different sections of the underlying MyPanel. I also allow using the scroll bar thumb to manually seek to a specific area of MyPanel.
In my paintComponent implementation I am currently finding the portion of MyPanel that is currently visible in the view port using JViewport#getVisibleRect, and just painting that portion each time the view port position is changed.
This works fine - but I end up repainting a significant percentage of the visible portion of MyPanel over and over as the timed scrolling only moves the view port 1/50 of the view port width at a time. Also, I generally end up scrolling through the entire horizontal extent of MyPanel, so I have to paint it all at least once anyway.
That leads me to think about painting the entire contents of MyPanel just once (to a BufferedImage?) and then letting JScrollPane (or JViewport) handle clipping and blitting only the needed area of the BufferedImage.
Intuitively this seems to me to be the most efficient way of handling this, and something that would be relatively common.
As I investigate the Swing tutorials and other sources, I learn that Swing is already double buffered. If I try to force this on my own brute-force, independent of Swing functionality, it sounds like I'll end up with triple-buffering.
I haven't found the recipe (if it exists) to exploit JScrollPane to do this for me.
Is there an example available, or some direction as to how to do this (if possible)?
Swing automatically paints only the smallest necessary area of components for you. repaint(4 args) is only useful when the component is partially changed and you don't want the entire visible area to be repainted. And in your practical, it has the same effect as repaint(no-args).
The auto-clipped area is already small enough for visibility concerns as you described in your question. And you can configure it in your program.
Also, you don't need to worry about the scrolling -- JScrollPane invokes repaint of its children automatically.
You can easily experiment on these:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test extends JFrame {
private Random rnd = new Random();
private Color c = Color.WHITE;
public Test () {
final JPanel pnl = new JPanel() {
#Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
Rectangle r = g.getClipBounds();
System.out.println(r.width + ", " + r.height);
}
};
pnl.setPreferredSize(new Dimension(10000, 10000));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
add(new JScrollPane(pnl));
setVisible(true);
new Thread() {
#Override
public void run () {
while (true) {
c = new Color(rnd.nextInt(0xffffff));
pnl.repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
}.start();
}
public static void main (String args[]) {
new Test();
}
}
The Jlabel is not showing up when I put it in the paint(Graphics2d g) method and I can't figure out why.
My text class:
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JLabel;
public class Text {
int ballX,ballY,squareX,squareY;
Text text;
private Game game;
private Ball ball;
private Racquet racquet;
public void main(){
ballX = ball.getBallX();
ballY = ball.getBallY();
squareX = racquet.getSquareX();
squareY = racquet.getSquareY();
}
public void paint(Graphics2D g) {
g.setColor(Color.red);
JLabel balltext = new JLabel("the ball is at " + ballX + ballY);
balltext.setVisible(true);
g.setColor(Color.green);
JLabel squaretext = new JLabel("the ball is at " + squareX + squareY);
squaretext.setVisible(true);
}
}
There are a few things not quite right with your code.
Firstly, Text does not extend from anything that is paintable, so paint will never be called. Convention tends to favor overriding paintComponent of Swing components anyway.
Also, you should always call super.paintXxx, this would have highlighted the problem in the first place.
Secondly, components are normally added to some kind container which takes care of painting them for you.
If you want to use Swing components in your program, I'd suggest taking a look at Creating a GUI With JFC/Swing.
If you want to paint text, I'd suggest you take a look at 2D Graphics, in particular Working with Text APIs
An bit more information about what it is you're trying to achieve might also help
Also, I'm not sure if this deliberate or not, but public void main(){ ins't going to act as the main entry point of the program, it should be public static void main(String args[]), but you might just be using main as means to call into the class from else where ;)
From the look of things you are missing quite a few paradigms / idioms for a Java Swing gui.
For example:
Text should extend JComponent if you want to override paint / paintComponent to specify how the component should be drawn.
You should create a separate Main class to serve as an entrypoint to your program (you don't have to, but it helps you keep things logically separated for now, which is easier conceptualize mentally for you)
You need to create a JFrame inside your main method, then create the Text class and add it to JFrame and call pack() and setVisible(True) on the JFrame.
I would recommend looking at some examples first to get oriented:
http://zetcode.com/tutorials/javaswingtutorial/firstprograms/
http://www.javabeginner.com/java-swing/java-swing-tutorial
In Java2D when you use setOpaque I am a little confused on what the true and false does.
For example I know that in Swing Opaque means that when painting Swing wont paint what is behind the component. Or is this backwards? Which one is it?
Thanks
The short answer to your question is that "opaque" is defined in English as completely non-transparent. Therefore an opaque component is one which paints its entire rectangle, and every pixel is not at all translucent to any degree.
However, the Swing component opacity API is one of those mis-designed and therefore often mis-used APIs.
What's important to understand is that isOpaque is a contract between the Swing system and a particular component. If it returns true, the component guarantees to non-translucently paint every pixel of its rectangular area. This API should have been abstract to force all component writers to consider it. The isOpaque API is used by Swing's painting system to determine whether the area covered by a given component must be painted for components which overlap it and which are behind it, including the component's container and ancestors. If a component returns true to this API, the Swing system may optimize painting to not paint anything in that area until invoking the specific component's paint method.
Because of contractual implication of isOpaque, the API setOpaque should not exist, since it is actually incorrect for anything external to call setOpaque since, in turn, the external thing can't know whether the component in question will (or even can) honor it. Instead, isOpaque should have been overridden by each concrete component to return whether it actually is, in fact, opaque given its current properties.
Because the setOpaque API does exist, many components have mis-implemented it (quite understandably) to drive whether or not they will paint their "background" (for example JLabel and JPanel filling with their background color). The effect of this is to create an impression with users of the API to think that setOpaque drives whether or not that background should paint, but it doesn't.
Furthermore, if, say, you wish to paint a JLabel with a translucent background you need to set a background color with an alpha value, and do setOpaque(true), but it's not actually opaque - it's translucent; the components behind it still need to paint in order for the component to render properly.
This problem was exposed in a significant way with the Java 6's new Nimbus Look & Feel. There are numerous bug reports regarding transparent components filed against Nimbus (see stack overflow question Java Nimbus LAF with transparent text fields). The response of the Nimbus development team is this:
This is a problem [in] the orginal design of Swing and how it has been confusing for years. The issue is setOpaque(false) has had a side effect in [existing] LAFs which is that of hiding the background which is not really what it is [meant] for. It is [meant] to say that the component may have transparent parts and [Swing] should paint the parent component behind it.
So, in summary, you should not use setOpaque. If you do use it, bear in mind that the combination of some Look & Feels and some components may do "surprising" things. And, in the end, there is actually no right answer.
javadoc says : If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
try this example program too...
http://www.java2s.com/Code/JavaAPI/javax.swing/JPanelsetOpaquebooleanisOpaque.htm
I think that the following also needs to be added:
The term opaque has different meanings in Java 2D and in Swing.
In Java 2D opacity is a rendering concept. It is a combination
of an alpha value and the Composite mode. It is a degree to
which the pixel colours being drawn should be blended with pixel
values already present. For instance, we draw a semi-transparent
rectangle over an existing oval shape. The oval is therefore
partially visible. This concept is often compared to light
going trough glass or water.
In Swing, an opaque component paints every pixel within its
rectangular bounds. A non-opaque component paints only a subset of
its pixels or none at all, allowing the pixels underneath it to
show through. The opaque property was set for efficiency reasons; Swing
does not have to paint areas behind opaque components.
Source: Java docs and Filthy Rich Clients
package com.zetcode;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import static javax.swing.SwingConstants.CENTER;
import net.miginfocom.swing.MigLayout;
class DrawingPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.green);
g2d.fillOval(20, 20, 100, 100);
g2d.setColor(Color.blue);
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.1f));
g2d.fillRect(0, 0, 150, 150);
}
}
class MyLabel extends JLabel {
public MyLabel(String text) {
super(text, null, CENTER);
}
#Override
public boolean isOpaque() {
return true;
}
}
public class OpaqueEx2 extends JFrame {
public OpaqueEx2() {
initUI();
}
private void initUI() {
JLabel lbl1 = new JLabel("Java 2D opacity");
JLabel lbl2 = new JLabel("Swing opaque");
DrawingPanel dpanel = new DrawingPanel();
MyLabel mylbl = new MyLabel("isOpaque()");
mylbl.setBackground(Color.decode("#A9A9A9"));
createLayout(lbl1, lbl2, dpanel, mylbl);
setTitle("Opaque");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
JPanel pnl = new JPanel(new MigLayout("ins 10"));
pnl.add(arg[0], "w 150");
pnl.add(arg[1], "w 150, wrap");
pnl.add(arg[2], "w 150, h 150");
pnl.add(arg[3], "w 150, h 150");
add(pnl);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
OpaqueEx2 ex = new OpaqueEx2();
ex.setVisible(true);
}
});
}
}
In the code example, we have two components. The component on the left is a panel which uses AlphaComposite to paint a highly translucent rectangle over an oval. The component on the right is a label. Labels are non-opaque in most look and feels. We overwrite the label's isOpaque() method to set a gray background.
I need to make an image map using Swing that displays a background image, and then when the mouse hovers over (or clicks) specific hotspots, I need to pop up a 'zoomed-in' image and have it display.
I was thinking of extending JPanel to include an image reference and have that drawn thru the paintComponent(g) method. This part I have done so far, and here's the code:
public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image;
public ImagePanel(Image image)
{
setImage(image);
}
public void setImage(Image newImage)
{
image = newImage;
}
#Override
public void paintComponent(Graphics g)
{
Dimension size = getSize();
g.drawImage(image, 0, 0, size.width, size.height, this);
}
Could anyone recommend how I might listen for / respond to mouse clicks over defined hot-spots? Could someone additionally recommend a method for displaying the pop-ups? My gut reaction was to extend JPopupMenu to have it display an image, similar to the above code.
Thanks for any help!
To listen to the mouse clicks implement the MouseListener interface, and add it to your panel. Then when the click is recieved you can use a JPopupMenu as you suggested, or you could even use a glass pane to show the zoomed in image.
I'm guessing you want to achieve something similar to this post by Joshua Marinacci, he has also posted the source here, I would take a look at that.
I would probably:
create some instance of Shape that represents each of your hotspots (could be a plain boring old Rectangle, or see GeneralPath if you need to create fancy shapes)
register a MouseListener which iterates through each of the Shapes and calls its contains() method to see if the clicked coordinate is inside the hotspot in question