Transparent JPanel - java

I want to create a semi-transparent JPanel. I've done it by simply using RGBA value of color constructor but problem is when i m using event handling is not woking properly. My requirement is a semi transparent Jpanel when mouse enters it border of this panel became visible and if mouse exit the border shoud not visible. I have done this by following code but problem is its not working properly for transparent backgroud (RGBA) but it working fine for RGB color.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class MDCW extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MDCW frame = new MDCW();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MDCW() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1013, 551);
contentPane = new JPanel();
contentPane.setBackground(new Color(0, 139, 139));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JPanel panel = new JPanel();
panel.setBackground(new Color(0, 0, 0,50));
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
panel.setBorder(new LineBorder(new Color(255, 255, 255), 5));
}
#Override
public void mouseExited(MouseEvent e) {
panel.setBorder(null);
}
});
panel.setBounds(360, 155, 215, 215);
contentPane.add(panel);
final JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(0, 0, 0));
panel_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
panel_1.setBorder(new LineBorder(new Color(255, 255, 255), 5));
}
#Override
public void mouseExited(MouseEvent e) {
panel_1.setBorder(null);
}
});
panel_1.setBounds(84, 155, 215, 215);
contentPane.add(panel_1);
}
}

JPanel does not support semi-transparent backgrounds. There are two steps needed to take care of this problem:
First, to have any correctly-functioning transparency at all, you must setOpaque(false) on the panel; otherwise you will have glitches, because an opaque panel is assumed to completely cover what is underneath its bounds.
However, when opaque is false, the panel also does not draw its background at all (!) so you will have to draw a background in paintComponent.
Here is a drop-in replacement class which will take care of both of these steps.
private class TransparentPanel extends JPanel {
{
setOpaque(false);
}
public void paintComponent(Graphics g) {
g.setColor(getBackground());
Rectangle r = g.getClipBounds();
g.fillRect(r.x, r.y, r.width, r.height);
super.paintComponent(g);
}
}
I’ve checked that it works in your program if I change the first panel creation to:
final JPanel panel = new TransparentPanel();

It's easy to do it like so:
// initialise JPanel
JPanel somePanel = new JPanel(new GridBagLayout());
somePanel.setBackground(new Color(0,0,0,x);
x in this case is the level of transparency you're looking for
0 being invisible, 100 being solid.
e.g:
somePanel.setBackground(new Color(0,0,0,55)
See:
http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html

Related

Issue when adding two JPanels

I'm trying to add two JPanels to a JFrame, one with a simple backround and another one with buttons etc. Either I get only buttons or only the background. I can't find a solution to my problem anywhere, so any help would be appreciated. I'm still new to Java, so please don't hate.
GuiMainMenu:
public class GuiMainMenu extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = -7936366600070922227L;
Color blue = new Color(114, 137, 218);
Color gray = new Color(44, 47, 51);
Color white = new Color(255, 255, 255);
ImagePanel panel = new ImagePanel(new ImageIcon("image.png").getImage());
public static int width;
public static int height;
JPanel p = new JPanel();
JPanel p1 = new JPanel();
JLabel l = new JLabel();
JLabel l1 = new JLabel();
JLabel l2 = new JLabel();
JButton b = new JButton();
JButton b1 = new JButton();
JButton b2 = new JButton();
String title = "-";
public GuiMainMenu() {
setSize(m.X, m.Y);
setTitle(title);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
p.setLayout(null);
width = getWidth();
height = getHeight();
getRootPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
width = getWidth();
height = getHeight();
addButtons();
addLabels();
}
});
addLabels();
addButtons();
add(p);
add(panel);
setVisible(true);
}
public void addLabels() {
l.setSize(width, height);
l.setLocation(5, -40);
l.setText("x");
l.setHorizontalAlignment(SwingConstants.LEFT);
l.setVerticalAlignment(SwingConstants.BOTTOM);
l.setForeground(blue);
l.setFont(new Font("Trebuchet MS", Font.PLAIN, 15));
l1.setSize(width, height);
l1.setLocation(-22, -40);
l1.setText("y");
l1.setHorizontalAlignment(SwingConstants.RIGHT);
l1.setVerticalAlignment(SwingConstants.BOTTOM);
l1.setForeground(blue);
l1.setFont(new Font("Trebuchet MS", Font.PLAIN, 15));
l2.setText("test label");
l2.setSize(width, height);
l2.setLocation(0, -75);
l2.setVerticalAlignment(SwingConstants.CENTER);
l2.setHorizontalAlignment(SwingConstants.CENTER);
l2.setForeground(blue);
l2.setFont(new Font("Trebuchet MS", Font.BOLD, 26));
p.add(l);
p.add(l1);
p.add(l2);
validate();
}
public void addButtons() {
b.setText("button0");
b.setFocusable(false);
b.setBorder(null);
b.setLocation(width / 2 - 200, height / 2 - 35);
b.setSize(400, 35);
b.setForeground(white);
b.setBackground(blue);
b.addActionListener(this);
b1.setText("button1");
b1.setFocusable(false);
b1.setBorder(null);
b1.setLocation(width / 2 - 200, height / 2 + 10);
b1.setSize(400, 35);
b1.setForeground(white);
b1.setBackground(blue);
b1.addActionListener(this);
p.add(b);
p.add(b1);
validate();
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
ImagePanel Class:
class ImagePanel extends JPanel {
private static final long serialVersionUID = -7270956677693528549L;
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, GuiMainMenu.width, GuiMainMenu.height, null);
}
}
p.setLayout(null);
Don't use a null layout. Swing was designed to be used with layout managers.
Read the section from the Swing tutorial on Layout Managers for more information and working examples.
Either I get only buttons or only the background
add(p);
add(panel);
The default layout manager for a JFrame is the BorderLayout. If you don't specify a constraint both components get added to the CENTER. However only the last one added will be displayed.
Try the following to see the difference:
add(p, BorderLayout.PAGE_STRT);
add(panel, BorderLayout.CENTER);
one with a simple backround and another one with buttons etc.
However above is not what you want. Swing components have a parent/child relationship. So what you really need is:
backgroundPanel.add(buttonPanel);
add(backgroundPanel, BorderLayout.CENTER);
Note I used more meaningful names because "p" and "panel" and not descriptive. Use descriptive names for variable so people can understand what they mean.
I suppose you want to display a JFrame with a background image and various components. I think after reviewing your code that there is some misunderstanding on your part causing the problem.
I've created a short snippet of code that does the basics and maybe helps you to solve your problem. (Not tested!)
#SuppressWarnings("serial")
public class GuiMainMenu extends JFrame{
private BufferedImage imageBackground; // TODO: load your background image
public GuiMainMenu(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1024, 768));
setMinimumSize(new Dimension(800, 600));
// TODO: setLayout if needed
JPanel panel = (JPanel)add(new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(imageBackground, 0, 0, this);
}
});
addOtherComponents(panel);
pack();
setLocationRelativeTo(null);
setTitle("Your Title her");
setVisible(true);
}
private void addOtherComponents(JPanel panel){
//TODO: add the needed Stuff
//panel.add ...
}
}

KeyEvent won't change background color of JPanels

I want the KeyEvent to change the background color of my JPanels. Nothing happens when I press anything on the keyboard. One of my applications specifications is that I need a 'Customized component extended from JPanel.' which is why I have another class for my graphics panel.
My problem is when G is pressed nothing happens but my center panel should turn green...
Here is code for part of my application.
public class Maths extends JFrame implements KeyListener
{
private JPanel pNorth = new JPanel();
private JPanel pSouth = new JPanel();
private JPanel pCenter = new JPanel();
private JPanel pEast = new JPanel();
private JPanel pWest = new JPanel();
private File file;
private JPanel pDraw = new GraphicsPanel();
public static void main(String args[])
{
new Maths();
}
public Maths()
{
mainFrame = new JFrame();
mainFrame.setTitle("Maths Test Game");
mainFrame.setLayout(new BorderLayout());
mainFrame.setSize(1200, 800);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(pNorth, BorderLayout.NORTH);
mainFrame.add(pSouth, BorderLayout.SOUTH);
mainFrame.add(pCenter, BorderLayout.CENTER);
mainFrame.add(pEast, BorderLayout.EAST);
mainFrame.add(pWest, BorderLayout.WEST);
pNorth.setLayout(new FlowLayout());
pSouth.setLayout(new FlowLayout());
pCenter.setLayout(new FlowLayout());
pEast.setLayout(new FlowLayout());
pWest.setLayout(new FlowLayout());
addKeyListener(this);
setFocusable(true);
mainFrame.setVisible(true);
}
class GraphicsPanel extends JPanel
{
GraphicsPanel()
{
// set a preferred size for the custom panel.
setPreferredSize(new Dimension(250, 300));
}
#Override
public void paint(Graphics g)
{
super.paint(g);
// set blue color for drawing
g.setColor(Color.blue);
// face
g.drawOval(90, 70, 80, 80);
// eyes
g.drawOval(110, 95, 5, 5);
g.drawOval(145, 95, 5, 5);
// nose
g.drawLine(130, 95, 130, 115);
// mouth
g.drawArc(113, 115, 35, 20, 0, -180);
}
}
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_G)
{
pCenter.setBackground(Color.green);
}
repaint();
}
#Override
public void keyReleased(KeyEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
}
There are a multitude of reasons this is probably not working, generally, you don't want to attach KeyListeners to top level containers like JFrame, as they is simply to many things that can get in the way and prevent the frame from raising key events.
Instead, use the key bindings API. See How to Use Key Bindings for more details

background image help, JPanel, JFrame, anything?

I want to make a background image for a game I'm designing but I cant figure out the right way to get the effect I want, I want a background that can be seen behind text etc. basically having the background cover the whole JFrame / JPanel not just one section of the layout (e.g. BorderLayout.Center) I think it does this anyway but if it does do that how do I make the background for those transparent to see the background which is behind...
Confusing i know but I hope someone here understands what I am trying to do and can help... this is my current code. I have been playing around with the background so dont read to much in how i have written it.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JLabel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
ImageIcon banner = new ImageIcon("images/banner.png", "North Background");
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JLabel northpanel = new JLabel();
northpanel.setLayout(new BorderLayout());
northpanel.setIcon(banner);
northpanel.add(new JSeparator(), BorderLayout.PAGE_END);
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.setBackground(Game.getBackgroundColor());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
So if you already have a JPanel that has your image as Background and you want to add another panel over it with your components you can use Opacity to achieve this. Only the components added to this panel will be visible. Here's the code :
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class TransparentPane extends JPanel {
public TransparentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0f));
g2d.setColor(getBackground());
g2d.fill(getBounds());
g2d.dispose();
}
}
Create a class that extends from JPanel and in its paint method draw an image over it.
Now create a class the extends from JFrame and in its constructor set its contentpane to the object of that JPanel class like below. Now you can add components to jframe.
class SimpleTest extends JFrame {
JButton btn = new JButton("A Game");
public SimpleTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new CPane());
getContentPane().setBackground(Color.red);
getContentPane().add(btn, BorderLayout.NORTH);
setSize(new Dimension(300, 300));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleTest();
}
});
}
}
class CPane extends JPanel {
Image back;
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
back = ImageIO.read(getClass().getResource("back.jpg"));
} catch (Exception ex) {
}
g.drawImage(back, 0, 0, this);
}
}
If you want to make a jpanel transparent then do
panel.setOpaque(false);

Swing - windowStateChanged event trouble

I have a JFrame where some elements (one, for now) have to be centered manually on the contentPane when resizing the window or changing the window state. Resizing event (componentResized) works fine but the windowStateChanged event is causing problems because it doesn't seem to "update" the contentPane's new size properly - it keeps the previous value. This can be seen by simply printing the result of getSize called on contentPane.
Centering is done by programmatically changing the constraint of the component (using putConstraint, SpringLayout). The issue is that getWidth used in that method returns "wrong" values which results in an uncentered component.
Maybe another listener is needed here?
Additional info: Eclipse with WindowBuilder, Linux Mint 15
Any kind of advice is appreciated.
addWindowStateListener(new WindowStateListener()
{
public void windowStateChanged(WindowEvent e)
{
System.out.println(contentPane.getSize()); // returns old size
tfArrayPanelCenter();
}
});
public void tfArrayPanelCenter()
{
int padding = (contentPane.getWidth()
- tfArrayPanel.getPreferredSize().width - HGAP) / 2;
sl_contentPane.putConstraint(SpringLayout.WEST, tfArrayPanel, padding,
SpringLayout.WEST, contentPane);
}
As requested I'm posting more code - a simple game of hangman. I think the JFrame constructor should be enough (other stuff is non-GUI):
/**
* Create the frame.
*/
public MainWindow()
{
addWindowStateListener(new WindowStateListener()
{
// no "#Override" was generated but it is the same with it
public void windowStateChanged(WindowEvent e)
{
System.out.println("EVENT: " + contentPane.getSize() + ", "
+ getExtendedState() + ", " + e.getOldState()); // amusingly, states are actually correct - interchanging between 0 (Frame.NORMAL) and 6 (Frame.MAXIMIZED_BOTH) when I maximize and "unmaximize"
tfArrayPanelCenter();
}
});
addComponentListener(new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent e)
{
tfArrayPanelCenter();
}
});
setTitle("Hangman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 790, 620);
setLocationRelativeTo(null);
GameMechanics.setMainWindow(this);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
sl_contentPane = new SpringLayout(); // I've declared this as a field, it is normally generated as a local variable
contentPane.setLayout(sl_contentPane);
newGame = new JButton("New Game");
newGame.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
newGame.setVisible(false);
lblGame.setVisible(true);
lblGame.setBtnHintStatus(true);
lblGame.setLblTriesLeftCountText(Integer
.toString(GameMechanics.TRIES));
lblGame.paint(triesLeft);
inputChars = new ArrayList<Character>();
GameMechanics.loadWord();
initControls(GameMechanics.getGuessingWord().length());
lblTest.setText(GameMechanics.getGuessingWord().toUpperCase());
}
});
newGame.setFont(new Font("Tempus Sans ITC", Font.BOLD, 12));
sl_contentPane.putConstraint(SpringLayout.NORTH, newGame, 10,
SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, newGame, 10,
SpringLayout.WEST, contentPane);
newGame.setPreferredSize(new Dimension(100, 40));
newGame.setFocusPainted(false);
contentPane.add(newGame);
tfArrayPanel = new JPanel();
sl_contentPane.putConstraint(SpringLayout.SOUTH, tfArrayPanel, -10,
SpringLayout.SOUTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, tfArrayPanel, 400,
SpringLayout.WEST, contentPane);
contentPane.add(tfArrayPanel);
tfArrayPanel.setLayout(new FlowLayout(FlowLayout.CENTER, HGAP, VGAP));
lblTest = new JLabel("New label");
sl_contentPane.putConstraint(SpringLayout.NORTH, lblTest, 15,
SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, lblTest, 416,
SpringLayout.WEST, contentPane);
contentPane.add(lblTest);
lblGame = new GameLabels(); // custom JPanel imported into the Palette and used from there on the MainWindow
sl_contentPane.putConstraint(SpringLayout.SOUTH, lblGame, -60,
SpringLayout.SOUTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, lblGame, 10,
SpringLayout.WEST, contentPane);
lblGame.setPreferredSize(new Dimension(315, 130));
lblGame.setLayout(null);
lblGame.setVisible(false);
lblGame.setMainWindow(this);
contentPane.add(lblGame);
}
"Any kind of advice is appreciated."
Not sure if it fully fits your requirements, but if all you want to do is keep a set of components constantly centered (no matter size of the containing frame), as comments pointed out, you can just wrap everything in a GridBagLayout
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class CenteringWithGridBag {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JPanel gridBagPanel = new JPanel(new GridBagLayout());
gridBagPanel.setBorder(new TitledBorder("JPanel with GridBagLayout"));
JPanel innerPanel = new JPanel();
innerPanel.setBorder(new TitledBorder("JPanel Wrap"));
innerPanel.add(new JButton("Button"));
gridBagPanel.add(innerPanel);
JFrame frame = new JFrame("GridBagLayout Test");
frame.add(gridBagPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I don't think you need WindowStateListener for this because whenever you maximize or minimize or get the window in normal state the componentResized is called. Just remove the WindowStateListener and it works fine. You said componentResized is working for you, then you probably don't need WindowStateListener
addComponentListener(new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent e)
{
tfArrayPanelCenter();
}
});
Upon reading kleopatra's suggestion I approached the problem in another way. All I've done was putting the EAST constraint too (there were only WEST and SOUTH before) on the JPanel that needed to be centered. JPanel's FlowLayout handles the actual centering of the elements located within it.
To be honest, this doesn't truly answer the question itself but it is a solution to my troubles regarding the centering of components. Good enough, I guess.

Draw a line in a JPanel with button click in Java

I want to draw a line in a JPanel.
This is my GUI and I want a line in the JPanel in white.
I find many examples but the problem is the how to use it.
In many exmples, always they draw in a JFrame that extends from a JPanel.
I want to add the Panel to the Frame and add some buttons to draw lines in many directions and use the X button in center to clean the JPanel.
This is the code of the interface:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class circuit extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
circuit frame = new circuit();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public circuit() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 559, 332);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 21, 359, 255);
contentPane.add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setBackground(Color.WHITE);
JLabel label = new JLabel("New label");
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
/////////////
}
});
label.setIcon(new ImageIcon("C:\\Users\\achermen\\Desktop\\up.png"));
label.setBounds(447, 66, 46, 48);
contentPane.add(label);
JLabel label_1 = new JLabel("New label");
label_1.setIcon(new ImageIcon("C:\\Users\\achermen\\Desktop\\down.png"));
label_1.setBounds(447, 159, 46, 48);
contentPane.add(label_1);
JLabel label_2 = new JLabel("New label");
label_2.setIcon(new ImageIcon("C:\\Users\\achermen\\Desktop\\right.png"));
label_2.setBounds(495, 112, 46, 48);
contentPane.add(label_2);
JLabel label_3 = new JLabel("New label");
label_3.setIcon(new ImageIcon("C:\\Users\\achermen\\Desktop\\left.png"));
label_3.setBounds(398, 112, 46, 48);
contentPane.add(label_3);
JLabel label_4 = new JLabel("New label");
label_4.setIcon(new ImageIcon("C:\\Users\\achermen\\Desktop\\1303860240_list-remove.png"));
label_4.setBounds(447, 112, 46, 48);
contentPane.add(label_4);
}
}
This is the code to draw a line
public void paint(Graphics graphics)
{
graphics.drawLine(10, 20, 300, 310);
}
So how to use this lines ....
Thanks in advance.
Best regards,
Ali
It may be easier to draw lines using the following approach:
click to mark the first endpoint
drag to show the line in progress
release to mark the second endpoint
This related example may offer some additional guidance.
Addendum
The example below implements the outline above.
I've update the example to show how to use a panel of buttons to affect the drawing.
See also this related example that uses the Action interface with key bindings.
I've updated this example to use Key Bindings.
LinePanel.java
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
/**
* #see https://stackoverflow.com/questions/6991648
* #see https://stackoverflow.com/questions/6887296
* #see https://stackoverflow.com/questions/5797965
*/
public class LinePanel extends JPanel {
private MouseHandler mouseHandler = new MouseHandler();
private Point p1 = new Point(100, 100);
private Point p2 = new Point(540, 380);
private boolean drawing;
public LinePanel() {
this.setPreferredSize(new Dimension(640, 480));
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
private class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
drawing = true;
p1 = e.getPoint();
p2 = p1;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
drawing = false;
p2 = e.getPoint();
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
if (drawing) {
p2 = e.getPoint();
repaint();
}
}
}
private class ControlPanel extends JPanel {
private static final int DELTA = 10;
public ControlPanel() {
this.add(new MoveButton("\u2190", KeyEvent.VK_LEFT, -DELTA, 0));
this.add(new MoveButton("\u2191", KeyEvent.VK_UP, 0, -DELTA));
this.add(new MoveButton("\u2192", KeyEvent.VK_RIGHT, DELTA, 0));
this.add(new MoveButton("\u2193", KeyEvent.VK_DOWN, 0, DELTA));
}
private class MoveButton extends JButton {
KeyStroke k;
int dx, dy;
public MoveButton(String name, int code,
final int dx, final int dy) {
super(name);
this.k = KeyStroke.getKeyStroke(code, 0);
this.dx = dx;
this.dy = dy;
this.setAction(new AbstractAction(this.getText()) {
#Override
public void actionPerformed(ActionEvent e) {
LinePanel.this.p1.translate(dx, dy);
LinePanel.this.p2.translate(dx, dy);
LinePanel.this.repaint();
}
});
ControlPanel.this.getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(k, k.toString());
ControlPanel.this.getActionMap()
.put(k.toString(), new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
MoveButton.this.doClick();
}
});
}
}
}
private void display() {
JFrame f = new JFrame("LinePanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.add(new ControlPanel(), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new LinePanel().display();
}
});
}
}
Is this going to work like an etch-a-sketch? Then you need to track the current position of the point.
Point current = new Point(0, 0); //for example.
Then when the user clicks the buttons you can simply increment or decrement x and y accordingly.
On left arrow:
current.setX(current.getX() - INC);
where INC could be a variable that specifies the length of the distance to draw the line. Maybe 5? Always set a second point p1 to the previous location though.
It is always easier to create a class that extends Canvas or JPanel to draw on rather than draweing directly on the JFrame.
e.g.
public class Circuit extends JFrame {
Point p1, current;
JPanel drawPanel;
//your other declarations
public Circuit(){
super();
drawPanel = new DrawPanel();
p1 = new Point(0, 0);
current = new Point(0, 0);
add(drawPanel, BorderLayout.CENTER);
//your other code
}
class DrawingPanel extends JPanel{
public void paintComponent(Graphics g){
g.drawLine(p1.getX(), p1.getY(), current.getX(), current.getY());
}
}
//the rest of your code.
}
There is a simple answer for triggering graphics: e.g. The following code can be placed inside a click event and used for drawing a few simple objects on a jPanel. jPanel1 in this case was situated on one side of a tabbed jPanel7 and next to the triggering button. To do this in netbeans GUI, the code was placed inside the button action event. Once the usual errors appeared for not having the proper imports, right click on the code and click on "fix imports". Bingo, all is well :-) Warning: the setBackground command for the panel will override the graphics object. If you set the background color without using the graphics object, you will not see your objects!
Graphics g = jPanel1.getGraphics();
g.setColor(Color.blue);
g.drawLine( 0, 50, 20, 50);
g.setColor(Color.white);
g.fillRect(40, 50, 20, 20);
g.setColor(Color.blue);
g.drawRect(40, 50, 20, 20);
g.drawOval(80, 50, 20, 20);
g.setColor(Color.green);
g.fillOval(80, 50, 18, 18);
This restores your faith in true love :-)
The difficulty here is that any change or repaint will erase your effort. This approach is specifically discouraged by the Java founders. But in the current rendition of Netbeans Swing, where extending the jPanel is made difficult by locking code changes, this approach could be your only short term solution. A simple persistent graphic extension for the jPanel would be a most welcome addition to the current Netbeans Swing environment, a graphics panel. This would allow you to drag and drop the graphics panel and then get on with the event driven use of that panel. 40 other IDE's already have this, it seems Java has been slow to add this feature.

Categories

Resources