How to make JFrame transparent while components are visible - java

I'm student studying java swing. And I tried to programming simple program.
What I want is a notepad program that toggles between transparent and opaque when you press Ctrl+Alt.
Now press Ctrl + Alt to toggle between transparent and opaque. However, the font in transparent mode also changes. I used the SetFont () function to force the font to be set, but it only applies in opaque mode and the setFont function does not work in transparent mode.
If I remove setBackground () from the toggleVisible () function, the font will not change either. My guess seems to change the setBackground font. Anyone who knows how to make a frame transparent without using setBackground? Or I would appreciate it if you could help me solve the problem.
package ffmemo;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsDevice;
import static java.awt.GraphicsDevice.WindowTranslucency.TRANSLUCENT;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.BitSet;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class FFMemo {
public static void main(String[] args){
new FFMemoFrame();
}
}
class FFMemoFrame extends JFrame {
BitSet keyBitSet = new BitSet(2); //0: ctrl key, 1: alt key
boolean visible = true;
JTextArea textArea;
JScrollPane scrollPane;
Color color;
FFMemoFrame(){
//PARAM: window title
super("FFMemo");
setSize(500, 200);
setLocation(100, 100);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
color = getBackground();
textArea = new JTextArea();
textArea.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void changedUpdate(DocumentEvent e){
warn();
}
#Override
public void insertUpdate(DocumentEvent e) {
warn();
}
#Override
public void removeUpdate(DocumentEvent e) {
warn();
}
public void warn(){
//System.out.println(textArea.getText());
repaint();
}
});
textArea.append("hello, world!");
textArea.setLineWrap(true);
textArea.setVisible(true);
textArea.setFont(new Font("굴림", Font.PLAIN, 20));
textArea.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
String s = e.getKeyText(e.getKeyCode());
if(s.equals("Ctrl")) keyBitSet.set(0, true);
else if(s.equals("Alt")) keyBitSet.set(1, true);
if(keyBitSet.get(0) && keyBitSet.get(1)){
toggleVisible();
}
}
public void keyReleased(KeyEvent e){
String s = e.getKeyText(e.getKeyCode());
if(s.equals("Ctrl")) keyBitSet.set(0, false);
else if(s.equals("Alt")) keyBitSet.set(1, false);
}
});
scrollPane = new JScrollPane(textArea);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVisible(true);
add(scrollPane);
revalidate();
}
private void toggleVisible(){
if(visible){
setBackground(new Color(255, 255, 255, 1));
textArea.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
scrollPane.setOpaque(false);
textArea.setFont(new Font("굴림", Font.PLAIN, 20));
}
else{
setBackground(new Color(255, 255, 255, 255));
textArea.setOpaque(true);
scrollPane.getViewport().setOpaque(true);
scrollPane.setOpaque(true);
textArea.setFont(new Font("굴림", Font.PLAIN, 20));
}
repaint();
visible = !visible;
}
}
+)
There are runtime screenshot. "|" at second picture is a cursor which moved right as far as possible. and I don't understand why I can't move cursor to right more.
Something must be wrong... but I don't know what it is.
first
second

Related

Java - how to zoom in/zoom out text in JTextArea

I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}

paintComponent() is not working when add to panel

I was working a swing application that can draw graphs of maths function. I was using getGraghics functions but I have no idea how I remove and repaint them so I decided to override the paintComponent() method to implement what I was looking for
what I want to do is drawing function graphs in a panel after user click the button. but it seems paintCompnent() is not working. I have followed exactly on any existing tutorial and similar questions on stack overflow.but none of them working for me :( it just made no sense:(
Please help I have stuck on this problem for over a whole night:(
following were codes for drawing functions graphs but as it is not working so I only left the part of drawing coordinate system for testing and after that is the code of how I create an instance and try to add it to my panel in the main class
class drawfunction extends JPanel{
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.drawLine(0, 200, 400, 200);
g.drawLine(200,0 , 200, 400);
}
}
then is the code in main class
JPanel panel = new JPanel();
panel.setBounds(14, 104, 400, 400);
contentPane.add(panel);
panel.setBackground(Color.white);
JButton btnNewButton = new JButton("View the graph");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//a= Integer.parseInt(cofficient_a.getText());
//b= Integer.parseInt(cofficient_b.getText());
//c= Integer.parseInt(cofficient_c.getText());
//d= Integer.parseInt(cofficient_d.getText());
//e= Integer.parseInt(cofficient_e.getText());
drawfunction a=new drawfunction();
panel.add(a);
});
Can anyone please tell me what I should do to fix this. Thank you !!!!
Two basic things...
A component has a default preferred size of 0x0, so when adding it a container under the control of just about any layout manager will get it sized to 0x0 (or very close)
Swing is generally lazy, it won't update the UI when you add or remove components, that could impede performance, as the UI doesn't know the best to update the UI based on what you are doing, instead, you need to call revalidate and (most of the time) repaint to have the UI updated
For example...
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.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel center;
public TestPane() {
setLayout(new BorderLayout());
JButton btnNewButton = new JButton("View the graph");
center = new JPanel();
center.setPreferredSize(new Dimension(400, 400));
add(center);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
remove(center);
//a= Integer.parseInt(cofficient_a.getText());
//b= Integer.parseInt(cofficient_b.getText());
//c= Integer.parseInt(cofficient_c.getText());
//d= Integer.parseInt(cofficient_d.getText());
//e= Integer.parseInt(cofficient_e.getText());
center = new Drawfunction();
add(center);
revalidate();
repaint();
}
});
add(btnNewButton, BorderLayout.NORTH);
}
public class Drawfunction extends JPanel {
public Drawfunction() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.red);
g2d.drawLine(0, 200, 400, 200);
g2d.drawLine(200, 0, 200, 400);
g2d.dispose();
}
}
}
}

How to change JLabel's size when the font size is changed?

I've a JLabel. The code for JLabel is as follows.
panelmain = new JPanel();
panelmain.setLayout(null);
panelmain.setPreferredSize(new java.awt.Dimension(800, 600));
panelmain.addComponentListener(listen);
panelmain.setBorder(null);
titlebar = new JLabel("Hello World");
titlebar.setBounds(10, 10, 100, 30);
panelmain.add(titlebar);
My questing is that if I change font of titlebar (i.e. JLabel), then how to change size (which is already set in code as titlebar.setBounds(10, 10, 100, 30);) of titlebar?
Edit by Girish
My full code is as below.
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class IFrame extends JInternalFrame {
/**
*
*/
private static final long serialVersionUID = 6526561589695424088L;
private JScrollPane jsp;
private IFListen listen;
private JPanel panelmain;
protected JPanel panel;
private String title;
private JLabel titlebar;
public IFrame()
{
this.title="";
init();
}
public IFrame(String title)
{
this.title=title;
init();
}
private void init()
{
setLayout(null);
listen=new IFListen();
panelmain=new JPanel();
panelmain.setLayout(null);
panelmain.setPreferredSize(new java.awt.Dimension(800, 600));
panelmain.addComponentListener(listen);
panelmain.setBorder(null);
titlebar=new JLabel("Hello World");
titlebar.setFont(new java.awt.Font("Monotype Corsiva", 1, 48));
panelmain.add(titlebar);
panel=new JPanel();
panel.setBorder(javax.swing.BorderFactory.createTitledBorder(title));
panel.setMinimumSize(new java.awt.Dimension(400, 400));
panel.setSize(400, 400);
panelmain.add(panel);
jsp=new JScrollPane(panelmain);
jsp.setBorder(null);
add(jsp);
this.addComponentListener(listen);
}
//INFO Custom Methods
public void setTitleFont(java.awt.Font font)
{
titlebar.setFont(font); //Here I want to change size of label.
}
//INFO Listener Class for IFrame
private class IFListen implements ComponentListener
{
//INFO Overridden Methods
#Override
public void componentResized(ComponentEvent e)
{
if(e.getSource() instanceof IFrame)
jsp.setBounds(5, 5, getWidth()-20, getHeight()-20);
else if(e.getSource()==panelmain)
{
panel.setLocation(Integer.parseInt(panelmain.getWidth()/2-panel.getWidth()/2+""), 0);
}
}
//INFO Unimplemented Methods
#Override
public void componentShown(ComponentEvent arg0) {}
#Override
public void componentHidden(ComponentEvent arg0) {}
#Override
public void componentMoved(ComponentEvent arg0) {}
}
}
I've commented where the font size is changed and I want to change size of jlabel.
Don't use setPreferredSize, you've just removed all the calculations that the label uses to calculate the size it would like to be.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Make use of appropriate layouts. The important thing here is, no one layout will ever do everything you want. You will need to learn to take advantage of the each layout's strengths (and weaknesses) and use them to your advantage. This is what is commonly known as "compound layouts". Have a look at Laying Out Components Within a Container for more details and ideas
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
private JSlider slider;
public TestPane() {
label = new JLabel("Look, no hands!");
setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
add(panel);
slider = new JSlider(8, 96);
add(slider, BorderLayout.SOUTH);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
Font font = label.getFont();
font = font.deriveFont((float)slider.getValue());
label.setFont(font);
}
});
slider.setValue(8);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
JLabel is surprising proficient, changing the font (text/icon) will automatically cause it to invalidate the layout and request a repaint all by itself...

Java graphics, making the window flash in different colors

this is my first post here. I am currently learning about basic GUI and Graphics in java. I'm still pretty new to the language, and it's my first language as well. As I learn java I like to experiment and play with the new tools I acquire from reading. As a result I wanted to make a window where the colors it is filled with will flash, currently, i wanted to stay simple and have it flash from orange to cyan and back. However, right now, all my program does is start white, and fill in with cyan and the text, and then stop changing whatsoever, and I'm not sure why this is.
Please point me in the right direction, thanks!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ColorFlash extends JFrame{
private static class Display extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int h = 200; h > 25; h--){
g.setColor(Color.ORANGE);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.CYAN);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.ORANGE);
g.drawString("Hello world!", 30, 35);
g.drawOval(100, 100, 60, 60);
}
}
}
private static class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
public static void main (String [] args){
Display displayPanel = new Display();
JButton okButton = new JButton("OK");
ButtonHandler listener = new ButtonHandler();
okButton.addActionListener(listener);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
//content.add(okButton, BorderLayout.SOUTH);
//subContent.add(displayPanel, BorderLayout.SOUTH);
//content.add(okButton, BorderLayout.SOUTH);
content.add(okButton, BorderLayout.SOUTH);
JFrame window = new JFrame("GUI Test");
window.setContentPane(content);
window.setSize(500, 500);
window.setLocation(100,100);
window.setVisible(true);
}
}
Start by taking a look at Performing Custom Painting and Painting in AWT and Swing
Basically, what's happening is whatever is painted last in your loop is what is actually been painted to the screen
What you need is some kind of timer/trigger that can change the color you want to paint with and repaint the component.
Take a look at How to use Swing Timers for more details
For example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestPaint {
private static class Display extends JPanel {
private Color[] colors = new Color[]{Color.ORANGE, Color.CYAN};
private int colorIndex;
public Display() {
Timer timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setBackground(colors[colorIndex % 2]);
colorIndex++;
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.ORANGE);
g.drawString("Hello world!", 30, 35);
g.drawOval(100, 100, 60, 60);
}
}
public static void main(String[] args) {
new TestPaint();
}
public TestPaint() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Display());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You might also like to take a look at Initial Threads

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