Draw in an image inside panel - java

I have a panel with two buttons. I'm trying to insert an image inside the panel and I want to draw lines inside the image after clicking on a button. I have used the below code but this doesn't seem to work.
public class Try_Panel extends JFrame {
// start attributes
private JPanel jPanel1 = new JPanel(null, true);
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
// end attributes
public Try_Panel(String title) {
// Frame-Init
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 300;
int frameHeight = 300;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);
// start components
jPanel1.setBounds(48, 24, 209, 145);
jPanel1.setOpaque(false);
cp.add(jPanel1);
jButton1.setBounds(88, 208, 75, 25);
jButton1.setText("jButton1");
jButton1.setMargin(new Insets(2, 2, 2, 2));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1_ActionPerformed(evt);
}
});
cp.add(jButton1);
jButton2.setBounds(184, 208, 75, 25);
jButton2.setText("jButton2");
jButton2.setMargin(new Insets(2, 2, 2, 2));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2_ActionPerformed(evt);
}
});
cp.add(jButton2);
// end components
setVisible(true);
} // end of public Try_Panel
// start methods
public void jButton1_ActionPerformed(ActionEvent evt) {
BufferedImage image=new BufferedImage(jPanel1.getWidth(), jPanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
JLabel l=new JLabel(new ImageIcon(image));
Graphics graphics = image.getGraphics();
Graphics2D g = (Graphics2D) graphics;
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.BLUE);
g.drawLine(0, 0, 300, 400);
jPanel1.add(l);
} // end of jButton1_ActionPerformed
public void jButton2_ActionPerformed(ActionEvent evt) {
// TODO add your code here
} // end of jButton2_ActionPerformed
// end methods
public static void main(String[] args) {
new Try_Panel("Try_Panel");
} // end of main
} // end of class Try_Panel
The biggest problem is the same code worked in my other class.

Try wrapping the image inside the ImageIcon AFTER you have updated it. Also, you should also call Graphics#dispose when you are finished rendering to the graphics context.
public void jButton1_ActionPerformed(ActionEvent evt) {
BufferedImage image=new BufferedImage(jPanel1.getWidth(), jPanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = image.createGraphics();
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.BLUE);
g.drawLine(0, 0, 300, 400);
g.dispose();
JLabel l=new JLabel(new ImageIcon(image));
jPanel1.add(l);
}
You should also rely on the layout managers rather the trying to do it yourself, it will simply make your life easier.
Personally, I think it would easier to paint directly to a custom component, like JPanel. Check out Performing Custom Painting for more details
UPDATED with example
Basically, I changed your example to
Use layout managers
Load the UI within the context of the EDT
revalidate the jPanel1
public class BadLabel extends JFrame {
// start attributes
private JPanel jPanel1 = new JPanel(new BorderLayout(), true);
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
// end attributes
public BadLabel(String title) {
// Frame-Init
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 300;
int frameHeight = 300;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
// setResizable(false);
Container cp = getContentPane();
// cp.setLayout(null);
// start components
// jPanel1.setBounds(48, 24, 209, 145);
jPanel1.setOpaque(true);
jPanel1.setBackground(Color.RED);
cp.add(jPanel1);
JPanel buttons = new JPanel();
// jButton1.setBounds(88, 208, 75, 25);
jButton1.setText("jButton1");
jButton1.setMargin(new Insets(2, 2, 2, 2));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1_ActionPerformed(evt);
}
});
buttons.add(jButton1);
// jButton2.setBounds(184, 208, 75, 25);
jButton2.setText("jButton2");
jButton2.setMargin(new Insets(2, 2, 2, 2));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2_ActionPerformed(evt);
}
});
buttons.add(jButton2);
// end components
cp.add(buttons, BorderLayout.SOUTH);
setVisible(true);
} // end of public BadLabel
// start methods
public void jButton1_ActionPerformed(ActionEvent evt) {
BufferedImage image = new BufferedImage(jPanel1.getWidth(), jPanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = image.createGraphics();
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.BLUE);
g.drawLine(0, 0, 300, 400);
g.dispose();
JLabel l = new JLabel(new ImageIcon(image));
l.setBorder(new LineBorder(Color.BLUE));
jPanel1.add(l);
jPanel1.revalidate();
} // end of jButton1_ActionPerformed
public void jButton2_ActionPerformed(ActionEvent evt) {
// TODO add your code here
} // end of jButton2_ActionPerformed
// end methods
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
}
new BadLabel("BadLabel");
}
});
} // end of main
} // end of class BadLabel}

Something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.border.EmptyBorder;
public class Try_Panel {
// start attributes
private JButton jButton1 = new JButton("jButton1");
private JButton jButton2 = new JButton("jButton2");
private JLabel imageView;
BufferedImage image;
int x = 300;
int y = 50;
// end attributes
public Component getGui() {
JPanel gui = new JPanel(new BorderLayout(5, 5));
gui.setBorder(new EmptyBorder(3, 3, 3, 3));
image = new BufferedImage(300, 100, BufferedImage.TYPE_INT_RGB);
imageView = new JLabel(new ImageIcon(image));
gui.add(imageView, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
gui.add(buttons, BorderLayout.PAGE_END);
jButton1.setMargin(new Insets(2, 2, 2, 2));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1_ActionPerformed(evt);
}
});
buttons.add(jButton1);
jButton2.setMargin(new Insets(2, 2, 2, 2));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2_ActionPerformed(evt);
}
});
buttons.add(jButton2);
// end components
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
// Frame-Init
JFrame f = new JFrame("Try Panel");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
Container cp = f.getContentPane();
cp.setLayout(new BorderLayout(3, 3));
Try_Panel tp = new Try_Panel();
cp.add(tp.getGui());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
} // end of public Try_Panel
// start methods
public void jButton1_ActionPerformed(ActionEvent evt) {
Graphics graphics = image.getGraphics();
Graphics2D g = (Graphics2D) graphics;
g.setColor(Color.RED);
g.drawLine(0, 0, x, y);
x -= 4;
y += 2;
g.dispose();
imageView.repaint();
} // end of jButton1_ActionPerformed
public void jButton2_ActionPerformed(ActionEvent evt) {
// TODO add your code here
} // end of jButton2_ActionPerformed
} // end of class Try_Panel

Related

Blink boxes in sequence

I changed a program (see below) I nabbed and have managed to get it to do some of what I want. I need a number of rows/bands/stripes of 3 to blink in sequence. If you could imagine three sets of three vertical bars/bands and each bar numbered 1-3. I want to get each band/bar numbered 1 of each group to blink. So all bands numbered 1 blinks for a finite time, then bands numbered 2, then 3 then repeat. So when looking at it it looks like vertical stripes blinking 1,2,3,1,2,3 etc.
What's set out below and what I have described as boxes below refers to the bands I am talking about
class BelishN {
private Timer timer;
public class Drawing extends JPanel {
private int x = 125;// Not required - it was for the ball!
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(1, 1, 10, 770);
//Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(10, 1, 10, 770);
//Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(20, 1, 10, 770);
// Rectangle box6 = new Rectangle(165, 405, 20, 45);
//drawing the shapes
//Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
//g2.draw(ball);
g2.draw(box1);
//g2.draw(box2);
//g2.draw(box3);
//g2.draw(box4);
//g2.draw(box5);
//g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.ORANGE);
//g2.fill(ball);
changeColors = !changeColors;
if (changeColors) {
g2.setColor(Color.white);
//g2.fill(new Ellipse2D.Double(x, y, 100, 100));
g2.fill(box1 = new Rectangle(1, 1, 10, 770));//3 vertical bands are flashing together
g2.fill(box3 = new Rectangle(10, 1, 10, 770));
g2.fill(box5 = new Rectangle(20, 1, 10, 770));
}
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishN() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(800, 770); //Screen size
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
shapes.repaint();
}
});
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
//Positioning
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// in last line here, start the timer:
timer.start();
}
public static void main(String[] args) {
new BelishN();
}
}

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 ...
}
}

Having troubles rendering rectangle on button press

I am trying to add a Rectangle in the panel by button press and remove it with another one. It should work but it doesn't render anything, and I absolutely don't know why.
Can someone explain what I am doing wrong and give me some nice tips what I can improve with my code?
public class GUI extends JPanel {
public static boolean isRecVisible = false;
public static void main(String[] args) {
createGui();
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g);
g2d.drawRect(10, 10, 200, 200);
}
public static void createGui() {
int frameWidth = 550;
int frameHeight = 400;
int buttonWidth1 = 250;
int buttonHeight1 = 30;
int buttonWidth2 = 500;
int buttonHeight2 = 30;
int displayWidth = frameWidth - 20;
int displayHeight = frameHeight - 105;
GUI drawRec = new GUI();
JFrame f = new JFrame("Rectangle");
JPanel p = new JPanel();
JPanel display = new JPanel();
JButton addRec = new JButton("Add Rectangle");
JButton removeRec = new JButton("Remove Rectangle");
JButton colorRec = new JButton("Color Rectangle");
f.add(p);
p.add(addRec);
p.add(removeRec);
p.add(colorRec);
p.add(display);
display.setBackground(Color.LIGHT_GRAY);
f.setSize(frameWidth, frameHeight);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
display.setBounds(frameWidth / 2 - displayWidth / 2, 10, displayWidth, displayHeight);
addRec.setBounds(frameWidth / 2 - buttonWidth1 / 2 - 250 / 2, frameHeight - 85, buttonWidth1, buttonHeight1);
removeRec.setBounds(frameWidth / 2 - buttonWidth1 / 2 + 250 / 2, frameHeight - 85, buttonWidth1, buttonHeight1);
colorRec.setBounds(frameWidth / 2 - buttonWidth2 / 2, frameHeight - 60, buttonWidth2, buttonHeight2);
addRec.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (isRecVisible == false) {
isRecVisible = true;
display.add(drawRec);
display.repaint();
System.out.println("Rectangle has been drawn!");
} else {
System.out.println("Rectangle has already been drawn!");
return;
}
}
});
removeRec.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (isRecVisible == true) {
isRecVisible = false;
System.out.println("Rectangle has been removed!");
} else {
System.out.println("Rectangle has already been removed");
return;
}
}
});
}
}
display.add(drawRec);
display.repaint();
When you add (or remove) components to a visible frame then the basic logic is:
display.add(...);
display.revalidate();
display.repaint(); // sometimes needed
The revalidate() is the key method because it invokes the layout manager so the size/location of the component can be set.
However, that still won't fix the problem because your custom panel doesn't have a preferred size, so there is nothing to paint for your component.
You need to override the getPreferredSize() method of your custom panel to return the preferred size of your custom component. So in your case you might set the preferred size to be (220, 220) so the rectangle is centered in the panel.
Read the section from the Swing tutorial on Custom Painting for more information and complete working examples.
Note: the tutorial example will also show you how to better structure your code to make sure the GUI is created on the Event Dispatch Thread.
Rather than adding or removing components, it would make more sense here to add the custom painted panel on construction, and use the isRecVisible boolean as a flag to test for drawing the rectangle.
Something like shown here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JPanel {
public static boolean isRecVisible = false;
public static void main(String[] args) {
createGui();
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g);
if (isRecVisible) {
g2d.drawRect(10, 10, 200, 200);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600,400);
}
public static void createGui() {
int frameWidth = 550;
int frameHeight = 400;
GUI drawRec = new GUI();
drawRec.setBackground(Color.LIGHT_GRAY);
JFrame f = new JFrame("Rectangle");
JPanel p = new JPanel();
JButton addRec = new JButton("Add Rectangle");
JButton removeRec = new JButton("Remove Rectangle");
JButton colorRec = new JButton("Color Rectangle");
f.add(p, BorderLayout.PAGE_START);
p.add(addRec);
p.add(removeRec);
p.add(colorRec);
f.add(drawRec);
f.setSize(frameWidth, frameHeight);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
addRec.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isRecVisible = true;
drawRec.repaint();
}
});
removeRec.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isRecVisible = false;
drawRec.repaint();
}
});
}
}

JFrame Background Image does not work [duplicate]

This question already has answers here:
JFrame background image
(4 answers)
Closed 6 years ago.
I searched for a way to add an Image as an Bakground for my JFrame.
I found some Questions for that and tried several solutions but my Image won't show up and I don't know what's wrong (I'm a noob btw xd)
I DID see the other Questions but they DID NOT help me, I tried really hard but can't find my fault! So please (Human who marked my post as duplicate).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class prognose extends Frame {
// Anfang Attribute
private JTextField spendenbetrag = new JTextField();
private JTextField streamzeit = new JTextField();
private JLabel sBetragL = new JLabel();
private JLabel sZeitL = new JLabel();
private JButton prognosebutton = new JButton();
private ImageIcon prognosebuttonIcon = new ImageIcon("C:\\Users\\user\\Documents\\Programmieren\\Workspace\\images\\Button.png");
private JTextField ergebnis = new JTextField();
// Ende Attribute
public prognose() {
// Frame-Initialisierung
super();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) { dispose(); }
});
int frameWidth = 455;
int frameHeight = 580;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("Loot für die Welt");
setResizable(false);
Panel cp = new Panel(null);
add(cp);
// Anfang Komponenten
spendenbetrag.setText("");
cp.add(spendenbetrag);
streamzeit.setText("");
cp.add(streamzeit);
sBetragL.setText("Aktueller Spendenbetrag");
cp.add(sBetragL);
streamzeit.setBounds(152, 184, 145, 25);
spendenbetrag.setBounds(152, 112, 145, 25);
sBetragL.setBounds(152, 80, 145, 25);
sZeitL.setBounds(152, 152, 155, 25);
sZeitL.setText("Aktuelle Streamzeit");
cp.add(sZeitL);
prognosebutton.setBounds(184, 224, 80, 280);
prognosebutton.setText("");
prognosebutton.setMargin(new Insets(2, 2, 2, 2));
prognosebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
prognosebutton_ActionPerformed(evt);
}
});
prognosebutton.setIcon(prognosebuttonIcon);
prognosebutton.setBorderPainted(false);
prognosebutton.setBackground(Color.WHITE);
prognosebutton.setBorder(BorderFactory.createEtchedBorder(0, Color.DARK_GRAY, new Color(0xC0C0C0)));
prognosebutton.setIconTextGap(0);
cp.setBackground(Color.WHITE);
setUndecorated(false);
cp.add(prognosebutton);
ergebnis.setBounds(152, 512, 145, 25);
ergebnis.setText("");
ergebnis.setEditable(false);
cp.add(ergebnis);
// Ende Komponenten
setVisible(true);
setLayout(new BorderLayout());
setSize(455,580);
setVisible(true);
JLabel background=new JLabel(new ImageIcon("C:\\Users\\user\\Documents\\Programmieren\\Workspace\\images\\Background.png"));
add(background);
background.setLayout(new FlowLayout());
} // end of public prognose
// Anfang Methoden
public static void main(String[] args) {
new prognose();
} // end of main
public void prognosebutton_ActionPerformed(ActionEvent evt) {
// TODO hier Quelltext einfügen
String a;
String b;
a = spendenbetrag.getText();
b = streamzeit.getText();
double d;
double e = Double.parseDouble(a);
double f = Double.parseDouble(b);
d = e*(60/f)*48;
d = ((double)((int)(d*100)))/100;
String g = String.valueOf(d);
ergebnis.setText(g);
} // end of prognosebutton_ActionPerformed
// Ende Methoden
} // end of class prognose
Extend JFrame instead of Frame, use the setComponentPane to set the backround, Move the declaration of the background label to the top of the code. Add all the components to that label.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class prognose extends JFrame {
// Anfang Attribute
private JTextField spendenbetrag = new JTextField();
private JTextField streamzeit = new JTextField();
private JLabel sBetragL = new JLabel();
private JLabel sZeitL = new JLabel();
private JButton prognosebutton = new JButton();
private ImageIcon prognosebuttonIcon = new ImageIcon("C:\\test\\rak.png");
private JTextField ergebnis = new JTextField();
// Ende Attribute
public prognose() {
// Frame-Initialisierung
super();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) { dispose(); }
});
int frameWidth = 455;
int frameHeight = 580;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("Loot für die Welt");
setResizable(false);
JLabel background=new JLabel(new ImageIcon("C:\\test\\rak.png"));
setContentPane(background);
background.setLayout(new FlowLayout());
Panel cp = new Panel(null);
background.add(cp);
// Anfang Komponenten
spendenbetrag.setText("");
background.add(spendenbetrag);
streamzeit.setText("");
background.add(streamzeit);
sBetragL.setText("Aktueller Spendenbetrag");
background.add(sBetragL);
streamzeit.setBounds(152, 184, 145, 25);
spendenbetrag.setBounds(152, 112, 145, 25);
sBetragL.setBounds(152, 80, 145, 25);
sZeitL.setBounds(152, 152, 155, 25);
sZeitL.setText("Aktuelle Streamzeit");
background.add(sZeitL);
prognosebutton.setBounds(184, 224, 80, 280);
prognosebutton.setText("");
prognosebutton.setMargin(new Insets(2, 2, 2, 2));
prognosebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
prognosebutton_ActionPerformed(evt);
}
});
prognosebutton.setIcon(prognosebuttonIcon);
prognosebutton.setBorderPainted(false);
prognosebutton.setBackground(Color.WHITE);
prognosebutton.setBorder(BorderFactory.createEtchedBorder(0, Color.DARK_GRAY, new Color(0xC0C0C0)));
prognosebutton.setIconTextGap(0);
background.setBackground(Color.WHITE);
setUndecorated(false);
background.add(prognosebutton);
ergebnis.setBounds(152, 512, 145, 25);
ergebnis.setText("");
ergebnis.setEditable(false);
background.add(ergebnis);
// Ende Komponenten
setVisible(true);
setLayout(new BorderLayout());
setSize(455,580);
setVisible(true);
} // end of public prognose
// Anfang Methoden
public static void main(String[] args) {
new prognose();
} // end of main
public void prognosebutton_ActionPerformed(ActionEvent evt) {
// TODO hier Quelltext einfügen
String a;
String b;
a = spendenbetrag.getText();
b = streamzeit.getText();
double d;
double e = Double.parseDouble(a);
double f = Double.parseDouble(b);
d = e*(60/f)*48;
d = ((double)((int)(d*100)))/100;
String g = String.valueOf(d);
ergebnis.setText(g);
} // end of prognosebutton_ActionPerformed
// Ende Methoden
} // end of class prognose

JTextField horizontal scrolling java swing

I have a JTextField inside a JPanel . The user can type text as big as she wants in the textfield , however horizontal scrolling should appear when the text goes beyond the screen of the textfield. At this point if the user backspace the text and shrink the text within the screen of the textfield , the scrolling should disappear. So basically scrolling should appear only when its needed. How to do it ? Help please.
If you don't like the behavior of the JScrollPane + JTextField, you need to use JScrollBar#setModel(BoundedRangeModel) + JTextField#getHorizontalVisibility():
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicScrollBarUI;
public class TextFieldScrollBarTest {
private static final String TEXT = "javascript:(function(){var l=location,m=l.href.match('^(https?://)(.+)(api[^+]+|technotes[^+]+)');if(m)l.href=m[1]+'docs.oracle.com/javase/8/docs/'+decodeURIComponent(m[3]).replace(/\\+.*$/,'').replace(/\\[\\]/g,':A').replace(/, |\\(|\\)/g,'-');}());";
public JComponent makeUI() {
JScrollPane scroll = new JScrollPane(new JTextField(TEXT));
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
JTextField textField = new JTextField(TEXT);
JScrollBar scroller = new JScrollBar(Adjustable.HORIZONTAL) {
#Override public void updateUI() {
//super.updateUI();
setUI(new ArrowButtonlessScrollBarUI());
}
#Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.height = 5;
return d;
}
};
scroller.setModel(textField.getHorizontalVisibility());
Box box = Box.createVerticalBox();
box.add(scroll);
box.add(Box.createVerticalStrut(50));
box.add(textField);
box.add(Box.createVerticalStrut(2));
box.add(scroller);
box.add(Box.createVerticalGlue());
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
p.add(box, BorderLayout.NORTH);
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TextFieldScrollBarTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class ZeroSizeButton extends JButton {
private static final Dimension ZERO_SIZE = new Dimension();
#Override public Dimension getPreferredSize() {
return ZERO_SIZE;
}
}
class ArrowButtonlessScrollBarUI extends BasicScrollBarUI {
private static final Color DEFAULT_COLOR = new Color(220, 100, 100);
private static final Color DRAGGING_COLOR = new Color(200, 100, 100);
private static final Color ROLLOVER_COLOR = new Color(255, 120, 100);
#Override protected JButton createDecreaseButton(int orientation) {
return new ZeroSizeButton();
}
#Override protected JButton createIncreaseButton(int orientation) {
return new ZeroSizeButton();
}
#Override protected void paintTrack(Graphics g, JComponent c, Rectangle r) {
//Graphics2D g2 = (Graphics2D) g.create();
//g2.setPaint(new Color(100, 100, 100));
//g2.fillRect(r.x, r.y, r.width - 1, r.height - 1);
//g2.dispose();
}
#Override protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
JScrollBar sb = (JScrollBar) c;
if (!sb.isEnabled()) {
return;
}
BoundedRangeModel m = sb.getModel();
int iv = m.getMaximum() - m.getMinimum() - m.getExtent() - 1; // -1: bug?
if (iv > 0) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color color;
if (isDragging) {
color = DRAGGING_COLOR;
} else if (isThumbRollover()) {
color = ROLLOVER_COLOR;
} else {
color = DEFAULT_COLOR;
}
g2.setPaint(color);
g2.fillRect(r.x, r.y, r.width - 1, r.height - 1);
g2.dispose();
}
}
}

Categories

Resources