Is it possible to split initialize section into different classes? - java

I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}

Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.

Related

when I make a popup menu with JPopupMenu it quits my file explorer page that I made and goes back to the main page(desktop)

I have tried telling it to dispose the file explorer and recreate it works but I cannot seem to get my file image on it now any help in making it not quit in the first place?
here is the code(btw I am on IntelliJ IDEA CE):
package os_pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OS extends JFrame implements ActionListener {
String title = "waliOS";
String message = "please login";
int width = 600;
int height = 400;
JButton b;
JLabel label;
JTextField text;
JLabel c;
JPasswordField pass;
JFrame f;
JFrame f2;
JLabel username;
JLabel password;
JLabel welcomeMain;
JFrame folderFrame;
JFrame textFrame;
JLabel folderLabel;
OS() {
f = new JFrame(title);
f.setSize(width, height);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel(message);
label.setBounds(200, 100, 200, 50);
label.setForeground(Color.WHITE);
text = new JTextField();
text.setBounds(200, 150, 200, 30);
b = new JButton("login");
b.setBounds(200, 250, 200, 50);
b.addActionListener(this);
pass = new JPasswordField();
pass.setBounds(200, 200, 200, 30);
c = new JLabel();
c.setBounds(200, 300, 200, 50);
c.setForeground(Color.WHITE);
username = new JLabel("username");
username.setBounds(130, 140, 200, 50);
username.setForeground(Color.WHITE);
password = new JLabel("password");
password.setBounds(130, 190, 200, 50);
password.setForeground(Color.WHITE);
f.add(password);
f.add(username);
f.add(c);
f.add(pass);
f.add(b);
f.add(label);
f.add(text);
f.setLayout(null);
f.setVisible(true);
f.setResizable(false);
f.getContentPane().setBackground(Color.BLACK);
}
public void mainPage(){
f.dispose();
f2 = new JFrame();
f2.setTitle(title);
f2.setSize(width, height);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setResizable(false);
f2.setLayout(null);
f2.setVisible(true);
f2.setResizable(false);
f2.getContentPane().setBackground(Color.BLACK);
welcomeMain = new JLabel("this is the home page");
welcomeMain.setForeground(Color.WHITE);
welcomeMain.setBounds(200, 100, 200, 50);
f2.add(welcomeMain);
ImageIcon folder = new ImageIcon(getClass().getResource("OS_file.png"));
JLabel folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
folderPage();
}
});
ImageIcon textEdit = new ImageIcon(getClass().getResource("text_edit.png"));
JLabel textImage = new JLabel(textEdit);
textImage.setBounds(200, 200, 80, 80);
textImage.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent em){
textEditPage();
}
});
f2.add(folderLabel);
f2.add(textImage);
}
public void folderPage() {
f2.dispose();
folderFrame = new JFrame(title + " folder");
folderFrame.setSize(width, height);
folderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
folderFrame.setLocationRelativeTo(null);
folderFrame.setResizable(false);
folderFrame.setLayout(null);
folderFrame.setVisible(true);
folderFrame.getContentPane().setBackground(Color.BLACK);
JLabel test = new JLabel("this is the folder page");
test.setForeground(Color.WHITE);
test.setBounds(300, 200, 200, 50);
JButton back = new JButton("back");
back.setBounds(10, 10, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
folderFrame.dispose();
}
});
JPopupMenu menu = new JPopupMenu();
JMenuItem newFolder = new JMenuItem("new Folder");
newFolder.addActionListener(this);
newFolder.setActionCommand("NF");
menu.add(newFolder);
folderFrame.addMouseListener((new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
menu.show(folderFrame, e.getX(), e.getY());
}
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}));
ImageIcon folder = new ImageIcon("folder.png");
folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderFrame.add(test);
folderFrame.add(back);
}
public void textEditPage() {
f2.dispose();
textFrame = new JFrame(title + " text editor");
textFrame.setResizable(false);
textFrame.setLayout(null);
textFrame.setSize(width, height);
textFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textFrame.setVisible(true);
textFrame.setLocationRelativeTo(null);
textFrame.getContentPane().setBackground(Color.BLACK);
JTextArea textArea = new JTextArea();
Font font = new Font(
Font.MONOSPACED,
Font.PLAIN,
textArea.getFont().getSize());
textArea.setFont(font);
textArea.setBounds(1, 30, 599, 399);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JLabel title = new JLabel("Text Editor");
title.setBounds(250, 2, 100, 30);
title.setForeground(Color.WHITE);
JButton back = new JButton("back");
back.setBounds(10, 4, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
textFrame.dispose();
}
});
textFrame.add(back);
textFrame.add(title);
textFrame.add(textArea);
}
public static void main(String[] args){
new OS();
}
#Override
public void actionPerformed(ActionEvent e) {
String user = text.getText();
String pass1 = pass.getText();
if (user.trim().equals("wali") && pass1.trim().equals("haider")) {
c.setText("welcome wali");
mainPage();
} else if(user.trim().equals("admin") && pass1.trim().equals("admin")) {
c.setText("welcome admin");
mainPage();
} else {
c.setText("wrong user");
}
String command = e.getActionCommand();
switch (command) {
case "NF":
System.out.println("done");
folderPage();
folderFrame.dispose();
System.out.print("hello");
folderFrame.add(folderLabel);
}
}
}
can I please get some help on this because I am really stuck if you have questions tell me in the comments that will be very helpful

Clicking on JButton(Bubble Sort) clears the JTextField.Why?

public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.

How to use a text area?

I m creating a GUI in java and would like to use a JTextArea, however I am having a lot of trouble adding it to the frame. How would I go about creating a text Area and then using it to read text or display text?
Here is my GUI code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addMemoUI extends JFrame {
JFrame frame = new JFrame();
/**
* Create the application.
*/
public addMemoUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JButton button = new JButton("Create");
button.setBackground(new Color(100, 149, 237));
button.setBounds(135, 350, 130, 50);
frame.getContentPane().add(button);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(22, 21, 234, 37);
frame.getContentPane().add(lblMemos);
JButton button_1 = new JButton("Cancel");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(5, 350, 130, 50);
frame.getContentPane().add(button_1);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemoUI window = new MemoUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thanks very much :)
Here is example for how to use JTextArea. You can set, get or append text. You can find the others by google.
public class Example {
private JTextArea jtextbox;
private void initialize() {
JFrame frm = new JFrame();
:
JScrollPane scroll = new JScrollPane();
jtextbox= new JTextArea();
scroll.setViewportView(jtextbox); // add scroll panel
jtextbox.setTabSize(4);
jtextbox.setLineWrap(true);
jtextbox.setBackground(SystemColor.window);
}
private void setText(String text) {
jtextbox.append(text); // or setText(text)
}
private String getText() {
return jtextbox.getText();
}
}

How to stop repaint() flickering

I am trying to make a program to java and i have the common problem with flickering. I have try many things to eliminate but all the same. while the oval that i paint is moving the japplet is flickering. i need your help to solve this problem. here is my code:
import java.awt.Color;
public class all extends JApplet implements Runnable {
double x=0;
double y=0;
int m=0;
int n=0;
int f=30;
int μ=0;
Thread kinisi;
JPanel panel;
JFrame frame;
private boolean running = false;
private JTextField textField1;
private JTextField textField2;
Image backGround;
JPanel panel_3;
Image bf = createImage(m, n);
private Graphics doubleg;
private Image i;
public void init() {
this.setSize(800, 700);
}
public all() {
getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Start");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String b=textField2.getText();
String z =textField1.getText();
if (textField1.getText().equals("") ||
textField2.getText().equals("")){
JOptionPane.showMessageDialog(
new JFrame(),
"Δωστε τιμή για το φ και το μ!",
"ERROR",JOptionPane.ERROR_MESSAGE);
} else{
f = Integer.parseInt(b);
μ = Integer.parseInt(z);
Start(); }
}
});
btnNewButton.setBounds(469, 168, 89, 23);
getContentPane().add(btnNewButton);
JButton btnStop = new JButton("Pause");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pause();
}
});
btnStop.setBounds(588, 168, 89, 23);
getContentPane().add(btnStop);
JButton btnReset = new JButton("Reset");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Reset();
}
});
btnReset.setBounds(701, 168, 89, 23);
getContentPane().add(btnReset);
JLabel label = new JLabel("\u03BC");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(549, 63, 46, 14);
getContentPane().add(label);
textField1 = new JTextField();
textField1.setBounds(529, 101, 86, 20);
getContentPane().add(textField1);
textField1.setColumns(10);
JLabel label_1 = new JLabel("\u03C6");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setBounds(681, 63, 46, 14);
getContentPane().add(label_1);
textField2 = new JTextField();
textField2.setBounds(667, 101, 86, 20);
getContentPane().add(textField2);
textField2.setColumns(10);
JButton btnNewButton_1 = new JButton("");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(
new JFrame(),
"Οδηγίες προγράμματος","Οδηγίες",
JOptionPane.INFORMATION_MESSAGE);
}
});
btnNewButton_1.setIcon(
new ImageIcon(all.class.getResource("/Images/info.png")));
btnNewButton_1.setBounds(732, 5, 39, 35);
getContentPane().add(btnNewButton_1);
JLabel label_2 = new JLabel("");
label_2.setIcon(
new ImageIcon(all.class.getResource("/Images/earth.jpg")));
label_2.setBounds(-20, 0, 820, 361);
getContentPane().add(label_2);
JPanel panel_1 = new JPanel();
panel_1.setBorder(
new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_1.setBounds(10, 372, 369, 290);
getContentPane().add(panel_1);
JPanel panel_2 = new JPanel();
panel_2.setBorder(
new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_2.setBounds(408, 372, 369, 290);
getContentPane().add(panel_2);
}
public void paint(Graphics g){
super.paint(g);
g.drawLine(0,f,350,200);
g.drawLine(0,200,350,200);
g.drawOval(m,n,40,40);
Color brown=new Color(137,66,0);
g.setColor(brown);
g.fillOval(m, n, 40, 40);
//Graphics2D g2d = (Graphics2D) g;
g.drawLine(460,400,460,650);
g.drawLine(20, 620, 350, 620);
g.drawLine(50,400,50,650);
g.drawLine(430, 620, 760, 620);
}
public void Start() {
kinisi = new Thread(this);
kinisi.start();
running = true;
}
public void run() {
while (running) {
if (x < 340){
double l = 200-f;
double k = l/350;
double y=k*x+f-30;
x= x+1;
m = (int) x;
n = (int) y;
repaint();
try {
Thread.sleep(μ);
} catch (InterruptedException ie) {}
}
}
}
public void update(Graphics g) {
if(i==null){
i=createImage(800,700);
doubleg = i.getGraphics();
}
doubleg.setColor(getBackground());
doubleg.fillRect(0,0,800,700);
doubleg.setColor(getForeground());
paint(doubleg);
g.drawImage(i,0,0,this);
}
public void paint1(Graphics g){
g.drawLine(0, f ,350, 200);
g.drawOval(m, n, 40, 40);
Color brown=new Color(137,66,0);
g.setColor(brown);
g.fillOval(m, n, 40, 40);
}
public void pause() {
if (kinisi != null) {
running = false;
}
}
public boolean Reset() {
if (kinisi != null) {
running = false;
kinisi.interrupt();
kinisi = null;
x=0;
y=0;
f=30;
m=0;
n=0;
repaint();
textField1.setText("");
textField2.setText("");
}
Graphics g = getGraphics();
g.drawOval(m,n,40,40);
Color brown=new Color(137,66,0);
g.setColor(brown);
g.fillOval(m, n, 40, 40);
return false;
}
public static void main(String[] args) {
JFrame frame = new JFrame("FISIKI");
frame.getContentPane().add(new all());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 700);
frame.setVisible(true);
frame.setResizable(false);
}
}
Thank you very much and sorry for my english are not very good!
There are a number of things that jump out at me.
You're extending from JApplet, but are adding it to a JFrame
You're mixing components with you custom painting
Not using layout managers.
Using getGraphics.
Firstly...
You should never override paint of a top level container (like JApplet). There are many reasons and you've found one. Top level containers are not double buffered. Instead, you should be creating a custom component (by extending something like JPanel) and overriding it's paintComponent method...
Secondly
Decided how you application is going to be. Is it an applet or application? If you follow the first point, then it really doesn't matter, as you only simply need to add the panel to the top level container.
Thirdly
I would create a panel that did the custom painting. Then I would create separate containers for all the fields and other parts of the application. This will allow you to separate the areas of responsibility. It would also allow you to use layout managers ;)
Fourthly
Use layout managers. The layout manager API has being designed to solve one of this most annoying aspects of GUI design, you're asking for a lot of trouble and work you decided to discard it - IMHO.
Fifthly
getGraphics should never be used. Apart from the fact that it can return null, it is only a snap shot of what is currently on the screen. As soon as the RepaintManager decides to perform a repaint, anything rendered to it will be lost. You should use paintComponent to update the state of your custom pane.

Java, runing "textArea = new JTextArea()" taking too much time

Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}

Categories