JFrame - ActionListener - java

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

Related

Java code for closing a desktop application after pressing the x button

i need a little help with introducing a method or something, that will close the desktop application after i press the default X button in the corner. I struggled with a lot of methods i found online, but i either don't know where to put it or i'm missing something...
Here's my code:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class Calculator implements ActionListener {
Frame frame = new Frame();
Label label1 = new Label("First Number");
Label label2 = new Label("Operator");
Label label3 = new Label("Second Number");
Label label4 = new Label("Result");
TextField text1 = new TextField();
Choice choice = new Choice();
TextField text2 = new TextField();
TextField text3 = new TextField();
Button button = new Button("Calculate");
Calculator() {
label1.setBounds(50, 100, 100, 20);
label2.setBounds(50, 140, 100, 20);
label3.setBounds(50, 180, 100, 20);
label4.setBounds(50, 220, 100, 20);
text1.setBounds(200, 100, 100, 20);
choice.setBounds(200, 140, 100, 20);
text2.setBounds(200, 180, 100, 20);
text3.setBounds(200, 220, 100, 20);
button.setBounds(200, 200, 100, 20);
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.add(label4);
frame.add(text1);
frame.add(choice);
frame.add(text2);
frame.add(text3);
frame.add(button);
button.addActionListener(this);
choice.add("+");
choice.add("-");
choice.add("*");
choice.add("/");
frame.setLayout(null);
frame.setVisible(true);
frame.setSize(400, 350);
}
public void actionPerformed(ActionEvent event) {
try {
double number1 = Double.parseDouble(text1.getText());
double number2 = Double.parseDouble(text2.getText());
String selectedOperation = choice.getSelectedItem();
if (selectedOperation.equals("+"))
text3.setText(String.valueOf(number1 + number2));
else if (selectedOperation.equals("-"))
text3.setText(String.valueOf(number1 - number2));
else if (selectedOperation.equals("*"))
text3.setText(String.valueOf(number1 * number2));
else if (selectedOperation.equals("/")) {
if (number2 != 0)
text3.setText(String.valueOf(number1 / number2));
else System.out.println("Can't do that...");
}
} catch (NumberFormatException ignore) {
System.out.println("You can only introduce numbers!");
}
}
}
public class Main {
public static void main(String[] args) {
new Calculator();
}
}
Some help would be very appreciated, as i'm trying to learn Java!
Not quite sure why you are using AWT rather than Swing. As the latter tends to be recommended over the former.
But nevertheless - you can make the application exit by adding a window listener. E.g.:
frame.addWindowListener(new WindowAdapter()
{
#Override public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
As a side note, if you were using Swing rather than AWT (i.e. a JFrame rather than Frame) you can also do :
JFrame jframe = ....;
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
No one uses the AWT GUI anymore. Use Swing, JFrame, JButton, JLabel, JTextField. And then JFrame.setDefaultCloseOperation(EXIT_ON_CLOSE).

JLabel background distorts while using JXDatePicker

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.

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:

The type TextFieldDemo must implement the inherited abstract method ActionListener?

I almost have this code working. I can launch the GUI, however, when I press any of the buttons, I get the following error message:
The type TextFieldDemo must implement the inherited abstract method ActionListener
I have looked around online and can't see any issues with the code. Can someone help me please?
Thanks :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextFieldDemo implements ActionListener{
private JLabel lblName, lblAddress, lblPhone;
private JTextField txtName, txtAddress, txtPhone;
private JButton btnUpper, btnLower, btnExit;
private JPanel panel;
private JFrame frame;
public static void main(String[] args){
new TextFieldDemo();
}
public TextFieldDemo(){
createForm();
addFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Student Form");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void addFields(){
txtName = new JTextField("Fred Bloggs");
txtName.setBounds(110, 50, 150, 20);
panel.add(txtName);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
txtAddress = new JTextField ("Ashley Road");
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
lblPhone = new JLabel ("Phone Number");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
txtPhone= new JTextField("01202 191 3333");
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
lblName = new JLabel("Student Name");
lblName.setBounds(10, 50, 100, 20);
panel.add(lblName);
}
public void addButtons(){
btnUpper = new JButton ("UpperCase");
btnUpper.setBounds(50, 200, 100, 20);
btnUpper.addActionListener(this);
panel.add (btnUpper);
btnLower = new JButton ("LowerCase");
btnLower.setBounds(150, 200, 100, 20);
btnLower.addActionListener(this);
panel.add (btnLower);
btnExit = new JButton ("Exit");
btnExit.setBounds(250, 200, 100, 20);
btnExit.addActionListener(this);
panel.add (btnExit);
}
class UpperCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toUpperCase());
txtAddress.setText(txtAddress.getText().toUpperCase());
}
class LowerCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toLowerCase());
txtAddress.setText(txtAddress.getText().toLowerCase());
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
}
}
You say TextFieldDemo implements ActionListener, but it doesn't have an actionPerformed() method, so it's not actually implementing the interface.
Either implement the method or don't claim it implements the interface.
I didn't think it would compile like you have it, but there you go!
The error should make you check the documentation of ActionListener to find out what method(s) is missing. Sometimes eclipse will prompt you to add stubs for the missing methods.
The documentation shows the interface ActionListener has one method to be implemented, actionPerformed();
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
Strange, the compiler should throw an error on this.

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.

Categories

Resources