JLabel background distorts while using JXDatePicker - java

As soon as I click on JXDatePicker (named j in my program code), the JLabel (named l1 in my program code) background to which it is added gets distorted. I also tried to repaint l1 whenever mouse is clicked, but, it doesn't work. Any help will be appreciated.
Program Code :
import java.util.HashMap;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.TextAttribute;
import javax.swing.border.*;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.prompt.PromptSupport;
import javax.swing.*;
public class Registration
{
JFrame stu_reg;
JLabel back, logo, header, l1, l2, l3;
JButton sub, cls;
JTextField t1, t2;
JFormattedTextField ft1;
Connection c;
Registration()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ex)
{
ex.printStackTrace();
}
stu_reg = new JFrame("Student Registration Form");
stu_reg.setSize(1366,740);
stu_reg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stu_reg.setLayout(null);
stu_reg.setVisible(true);
stu_reg.setResizable(false);
header = new JLabel("XYZ");
header.setForeground(Color.RED);
HashMap<TextAttribute, Object> attribute = new HashMap<TextAttribute, Object>();
attribute.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
header.setFont(new Font("A.C.M.E. Secret Agent",Font.BOLD,30).deriveFont(attribute));
header.setBounds(350, 0, 800, 75);
stu_reg.add(header);
ImageIcon image1 = new ImageIcon(Registration.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "xyz.jpg");
back = new JLabel(new ImageIcon(image1.getImage().getScaledInstance(1366, 730, Image.SCALE_SMOOTH)));
back.setBounds(0, 0, 1366, 730);
stu_reg.add(back);
ImageIcon image = new ImageIcon(Registration.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "R2.gif");
logo = new JLabel(new ImageIcon(image.getImage().getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
logo.setBounds(1100, 0, 200, 200);
back.add(logo);
l1 = new JLabel();
l1.setBackground(new Color(100, 100, 100, 70));
l1.setOpaque(true);
l1.setBounds(150, 80, 420, 590);
LineBorder line = new LineBorder(Color.blue, 2, true);
Font f = new Font("Scramble",Font.PLAIN,25).deriveFont(attribute);
TitledBorder title = new TitledBorder(line, "Register", TitledBorder.LEFT, TitledBorder.TOP, f, new Color(225,80,0));
l1.setBorder(title);
back.add(l1);
l2 = new JLabel("FULL NAME");
l2.setFont(new Font("",Font.BOLD,14));
l2.setBounds(27, 50, 100, 35);
l1.add(l2);
t1 = new JTextField(100);
t1.setBounds(25, 80, 175, 35);
PromptSupport.setPrompt("First Name", t1);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, t1);
l1.add(t1);
t2 = new JTextField(100);
t2.setBounds(220, 80, 175, 35);
PromptSupport.setPrompt("Last Name", t2);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, t2);
l1.add(t2);
l3 = new JLabel("DATE OF BIRTH");
l3.setFont(new Font("",Font.BOLD,14));
l3.setBounds(27, 130, 175, 35);
l1.add(l3);
JXDatePicker j=new JXDatePicker();
j.setBounds(25, 160, 175, 33);
j.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
l1.repaint();
}
});
l1.add(j);
ToolTipManager.sharedInstance().setEnabled(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater( ()->new Registration() );
}
}
Without Distortion
After Distortion

l1.setBackground(new Color(100, 100, 100, 70));
Swing doesn't support backgrounds with transparency properly. If a component is opaque then Swing expects the background to be opaque, not transparent.
If you want a transparent background then you need to do custom painting.
Check out Backgrounds With Transparency for more information and solutions.

First try setting the background color like so:
l1.setBackground(new Color(100, 100, 100, 255));
l1.setOpaque(false);
Give it a test, does that work now?
If it doesnt work then also remove the following UIManager line at the start of your code UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); and then give it a test again. Often some look&feel's will not allow you to use transparency correctly.
If it works now, then you know that you will either need to abandon the look and feel, or keep it and use custom painting as camickr suggested.

Related

How to add an image at specific location in JFrame in Java using eclipse?

I have made a student information page using GUI concept. I want to know that how can i add an image at a specific location using JLabel or any other method? What i want is a background image surrounding the whole Jframe and another image at specific location like at the top right. How can i achieve this?
i also found a code to add image using Jlabel but it doesn't work with my code as my setting the layout to null.
the code i found
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
Below is my code:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class LoginPage
{
JFrame jf;
JLabel gender,hobbies,name_label,rollno_label,marks_label,city_label,address_label;
JTextField name_field,rollno_field,marks_field;
JRadioButton male,female;
ButtonGroup bg;
JCheckBox photography,music,sketching,coding;
JComboBox city_combo;
JTextArea adress_textarea;
JButton save, exit;
JMenuBar mbar;
JMenu file,edit,help;
JMenuItem open,save_item,edit_item,close,cut,copy,paste,find,replace,help_content,about,updates;
public LoginPage() //constructor
{
jf = new JFrame("Student Information");
name_label = new JLabel("Student's Name");
name_field = new JTextField();
rollno_label = new JLabel("Student's Roll Number");
rollno_field = new JTextField();
marks_label = new JLabel("Student's Total Marks Achieved");
marks_field = new JTextField();
gender = new JLabel("Gender");
male = new JRadioButton("Male");
female = new JRadioButton("Female");
bg = new ButtonGroup();
hobbies = new JLabel("Hobbies");
photography = new JCheckBox("Photography");
music = new JCheckBox("Music");
coding = new JCheckBox("Coding");
sketching = new JCheckBox("Sketching");
city_label = new JLabel("City");
city_combo = new JComboBox();
address_label = new JLabel("Residential Address");
adress_textarea = new JTextArea();
save = new JButton("Save");
exit = new JButton("Exit");
mbar = new JMenuBar();
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");
open = new JMenuItem("open");
save_item = new JMenuItem("Save");
edit_item = new JMenuItem("Edit");
close = new JMenuItem("Close");
cut = new JMenuItem("Cut");
copy = new JMenuItem("Copy");
paste = new JMenuItem("Paste");
find = new JMenuItem("Find");
replace = new JMenuItem("Replace");
about = new JMenuItem("About");
updates = new JMenuItem("Check for Updates");
help_content = new JMenuItem("Help Content");
}
void Display()
{
jf.setSize(1000, 700);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.getContentPane().setBackground( Color.LIGHT_GRAY );
name_label.setBounds(50, 50, 150, 20);
name_field.setBounds(300, 50, 200, 20);
rollno_label.setBounds(50, 100, 150, 20);
rollno_field.setBounds(300, 100, 200, 20);
marks_label.setBounds(50, 150, 200, 20);
marks_field.setBounds(300, 150, 200, 20);
gender.setBounds(50, 200, 100, 20);
male.setBounds(300, 200, 80, 20);
female.setBounds(400, 200, 80, 20);
hobbies.setBounds(50, 250, 80, 20);
photography.setBounds(300, 250, 100, 20);
music.setBounds(420, 250, 80, 20);
sketching.setBounds(500, 250, 100, 20);
coding.setBounds(600, 250, 80, 20);
city_label.setBounds(50, 300, 100, 20);
city_combo.setBounds(300, 300, 100, 20);
address_label.setBounds(50, 350, 200, 20);
adress_textarea.setBounds(300, 350, 300, 100);
save.setBounds(300, 500, 100, 50);
exit.setBounds(600, 500, 100, 50);
bg.add(male);
bg.add(female);
city_combo.addItem("Select City");
city_combo.addItem("Chandigarh");
city_combo.addItem("Kurali");
city_combo.addItem("Mohali");
city_combo.addItem("Panchkula");
file.add(open);
file.add(save_item);
file.add(edit_item);
file.add(close);
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(find);
edit.add(replace);
help.add(about);
help.add(help_content);
help.add(updates);
mbar.add(file);
mbar.add(edit);
mbar.add(help);
jf.add(name_label);
jf.add(name_field);
jf.add(rollno_label);
jf.add(rollno_field);
jf.add(marks_label);
jf.add(marks_field);
jf.add(gender);
jf.add(male);
jf.add(female);
jf.add(hobbies);
jf.add(music);
jf.add(photography);
jf.add(sketching);
jf.add(coding);
jf.add(city_label);
jf.add(city_combo);
jf.add(address_label);
jf.add(adress_textarea);
jf.add(save);
jf.add(exit);
jf.setJMenuBar(mbar);
jf.setVisible(true);
}
public static void main(String[] args) {
new LoginPage().Display();
}
}
What i want is a background image surrounding the whole Jframe
Suggestions:
Create a class that extends JPanel,
override its paintComponent method
be sure to call the super's paintComponent method in your override
Draw your background image within this method using g.drawImage(...)
Either make this JPanel your JFrame's contentPane or add it to the contentPane BorderLayout.CENTER, and then add your GUI components to this JPanel
Make sure that some of the components are not-opaque, e.g., call setOpaque(false) on your JRadioButtons, and perhaps others, so that the background image shows up.
and another image at specific location like at the top right. How can i achieve this?
Use the same JPanel above, and draw the smaller image using an overload of drawImage(...) that precisely places the image where you want
Notes:
When I create background images for the GUI, I prefer to draw within a JPanel rather than a JLabel since the JLabel is not wired out of the box to act as a contentPane or a decent container.
I strongly advise you not to use null layouts and setBounds as this will lead to gui's that might look good on one platform, but not on another, that have JLabels whose text is not fully seen, that are very difficult to upgrade and maintain. Learn and use the layout managers.
Looks like you're using multiple JFrames. If so, please read: The Use of Multiple JFrames: Good or Bad Practice?
For example, here's one way to display an image as a background image as well as a smaller image in the right upper portion of the GUI, all within a JPanel:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class LoginPage3 extends JPanel {
public static final String BG_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
+ "commons/e/e9/Maesil_%28prunus_mume%29_washed_and_stemmed.jpg";
public static final String RU_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/5/5b/Escudo_de_San_Pedro_de_Atacama.svg/200px-Escudo_de_San_Pedro_de_Atacama.svg.png";
private BufferedImage backgroundImg;
private BufferedImage rightUpperImg;
public LoginPage3(BufferedImage bgImg, BufferedImage ruImg) {
this.backgroundImg = bgImg;
this.rightUpperImg = ruImg;
}
#Override
public Dimension getPreferredSize() {
if (backgroundImg == null || isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
int w = backgroundImg.getWidth();
int h = backgroundImg.getHeight();
return new Dimension(w, h);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
if (rightUpperImg != null) {
int x = getWidth() - rightUpperImg.getWidth();
g.drawImage(rightUpperImg, x, 0, this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
BufferedImage bg = null;
BufferedImage ru = null;
try {
bg = ImageIO.read(new URL(BG_IMG_PATH));
ru = ImageIO.read(new URL(RU_IMG_PATH));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
LoginPage3 mainPanel = new LoginPage3(bg, ru);
JFrame frame = new JFrame("LoginPage3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For background image:
Load it as an icon, and create a JLabel with it. (See your first snippet)
Set the JLabel as the JFrame's content pane.
All you have to take care of, that Icon does not stretch, so you have to have an image that is exactly the same size as your JFrame (or larger).
As for the image at a given position, the JLabel creating and Icon loading process is the same, but after adding it to the JFrame you have to set position and size, just like for your other components, EG call setBounds()...

swing - why is this creating two separate boxes

I apologise now if my terminology or turns of phrase aren't right, I'm new to swing. Also, apologise for the clunky and intelligent way I've tried to get this to work.
I am trying to create a single box that has a JTextArea inside it, and next this this area (still in the same box), has some buttons. However, all I've managed to do is make a box with the buttons in, and a separate box with a text area.
I have looked at many examples where people are trying to do similar things and I thought I managed to understand and implement it, but I haven't yet succeeded. If someone could point me at the part(s) of the code I'm misunderstanding I would be very grateful.
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.*;
public class GameGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea(50, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
String action;
private static GUIClient client = new GUIClient();
JButton n = new JButton("N");
JButton e = new JButton("E");
JButton s = new JButton("S");
JButton w = new JButton("W");
JButton look = new JButton("LOOK");
JButton pickup = new JButton("PICKUP");
JButton hello = new JButton("HELLO");
JButton quit = new JButton("QUIT");
public GameGUI()
{
textArea.setEditable(false);
panel.add(new JScrollPane(textArea));
this.setBounds(300, 300, 750, 500);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
n.setBounds(225, 25, 50, 50);
e.setBounds(300, 100, 50, 50);
s.setBounds(225, 175, 50, 50);
w.setBounds(150, 100, 50, 50);
look.setBounds(50, 362, 100, 50);
pickup.setBounds(200, 362, 100, 50);
hello.setBounds(350, 362, 100, 50);
quit.setBounds(500, 362, 100, 50);
this.add(n);
this.add(e);
this.add(s);
this.add(w);
this.add(look);
this.add(pickup);
this.add(hello);
this.add(quit);
n.addActionListener(this);
e.addActionListener(this);
s.addActionListener(this);
w.addActionListener(this);
look.addActionListener(this);
pickup.addActionListener(this);
hello.addActionListener(this);
quit.addActionListener(this);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public void displayInGUI(String fromServer)
{
textArea.append(fromServer);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
public void actionPerformed(ActionEvent f)
{
if(f.getSource()==n)
{
action = "MOVE N";
client.display(action);
}
else if(f.getSource()==e)
{
action = "MOVE E";
client.display(action);
}
else if(f.getSource()==s)
{
action = "MOVE S";
client.display(action);
}
else if(f.getSource()==w)
{
action = "MOVE W";
client.display(action);
}
else if(f.getSource()==look)
{
action = "LOOK";
client.display(action);
}
else if(f.getSource()==pickup)
{
action = "PICKUP";
client.display(action);
}
else if(f.getSource()==hello)
{
action = "HELLO";
client.display(action);
}
else if(f.getSource()==quit)
{
action = "QUIT";
client.display(action);
}
}
}
I've used this class by creating an instance of it in GUIClient (I've also created an instance of GUIClient in this class, GameGUI, which seems really ugly but it was the only way I could think to notice when the buttons were pressed).
So, if I want to run the game, I set up the server, then run GUIClient, which creates the two boxes. GUIGame then notices when the buttons are pressed and sends this info to the client which sends it to the server.
Again, I'm sorry this is so convoluted. I hope my explanation helped clear things up but if not just let me know.
Many thanks,
Elise.
I added a 'main()' method (and commented out the client parts) so I could run your program. I also set the Frame's size to 800x500 so it is visible. This is what I see:
The reason the text area is not visible is you did not add it to the frame. You will need to add the panel that contains the scrollpane that contains the textarea to the frame. You will also need to position and size it. For example:
panel.setBounds(400, 25, 200, 200);
this.add(panel);
This produces the following:

Repaint only a specific JPanel inside a JFrame

I am trying to create a paint component for the panel_1 JPanel, but I don't know how to do it. This is my class.
This code works, except that it does not paint the panel_1.
If I try and add it to the panel without painting it, it works just fine.
Also I need that panel to refresh (repaints) automatically at a given interval.
Please let help me. :D
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class GUI extends JFrame implements ActionListener {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JButton btnStop, btnStart;
private JComboBox comboBox_1, comboBox;
private Manager manager = new Manager();
private String arrMin, arrMax, svcMin, svcMax, simTime;
private JTextField textField_4;
private JPanel panel_1 = new JPanel(){
#Override
public void paintComponent(Graphics g){
paintComponents(g);
panel_1.setBackground(Color.orange);
panel_1.setVisible(true);
System.out.println("Just testing");
}
};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
setResizable(false);
setForeground(Color.DARK_GRAY);
setBackground(Color.DARK_GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 500);
contentPane = new JPanel();
contentPane.setForeground(Color.DARK_GRAY);
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(12, 12, 434, 346);
panel.setForeground(Color.LIGHT_GRAY);
contentPane.add(panel);
panel.setLayout(null);
JLabel lblArrivingTime = new JLabel("Arriving time");
lblArrivingTime.setBounds(12, 367, 94, 15);
lblArrivingTime.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblArrivingTime);
JLabel lblMin = new JLabel("Min");
lblMin.setBounds(12, 395, 70, 15);
lblMin.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMin);
JLabel lblMax = new JLabel("Max");
lblMax.setBounds(12, 418, 70, 15);
lblMax.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMax);
textField = new JTextField();
textField.setBounds(58, 394, 48, 16);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(58, 422, 48, 15);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblServiceTime = new JLabel("Service Time");
lblServiceTime.setBounds(152, 367, 105, 15);
lblServiceTime.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblServiceTime);
JLabel lblMin_1 = new JLabel("Min");
lblMin_1.setBounds(152, 395, 51, 15);
lblMin_1.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMin_1);
JLabel lblMax_1 = new JLabel("Max");
lblMax_1.setBounds(152, 418, 70, 15);
lblMax_1.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMax_1);
textField_2 = new JTextField();
textField_2.setBounds(209, 393, 48, 17);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(209, 417, 48, 17);
contentPane.add(textField_3);
textField_3.setColumns(10);
JLabel lblSimSetup = new JLabel("Sim. Setup");
lblSimSetup.setBounds(292, 367, 94, 15);
lblSimSetup.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblSimSetup);
JLabel lblQueue = new JLabel("Queue");
lblQueue.setBounds(292, 395, 70, 15);
lblQueue.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblQueue);
String[] numbers = { "1", "2", "3", "4" };
comboBox = new JComboBox(numbers);
comboBox.setBounds(345, 395, 75, 15);
contentPane.add(comboBox);
JLabel lblMode = new JLabel("Mode");
lblMode.setBounds(292, 418, 70, 15);
lblMode.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMode);
String[] mode = { "Time", "Number" };
comboBox_1 = new JComboBox(mode);
comboBox_1.setBounds(345, 413, 75, 15);
contentPane.add(comboBox_1);
JLabel lblActions = new JLabel("Actions");
lblActions.setBounds(484, 367, 70, 15);
lblActions.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblActions);
btnStart = new JButton("Start");
btnStart.setBounds(482, 392, 81, 20);
contentPane.add(btnStart);
btnStop = new JButton("Stop");
btnStop.setBounds(482, 415, 81, 20);
contentPane.add(btnStop);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(292, 440, 70, 15);
lblTime.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblTime);
textField_4 = new JTextField();
textField_4.setBounds(345, 438, 75, 17);
contentPane.add(textField_4);
textField_4.setColumns(10);
panel_1.setBounds(484, 12, 202, 346);
contentPane.add(panel_1);
panel_1.setLayout(null);
JTextArea textArea = new JTextArea();
textArea.setBounds(158, 12, -126, 322);
panel_1.add(textArea);
btnStop.addActionListener(this);
btnStart.addActionListener(this);
comboBox.addActionListener(this);
comboBox_1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStop) {
this.dispose();
System.exit(NORMAL);
} else if (e.getSource() == btnStart) {
String nrQueues = (String) comboBox.getSelectedItem();
arrMin = textField.getText();
arrMax = textField_1.getText();
svcMin = textField_2.getText();
svcMax = textField_3.getText();
simTime = textField_4.getText();
int aMin = 0;
int aMax = 0;
int sMin = 0;
int sMax = 0;
int sTime = 0;
int nQueues = 1;
try {
nQueues = Integer.parseInt(nrQueues);
aMin = Integer.parseInt(arrMin);
aMax = Integer.parseInt(arrMax);
sMin = Integer.parseInt(svcMin);
sMax = Integer.parseInt(svcMax);
sTime = Integer.parseInt(simTime);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s = (String) comboBox_1.getSelectedItem();
System.out.println("Selected: " + s);
boolean mode = true;
if (s.equals("Time")) {
mode = true;
} else {
mode = false;
}
manager.startSimulation(aMin * 1000, aMax * 1000, sMin * 1000,
sMax * 1000, sTime * 1000, nQueues, mode);
}
}
}
Of course the handler is not relevant in this case since I am only interested in painting that panel.
First of all, this...
private JPanel panel_1 = new JPanel(){
#Override
public void paintComponent(Graphics g){
paintComponents(g);
panel_1.setBackground(Color.orange);
panel_1.setVisible(true);
System.out.println("Just testing");
}
};
Is not what custom painting is for. You should NEVER change the state of the component, or any component for that matter, from inside any paint method.
This could trigger a new repaint request which would put you into a never ending cycle of painting...
Calling paintComponents(g); is going to produce a StackOverflowException. You should not be calling paintComponents any way (note the s at the end) but you should be calling super.paintComponent(g);
JPanel is visible by default.
As it stands, you simply don't need to do anything that you are...
Don't use null layouts. Swing was designed to work with layout managers, you will have no end of issues getting the screen to update without them, besides, pixel perfect layouts are an illusion in modern user interface design, you don't control the fonts, rendering pipelines or other aspects of the target system that might effect how large elements like text are rendered.
Take a look at Laying Out Components Within a Container for more details
You're calling the super.paintComponents method inside of your paintComponent override. Yikes. You are also using null layout and shouldn't be.
You are setting background color but doing nothing with it. You should instead set the background color on your JPanel object, not in its paintComponent method.
i.e., here
panel_1.setBackground(Color.orange); // here
// !! panel_1.setBounds(484, 12, 202, 346); // you shouldn't need this!
contentPane.add(panel_1);
Edit
You state:
Is it enough to simply append a string to the text area, and it will be displayed on the screen automatically?
Yes, as long as you take Swing thread rules into consideration.

JFrame - ActionListener

I'm working on building a program that uses JFrame. What I want for my end result, is to implement an ActionListener which will remove labels when the user clicks a button. For example: when the user clicks the JButton, one of 5 labels is removed from the frame. When they click the button again, one of the remaining 4 labels is removed...and so on a so forth, until 0 labels remain. Technically, I have the program working as required however, I'm trying to see if there is a way to implement the ActionListener event via a loop as opposed to listing an if statement for each individual label. Thank you so much!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//calls for public class to inherit features of JFrame within Java
public class NoPurchaseReason extends JFrame implements ActionListener {
private int removeText = 0;
JButton btn = new JButton("Select");
JLabel lbl = new JLabel("Found better price");
JLabel lbl1 = new JLabel("Not as shown on website");
JLabel lbl2 = new JLabel("Wrong product");
JLabel lbl3 = new JLabel("Damaged upon delivery");
JLabel lbl4 = new JLabel("None of the above");
public static void main(String[] args) {
JFrame f = new NoPurchaseReason("Please tell us why you wish to return your purchase.");
f.setBounds(300, 100, 500, 500);
f.setVisible(true);
f.setBackground(Color.blue);
}
public NoPurchaseReason(String title) {
super(title);
setLayout(null);
lbl.setBounds(40, 40, 600, 40);
btn.setBounds(320, 10, 80, 20);
lbl.setBounds(100, 40, 100, 20);
lbl1.setBounds(100, 70, 100, 20);
lbl2.setBounds(100, 100, 150, 20);
lbl3.setBounds(100, 130, 100, 20);
lbl4.setBounds(100, 160, 100, 20);
add(btn);
add(lbl);
add(lbl);
add(lbl1);
add(lbl2);
add(lbl3);
add(lbl4);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
removeText++;
if (removeText == 1) {
lbl.setVisible(false);
lbl1.setBounds(100, 40, 100, 20);
lbl2.setBounds(100, 70, 100, 20);
lbl3.setBounds(100, 100, 150, 20);
lbl4.setBounds(100, 130, 100, 20);
}
if (removeText == 2) {
lbl1.setVisible(false);
lbl2.setBounds(100, 40, 100, 20);
lbl3.setBounds(100, 70, 150, 20);
lbl4.setBounds(100, 100, 100, 20);
}
if (removeText == 3) {
lbl2.setVisible(false);
lbl3.setBounds(100, 40, 150, 20);
lbl4.setBounds(100, 70, 100, 20);
}
if (removeText == 4) {
lbl3.setVisible(false);
lbl4.setBounds(100, 40, 100, 20);
}
if (removeText == 5) {
lbl4.setVisible(false);
}
}
}
Learning how to properly use layout managers will save you a lot of trouble in the long run.
You'll also find that people will tell you to adhere to the single responsibility principle, and avoid making classes that violate this principle (e.g., extending JFrame and implementing ActionListener).
You'll also hear folks tell you to prefer using actions over action listeners (if you need to share functionality across multiple components, that is).
A simple way would be to dedicate an entire panel to holding your labels, and simply remove the first label in the panel until there are no more labels. Here's an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class LabelDemo
{
public static void main(String[] args) {
String[] labels = {
"Found better price",
"Not as shown on website",
"Wrong product",
"Damaged upon delivery",
"None of the above"
};
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String s: labels) {
panel.add(new JLabel(s));
}
frame.add(panel);
JButton button = new JButton("Select");
button.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
if (panel.getComponentCount() > 0)
panel.remove(0);
frame.repaint();
}
});
frame.add(button, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
}
Also, you may just have a certain goal in mind that I'm not aware of, but it honestly seems like a list would be better in this case. Here's an example of that as well:
String[] labels = {
"Found better price",
"Not as shown on website",
"Wrong product",
"Damaged upon delivery",
"None of the above"
};
JList<String> list = new JList<>(labels);
int option = JOptionPane.showConfirmDialog(null, list,
"Please tell us why you wish to return your purchase.",
JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String selectedValue = list.getSelectedValue();
System.out.println(selectedValue); // Do something with it.
}

.drawLine is not drawing onto JTabbedPane (Java)

Someone told me a way to paint onto a Jframe and it worked fine in the example, but now I have tabs it doesn't paint onto them.
I need the paint/drawLine to work in my Tabbed example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.io.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
public class GUI extends JTabbedPane implements ActionListener
{
static JFrame aWindow = new JFrame("Project");
JTabbedPane myTabs = new JTabbedPane();
JPanel loginMainPanel = new JPanel();
JPanel displayMainPanel = new JPanel();
JPanel editMainPanel = new JPanel();
JTextField myText1 = new JTextField("");
JTextField myText2 = new JTextField("");
JTextField myText3 = new JTextField("");
JLabel loginLabel = new JLabel("Username:");
JTextField loginField = new JTextField();
JLabel loginLabel2 = new JLabel("Password:");
JPasswordField loginPass = new JPasswordField();
JButton displayButton = new JButton("Load Data");
JButton loginButton = new JButton("Login");
JLabel editLabel = new JLabel("Write:");
JTextArea editArea = new JTextArea();
public GUI()
{
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width/3, wndSize.height/3, 250, 250);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(1,1);
Container content = aWindow.getContentPane();
content.setLayout(grid);
createLoginPanel();
createDisplayPanel();
createEditPanel();
myTabs.addTab("Login", loginMainPanel);
myTabs.addTab("Main Menu", displayMainPanel);
myTabs.addTab("Setting", editMainPanel);
myTabs.setSelectedIndex(0);
myTabs.setEnabledAt(1,false);
myTabs.setEnabledAt(2,false);
content.add(myTabs);
aWindow.setVisible(true);
}
public void createLoginPanel()
{
loginMainPanel.setLayout(null);
loginLabel.setBounds(10, 15, 150, 20);
loginMainPanel.add(loginLabel);
loginField.setBounds(10, 35, 150, 20);
loginMainPanel.add(loginField);
loginLabel2.setBounds(10, 60, 150, 20);
loginMainPanel.add(loginLabel2);
loginPass.setBounds(10, 80, 150, 20);
loginMainPanel.add(loginPass);
loginButton.addActionListener(this);
loginButton.setBounds(50, 110, 80, 20);
loginMainPanel.add(loginButton);
}
public void createDisplayPanel()
{
displayMainPanel.setLayout(null);
displayButton.addActionListener(this);
displayButton.setBounds(50, 80, 150, 20);
displayMainPanel.add(displayButton);
myText1.setBounds(50, 170, 200, 30);
myText2.setBounds(50, 140, 200, 30);
myText3.setBounds(50, 110, 200, 30);
displayMainPanel.add(myText1);
displayMainPanel.add(myText2);
displayMainPanel.add(myText3);
}
public void createEditPanel()
{
editMainPanel.setLayout(null);
editLabel.setBounds(10, 15, 150, 20);
editMainPanel.add(editLabel);
editArea.setBounds(10, 65, 150, 50);
editMainPanel.add(editArea);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//myTabs.setSelectedIndex(1);
}
}
public void paint(Graphics g) {
super.paint(g);
int locX = 0;
int locY = 0;
int destX = 210;
int destY = 210;
g.setColor(Color.red);
// draw a line (there is now drawPoint..)
g.drawLine(locX, locY, destX, destY);
}
public static void main(String[] args)
{
GUI tw1 = new GUI();
}
}
How can I find a solution so it will paint that line on the tab (loginMainPanel)?
If you want custom drawing on a JPanel, you should create a custom class that extends JPanel:
class CustomPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
}
}
Then:
JPanel loginMainPanel = new JPanel();
Woudl become:
JPanel loginMainPanel = new CustomPanel();
Sorry for the blurge of bloated code
Yes, well that is why people can't solve problems, because the code is so bloated you can't see what you are doing.
If you want us to help you problem solve then you need to post a SSCCE
Someone told me a way to paint onto a Jframe
Well, that is wrong, in general you should not be overrding the paint() method, unless you have a specific reason.
Also, your whole program is wrong because you are extending JTabbedPane. You should never do this to create a GUI.
Your paint() method is never invoked because you never use that class anywhere. Look at your code. For your class variables you create a new JTabbedPane. Then in the constructor you add all these components to the frame and make the frame visible.
You need to take a look at the Swing tutorial and follow some of the example there for a better way to create a simple GUI.
I don't understand what you are trying to do by drawing a line on the tabbed pane. A tabbed pane displays different panels every time you click on a tab. Where exactly do you want the line to appear?
Also, you should learn how to use layout managers. Using a null layout will cause unnecessary problems.
Until you post a SSCCE, I can't be of much help.

Categories

Resources