Java Swing Game TT [closed] - swing

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am trying to have this quiz like game where user have 3 buttons to choose from. If they chose the wrong answer, an image bomb wil appear and immediately it wil automatically change to the next question and if they chose the corect one, it will also change to the next question. However, my problem here is that i do not know if i wrote my if...else statements correctly. When i run my program, it doesn't change to the next question and there is no bomb image appearing too. I tried many methods to solve this but i stil could'nt. I really need help.
Here is my code and the if... else statements is from line 244 to 388.
public class GamesQuestionPanel extends JPanel{
private static final long serialVersionUID = 1L;
private JLabel jLabelQuestion = null;
private JLabel jLabelScore = null;
private JLabel jLabelHeart1 = null;
private JLabel jLabelHeart2 = null;
private JLabel jLabelHeart3 = null;
private JButton jButtonAnswer1;
private JButton jButtonAnswer2;
private JButton jButtonAnswer3;
private JLabel jLabelDescription1;
private JLabel jLabelDescription2;
private JLabel jLabelDescription3;
private JButton jButtonAdd = null;
private JFrame myFrame = null;
private JLabel jLabelTimer = null;
private Timer t;
private TimerModel tm;
private int qn_num = 0;
private JLabel jLabelScore1 = null;
private JLabel jLabelQn;
private JButton jButtonEdit = null;
private static int answer1;
private int answer2;
private int answer3;
private int count=0;
int Score = 0;
public void Randomise() {
ArrayList<Integer> random = new ArrayList<Integer>();
try{
DBController db = new DBController();
//passing data source name
db.setUp("CFDatabase");
String g_question =" ";
String dbQuery = "SELECT * FROM GameQuestion WHERE g_question ='" + g_question + "'";
//for retrieve SQL use readRequest method
ResultSet rs = db.readRequest(dbQuery);
if (rs.next()){
int g_questionNo =rs.getInt("g_questionNo");
random.add(g_questionNo);
System.out.println(random.get(g_questionNo));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This is the default constructor
*/
public GamesQuestionPanel() {
super();
initialize();
}
public GamesQuestionPanel(JFrame f) {
this();
myFrame = f;
}
public GamesQuestionPanel(JFrame f, String s ){
this();
myFrame = f;
jLabelTimer.setText(s);
}
/**
* This method initialises this
*
* #return void
*/
private void initialize() {
jLabelQn = new JLabel();
jLabelQn.setBounds(new Rectangle(13, 96, 55, 50));
jLabelQn.setFont(new Font("Dialog", Font.BOLD, 18));
jLabelQn.setHorizontalAlignment(SwingConstants.CENTER);
jLabelQn.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelQn.setText("");
jLabelScore1 = new JLabel();
jLabelScore1.setText("");
jLabelScore1.setSize(new Dimension(83, 29));
jLabelScore1.setLocation(new Point(119, 438));
jLabelTimer = new JLabel();
jLabelTimer.setBounds(new Rectangle(17, 23, 199, 53));
jLabelTimer.setText("00:01:00");
jLabelTimer.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelTimer.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/timerbg.png")));
jLabelTimer.setFont(new Font("Dialog", Font.BOLD, 18));
jLabelTimer.setHorizontalAlignment(SwingConstants.CENTER);
t = new Timer(1000, new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e) {
tm.timeTick();
jLabelTimer.setText(tm.getTime());
if(tm.isTimeUp()){
t.stop();
JOptionPane.showMessageDialog(null, "HighScore: " + Score, "GameOver",
JOptionPane.INFORMATION_MESSAGE);
int finalScore = Score ;
String display = Integer.toString(finalScore);
jLabelScore.setText(display);
tm.setTime("00:10:00");
JPanel panel = new ProgrammesEventsPanelEnq(myFrame);
myFrame.getContentPane().removeAll();
myFrame.getContentPane().add(panel);
myFrame.getContentPane().validate();
myFrame.getContentPane().repaint();
}
}
});
tm = new TimerModel();
tm.setTime("00:01:00");
t.start();
jLabelDescription3 = new JLabel();
jLabelDescription3.setFont(new Font("Dialog", Font.BOLD, 20));
jLabelDescription3.setLocation(new Point(483, 385));
jLabelDescription3.setSize(new Dimension(218, 33));
jLabelDescription3.setHorizontalAlignment(SwingConstants.CENTER);
jLabelDescription3.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelDescription3.setForeground(Color.black);
jLabelDescription2 = new JLabel();
jLabelDescription2.setFont(new Font("Dialog", Font.BOLD, 20));
jLabelDescription2.setLocation(new Point(244, 386));
jLabelDescription2.setSize(new Dimension(226, 33));
jLabelDescription2.setHorizontalAlignment(SwingConstants.CENTER);
jLabelDescription2.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelDescription2.setForeground(Color.black);
jLabelDescription1 = new JLabel();
jLabelDescription1.setFont(new Font("Dialog", Font.BOLD, 20));
jLabelDescription1.setBackground(new Color(238, 238, 238));
jLabelDescription1.setLocation(new Point(9, 386));
jLabelDescription1.setSize(new Dimension(225, 33));
jLabelDescription1.setHorizontalAlignment(SwingConstants.CENTER);
jLabelDescription1.setHorizontalTextPosition(SwingConstants.CENTER);
jLabelDescription1.setForeground(Color.black);
jLabelHeart3 = new JLabel();
jLabelHeart3.setBounds(new Rectangle(611, 61, 45, 39));
jLabelHeart3.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/heartshape.png")));
jLabelHeart3.setText("");
jLabelHeart2 = new JLabel();
jLabelHeart2.setBounds(new Rectangle(546, 61, 43, 40));
jLabelHeart2.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/heartshape.png")));
jLabelHeart2.setText("");
jLabelHeart1 = new JLabel();
jLabelHeart1.setBounds(new Rectangle(482, 60, 44, 41));
jLabelHeart1.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/heartshape.png")));
jLabelHeart1.setText("");
jLabelScore = new JLabel();
jLabelScore.setBounds(new Rectangle(25, 438, 83, 29));
jLabelScore.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
jLabelScore.setForeground(Color.black);
jLabelScore.setText(" Score:");
jLabelQuestion = new JLabel();
jLabelQuestion.setBounds(new Rectangle(71, 95, 618, 52));
jLabelQuestion.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
jLabelQuestion.setForeground(Color.black);
this.setSize(712, 500);
this.setLayout(null);
this.setBackground(Color.white);
this.add(jLabelQuestion, null);
this.add(jLabelScore, null);
this.add(jLabelHeart1, null);
this.add(jLabelHeart2, null);
this.add(jLabelHeart3, null);
this.add(getJButtonAnswer1(), null);
this.add(getJButtonAnswer2(), null);
this.add(getJButtonAnswer3(), null);
this.add(jLabelDescription1, null);
this.add(jLabelDescription2, null);
this.add(jLabelDescription3, null);
this.add(getJButtonAdd(), null);
this.add(jLabelTimer, null);
this.add(jLabelScore1, null);
this.add(jLabelQn, null);
this.add(getJButtonEdit(), null);
qn_num = 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
jLabelQn.setText("Q1.");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
/**
* This method initialises jButtonAnswer1
*
* #return javax.swing.JButton
*/
private JButton getJButtonAnswer1() {
if (jButtonAnswer1 == null) {
jButtonAnswer1 = new JButton();
jButtonAnswer1.setBackground(Color.white);
jButtonAnswer1.setSize(new Dimension(228, 214));
jButtonAnswer1.setLocation(new Point(5, 164));
jButtonAnswer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonAnswer1.equals("answer1");
qn_num = qn_num + 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
if((jButtonAnswer1.isSelected()) && (g1.getG_correctAnswer() == answer1))
{
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
//jButtonAnswer1.removeAll();
}
else if((jButtonAnswer1.isSelected()) && (g1.getG_correctAnswer() != answer1))
{
jButtonAnswer1.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/explode.png")));
int delay = 100;
try
{
Thread.sleep(delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
}
});
}
return jButtonAnswer1;
}
/**
* This method initialises jButtonAnswer2
*
* #return javax.swing.JButton
*/
private JButton getJButtonAnswer2() {
if (jButtonAnswer2 == null) {
jButtonAnswer2 = new JButton();
jButtonAnswer2.setBackground(Color.white);
jButtonAnswer2.setSize(new Dimension(228, 214));
jButtonAnswer2.setLocation(new Point(240, 164));
jButtonAnswer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonAnswer2.equals("answer2");
qn_num = qn_num + 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
if((jButtonAnswer2.isSelected()) && (g1.getG_correctAnswer() == answer2))
{
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
else if((jButtonAnswer2.isSelected()) && (g1.getG_correctAnswer() != answer2))
{
jButtonAnswer2.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/explode.png")));
int delay = 100;
try
{
Thread.sleep(delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
}
});
}
return jButtonAnswer2;
}
/**
* This method initialises jButtonAnswer3
*
* #return javax.swing.JButton
*/
private JButton getJButtonAnswer3() {
if (jButtonAnswer3 == null) {
jButtonAnswer3 = new JButton();
jButtonAnswer3.setBackground(Color.white);
jButtonAnswer3.setSize(new Dimension(228, 214));
jButtonAnswer3.setLocation(new Point(474, 163));
jButtonAnswer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonAnswer3.equals("answer3");
qn_num = qn_num + 1;
GameQuestion g1 = new GameQuestion(qn_num);
g1.retrieveGameQuestion();
if((jButtonAnswer3.isSelected()) && (g1.getG_correctAnswer() == answer3))
{
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
else if((jButtonAnswer3.isSelected()) && (g1.getG_correctAnswer() != answer3))
{
jButtonAnswer1.setIcon(new ImageIcon(getClass().getResource("/HealthOK/ui/images/explode.png")));
int delay = 100;
try
{
Thread.sleep(delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
jLabelQn.setText("Q" + qn_num + ".");
jLabelQuestion.setText(g1.getG_question());
jLabelDescription1.setText(g1.getG_imageDescription1());
jButtonAnswer1.setIcon(new ImageIcon(g1.getG_image1()));
jButtonAnswer1.removeAll();
jLabelDescription2.setText(g1.getG_imageDescription2());
jLabelDescription3.setText(g1.getG_imageDescription3());
jButtonAnswer2.setIcon(new ImageIcon(g1.getG_image2()));
jButtonAnswer3.setIcon(new ImageIcon(g1.getG_image3()));
}
}
});
}
return jButtonAnswer3;
}
/**
* This method initializes jButtonEdit
*
* #return javax.swing.JButton
*/
private JButton getJButtonAdd() {
if (jButtonAdd == null) {
jButtonAdd = new JButton();
jButtonAdd.setBounds(new Rectangle(591, 9, 90, 39));
jButtonAdd.setFont(new Font("Dialog", Font.BOLD, 16));
jButtonAdd.setText("Add");
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
t.stop();
JPanel panel = new GamesCreatePanel(myFrame);
myFrame.getContentPane().removeAll();
myFrame.getContentPane().add(panel);
myFrame.getContentPane().validate();
myFrame.getContentPane().repaint();
Object admin = null;
if(getName() == admin) {
jButtonAdd.setVisible(true);
}
else {
jButtonAdd.setVisible(false);
}
}
});
}
return jButtonAdd;
}
/**
* This method initializes jButtonEdit
*
* #return javax.swing.JButton
*/
private JButton getJButtonEdit() {
if (jButtonEdit == null) {
jButtonEdit = new JButton();
jButtonEdit.setPreferredSize(new Dimension(65, 31));
jButtonEdit.setSize(new Dimension(90, 39));
jButtonEdit.setText("Edit");
jButtonEdit.setFont(new Font("Dialog", Font.BOLD, 16));
jButtonEdit.setLocation(new Point(492, 9));
jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
t.stop();
String a = jLabelQuestion.getText();
String b = jButtonAnswer1.getText();
String c = jButtonAnswer2.getText();
String d = jButtonAnswer3.getText();
String f = jLabelDescription1.getText();
String g = jLabelDescription2.getText();
String h = jLabelDescription3.getText();
GameQuestion game = new GameQuestion();
game.setG_question(a);
game.setG_image1(b);
game.setG_image2(c);
game.setG_image3(d);
game.setG_imageDescription1(f);
game.setG_imageDescription2(g);
game.setG_imageDescription3(h);
JPanel panel = new GamesEditPanel(myFrame, a, game);
myFrame.getContentPane().removeAll();
myFrame.getContentPane().add(panel);
myFrame.getContentPane().validate();
myFrame.getContentPane().repaint();
}
});
}
return jButtonEdit;
}
}

This code is way too long to go through it, but a quick look at your if statements reveals you are checking whether a JButton is selected. What you probably want is adding an ActionListener to the JButton, which will be called when the user clicks the JButton. In the ActionListener you can then check whether the correct answer was given and proceed, or show the 'bomb image'.
I suggest you take a look at the Swing button tutorial and more specifically the JButton part of the tutorial

Related

Make a line of Swing components of variable length inside another line

I'm trying to make a web inspector interface in Swing.
I managed to make the tags render correctly, but I have a problem with attributes.
I have a JPanel with FlowLayout, there are some JLabels inside it, and a JPanel in the middle, which has FlowLayout set on it too. That JPanel can contain any number of inner JPanels for attributes, each of them has 2 TextFields and 3 JLabels, inputs have zero width by default and are not visible, JLabels can have arbitrary length.
The problem is I cannot make my lines have the correct length. I add my attributes JPanels after the main container is laid out and made visible, maybe that is the problem. I also tried setting all the widths manually in the code (and increase the width of my top-level line too), but the output is still far from correct. My elements are either not visible except the first child JPanel (but I have a lot of empty space on the right).
I tried calling validate() and doLayout(), and I don't see any difference.
What is the right way to do this layout? First add everything, and then call setVisible() on my JFrame? Or it's not necessary?
Also, how can I make sure that the elements will always stay in one line?
I tried BoxLayout too, but that's not suitable, as it gives all the available parent width to my attributes panel (and I need it have zero pixel width when it is empty). If I add glue to the end, then free space is distributed equally between the glue and my JPanel.
public class WebInspectorTest {
private static Node prepareTree() {
Node root = new Node(1);
root.tagName = "body";
root.attributes.put("onload", "init()");
Node p = new Node(root, 1);
p.tagName = "p";
Node text1 = new Node(p, 3);
text1.nodeValue = "This is a ";
Node i = new Node(p, 1);
i.tagName = "i";
i.attributes.put("style", "background-color: rgb(223, 216, 45); color: #8848a7; cursor: pointer");
Node text2 = new Node(i, 3);
text2.nodeValue = "paragraph";
Node text3 = new Node(p, 3);
text3.nodeValue = ".";
Node img = new Node(p, 1);
img.tagName = "img";
img.attributes.put("src", "smiley.gif");
return root;
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {}
final Node root = prepareTree();
if (root == null) return;
final JFrame frame = new JFrame("Document Inspector");
JPanel cp = new JPanel();
cp.setBorder(BorderFactory.createEmptyBorder(9, 10, 9, 10));
frame.setContentPane(cp);
cp.setLayout(new BorderLayout());
final JPanel contentpane = new JPanel();
contentpane.setBackground(Color.WHITE);
contentpane.setOpaque(true);
//contentpane.setBounds(0, 0, 490, 380);
final int width = 490, height = 418;
final JScrollPane scrollpane = new JScrollPane(contentpane);
scrollpane.setOpaque(false);
scrollpane.getInsets();
cp.add(scrollpane);
scrollpane.setBackground(Color.WHITE);
scrollpane.setOpaque(true);
scrollpane.setPreferredSize(new Dimension(width, height));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TagLibrary.init();
final Entry rootEntry = new Entry(root);
contentpane.add(rootEntry);
final JScrollPane sp = scrollpane;
int width = sp.getVerticalScrollBar().isVisible() ? sp.getWidth() - sp.getVerticalScrollBar().getPreferredSize().width - 12 : sp.getWidth() + sp.getVerticalScrollBar().getPreferredSize().width;
rootEntry.inflate(width);
contentpane.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentMoved(java.awt.event.ComponentEvent evt) {}
#Override
public void componentResized(java.awt.event.ComponentEvent evt) {
int width = sp.getVerticalScrollBar().isVisible() ? sp.getWidth() - sp.getVerticalScrollBar().getPreferredSize().width - 12 : sp.getWidth() - 12;
rootEntry.setWidth(width);
}
});
}
});
}
}
public class Entry extends javax.swing.JPanel {
public Entry() {
initComponents();
}
public Entry(Node node) {
this.node = node;
initComponents();
initEvents();
}
private void addAttributes() {
final Entry entry = this;
Set<String> keys = node.attributes.keySet();
attributes.setPreferredSize(new Dimension(0, line_height));
int index = 0;
for (String key: keys) {
Attribute attr = new Attribute(this, key, node.attributes.get(key));
attributes.add(attr);
Dimension dim = attributes.getPreferredSize();
attributes.setPreferredSize(new Dimension(dim.width + attr.getWidth(), dim.height));
}
int max_width = Math.max(attributes.getPreferredSize().width + headerTag.getWidth() + headerTag2.getWidth() + 38, getPreferredSize().width);
header.setMinimumSize(new Dimension(max_width, line_height));
footer.setMinimumSize(new Dimension(max_width, line_height));
setMinimumSize(new Dimension(max_width, line_height));
}
private void initEvents() {
marker.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
if (!opened) open();
else close();
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});
addMouseListener(listener);
}
public void addChild(Entry child, int pos) {
content.add(child, pos);
//content.validate();
}
public void inflate(int width) {
if (node == null) return;
if (node.nodeType == 1) {
boolean isPaired = !TagLibrary.tags.containsKey(node.tagName.toLowerCase()) ||
TagLibrary.tags.get(node.tagName.toLowerCase());
if (!isPaired) {
headerTag.setText("<" + node.tagName.toLowerCase());
headerTag2.setText(" />");
threeDots.setText("");
headerTag3.setText("");
content.setVisible(false);
footer.setVisible(false);
marker.setVisible(false);
} else {
headerTag.setText("<" + node.tagName.toLowerCase());
headerTag2.setText(">");
headerTag3.setText("</" + node.tagName.toLowerCase() + ">");
footerTag.setText("</" + node.tagName.toLowerCase() + ">");
}
addAttributes();
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
content.removeAll();
//System.out.println(getWidth());
for (int i = 0; i < node.children.size(); i++) {
Entry e = new Entry(node.children.get(i));
content.add(e);
e.inflate(w);
//content.setSize(e.getSize());
}
content.doLayout();
if (node.children.size() > 0) {
open();
} else {
close();
}
} else if (node.nodeType == 3 && !node.nodeValue.matches("\\s*")) {
content.removeAll();
header.setVisible(false);
footer.setVisible(false);
JTextArea textarea = new JTextArea();
textarea.setText(node.nodeValue);
textarea.setEditable(false);
textarea.setOpaque(false);
textarea.setBackground(new Color(255, 255, 255, 0));
textarea.setColumns(180);
textarea.setFont(new Font("Tahoma", Font.PLAIN, 16));
int rows = node.nodeValue.split("\n").length;
textarea.setRows(rows);
textarea.addMouseListener(listener);
int height = getFontMetrics(textarea.getFont()).getHeight() * rows;
content.add(textarea);
content.setOpaque(false);
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
((JPanel)getParent()).setMinimumSize(new Dimension(w, line_height * 2 + content.getPreferredSize().height));
opened = true;
content.validate();
} else {
setVisible(false);
content.removeAll();
opened = false;
return;
}
int w = Math.max(Math.max(Math.max(content.getMinimumSize().width, header.getMinimumSize().width), min_width), width - margin);
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
int height = line_height * 2 + content.getPreferredSize().height;
if (opened) {
setSize(w, height);
}
updateWidth(w);
}
public void setWidth(int width) {
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
setPreferredSize(new Dimension(w, getPreferredSize().height));
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry)c[i]).setWidth(w);
} else {
c[i].setSize(w, c[i].getMaximumSize().height);
c[i].setMaximumSize(new Dimension(w, c[i].getMaximumSize().height));
}
}
}
private void updateWidth(int width) {
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width);
if (content.getPreferredSize().width > w) {
w = content.getPreferredSize().width;
}
if (getSize().width > w) return;
setPreferredSize(new Dimension(w, getPreferredSize().height));
Entry last = this;
Component c = getParent();
while (c != null && c.getParent() != null && c.getParent() instanceof Entry) {
//c.setPreferredSize(new Dimension(w, c.getPreferredSize().height));
Component[] children = ((JPanel)c).getComponents();
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof Entry && children[i] != last && children[i].getSize().width < w) {
((Entry)children[i]).setWidth(w);
} else if (!(children[i] instanceof Entry) && children[i].getParent() != last && children[i].getSize().width < w) {
children[i].setSize(w, children[i].getMaximumSize().height);
children[i].setMaximumSize(new Dimension(w, children[i].getMaximumSize().height));
}
}
w += margin;
w = Math.max(c.getParent().getSize().width, w);
if (((Entry)c.getParent()).node.tagName.equals("body")) System.err.println("Root entry width: " + w);
int h = line_height * 2 + ((Entry)c.getParent()).content.getPreferredSize().height;
c.getParent().setSize(w, h);
((Entry)c.getParent()).header.setMinimumSize(new Dimension(w, line_height));
((Entry)c.getParent()).footer.setMinimumSize(new Dimension(w, line_height));
//((Entry)c.getParent()).content.setPreferredSize(new Dimension(w, ((Entry)c.getParent()).getSize().height - line_height * 2));
last = (Entry)c.getParent();
c = c.getParent().getParent();
}
if (c != null) c.validate();
content.validate();
}
ActionListener callback;
public static final int min_width = 280;
public static final int line_height = 26;
public static final int margin = 30;
MouseListener listener = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {
//System.out.println("Entered");
updateChildren(true);
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
//System.out.println("Exited");
updateChildren(false);
repaint();
}
};
private void updateChildren(boolean value) {
hovered = value;
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry)c[i]).updateChildren(value);
}
}
}
#Override
public void paintComponent(Graphics g) {
if (hovered) {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(190, 230, 255, 93));
g.fillRect(0, 0, getWidth(), getHeight());
} else {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, getWidth(), getHeight());
}
//super.paintComponent(g);
}
private boolean hovered = false;
public void open() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png")));
threeDots.setVisible(false);
headerTag3.setVisible(false);
content.setVisible(true);
footer.setVisible(true);
opened = true;
}
public void close() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle2.png")));
content.setVisible(false);
footer.setVisible(false);
boolean has_children = node.children.size() > 0;
threeDots.setVisible(has_children);
marker.setVisible(has_children);
headerTag3.setVisible(true);
opened = false;
}
public void openAll() {
open();
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry) c[i]).openAll();
}
}
}
public void closeAll() {
close();
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry) c[i]).closeAll();
}
}
}
public boolean opened = false;
public Node node;
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
header = new javax.swing.JPanel();
headerMargin = new javax.swing.JPanel();
marker = new javax.swing.JLabel();
headerTag = new javax.swing.JLabel();
attributes = new javax.swing.JPanel();
headerTag2 = new javax.swing.JLabel();
threeDots = new javax.swing.JLabel();
headerTag3 = new javax.swing.JLabel();
content = new javax.swing.JPanel();
footer = new javax.swing.JPanel();
footerMargin = new javax.swing.JPanel();
footerTag = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));
header.setBackground(new java.awt.Color(255, 255, 255));
header.setAlignmentX(0.0F);
header.setMaximumSize(new java.awt.Dimension(32767, 26));
header.setMinimumSize(new java.awt.Dimension(280, 26));
header.setOpaque(false);
header.setPreferredSize(new java.awt.Dimension(280, 26));
header.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 0, 2));
headerMargin.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 0, 5));
headerMargin.setMaximumSize(new java.awt.Dimension(30, 26));
headerMargin.setOpaque(false);
headerMargin.setPreferredSize(new java.awt.Dimension(30, 26));
marker.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png"))); // NOI18N
marker.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
marker.setPreferredSize(new java.awt.Dimension(22, 22));
javax.swing.GroupLayout headerMarginLayout = new javax.swing.GroupLayout(headerMargin);
headerMargin.setLayout(headerMarginLayout);
headerMarginLayout.setHorizontalGroup(
headerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerMarginLayout.createSequentialGroup()
.addComponent(marker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
headerMarginLayout.setVerticalGroup(
headerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerMarginLayout.createSequentialGroup()
.addComponent(marker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
header.add(headerMargin);
headerTag.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag.setForeground(new java.awt.Color(102, 0, 153));
headerTag.setText("<body");
header.add(headerTag);
attributes.setMaximumSize(new java.awt.Dimension(32767, 26));
attributes.setOpaque(false);
attributes.setPreferredSize(new java.awt.Dimension(0, 26));
attributes.setLayout(new javax.swing.BoxLayout(attributes, javax.swing.BoxLayout.LINE_AXIS));
header.add(attributes);
headerTag2.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag2.setForeground(new java.awt.Color(102, 0, 153));
headerTag2.setText(">");
header.add(headerTag2);
threeDots.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
threeDots.setText("...");
threeDots.setPreferredSize(new java.awt.Dimension(19, 20));
header.add(threeDots);
headerTag3.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag3.setForeground(new java.awt.Color(102, 0, 153));
headerTag3.setText("</body>");
header.add(headerTag3);
add(header);
content.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 30, 0, 0));
content.setAlignmentX(0.0F);
content.setOpaque(false);
content.setLayout(new javax.swing.BoxLayout(content, javax.swing.BoxLayout.PAGE_AXIS));
add(content);
footer.setBackground(new java.awt.Color(255, 255, 255));
footer.setAlignmentX(0.0F);
footer.setMaximumSize(new java.awt.Dimension(32767, 26));
footer.setOpaque(false);
footer.setPreferredSize(new java.awt.Dimension(91, 26));
footer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 0, 2));
footerMargin.setOpaque(false);
footerMargin.setPreferredSize(new java.awt.Dimension(30, 26));
javax.swing.GroupLayout footerMarginLayout = new javax.swing.GroupLayout(footerMargin);
footerMargin.setLayout(footerMarginLayout);
footerMarginLayout.setHorizontalGroup(
footerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 30, Short.MAX_VALUE)
);
footerMarginLayout.setVerticalGroup(
footerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 26, Short.MAX_VALUE)
);
footer.add(footerMargin);
footerTag.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
footerTag.setForeground(new java.awt.Color(102, 0, 153));
footerTag.setText("</body>");
footer.add(footerTag);
add(footer);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel attributes;
private javax.swing.JPanel content;
private javax.swing.JPanel footer;
private javax.swing.JPanel footerMargin;
private javax.swing.JLabel footerTag;
private javax.swing.JPanel header;
private javax.swing.JPanel headerMargin;
private javax.swing.JLabel headerTag;
private javax.swing.JLabel headerTag2;
private javax.swing.JLabel headerTag3;
private javax.swing.JLabel marker;
private javax.swing.JLabel threeDots;
// End of variables declaration
}
public class Attribute extends javax.swing.JPanel {
public Attribute(Entry entry, String name, String value) {
initComponents();
this.entry = entry;
name_field.setText(name);
if (value == null || value.isEmpty()) {
value_field.setText("");
eq.setVisible(false);
quote1.setVisible(false);
quote2.setVisible(false);
value_field.setVisible(false);
} else {
value_field.setText(value);
}
//setOpaque(true);
//setBackground(Color.RED);
setSize(name_field.getPreferredSize().width + value_field.getPreferredSize().width + 36, Entry.line_height);
originalName = name;
}
public String getEditorText() {
return full_editor.getText();
}
public String getNameField() {
return name_field.getText();
}
public String getValueField() {
return value_field.getText();
}
public String getOriginalName() {
return originalName;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
full_editor = new javax.swing.JTextField();
name_field = new javax.swing.JLabel();
eq = new javax.swing.JLabel();
quote1 = new javax.swing.JLabel();
value_editor = new javax.swing.JTextField();
value_field = new javax.swing.JLabel();
quote2 = new javax.swing.JLabel();
setMaximumSize(new java.awt.Dimension(32767, 24));
setOpaque(false);
setPreferredSize(new java.awt.Dimension(400, 22));
setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
full_editor.setBorder(null);
full_editor.setMinimumSize(new java.awt.Dimension(0, 22));
full_editor.setOpaque(false);
full_editor.setPreferredSize(new java.awt.Dimension(6, 22));
add(full_editor);
name_field.setForeground(new java.awt.Color(102, 0, 102));
name_field.setText("class");
name_field.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 2, 0, 0));
add(name_field);
eq.setForeground(new java.awt.Color(102, 0, 102));
eq.setText("=");
add(eq);
quote1.setForeground(new java.awt.Color(153, 153, 153));
quote1.setText("\"");
add(quote1);
value_editor.setBorder(null);
value_editor.setMinimumSize(new java.awt.Dimension(0, 22));
value_editor.setOpaque(false);
value_editor.setPreferredSize(new java.awt.Dimension(0, 22));
add(value_editor);
value_field.setForeground(new java.awt.Color(0, 51, 204));
value_field.setText("link");
add(value_field);
quote2.setForeground(new java.awt.Color(153, 153, 153));
quote2.setText("\"");
add(quote2);
}// </editor-fold>
private final int full_editor_width = 8;
private boolean is_new = false;
private String originalName;
private Entry entry;
private ActionListener listener;
// Variables declaration - do not modify
private javax.swing.JLabel eq;
private javax.swing.JTextField full_editor;
private javax.swing.JLabel name_field;
private javax.swing.JLabel quote1;
private javax.swing.JLabel quote2;
private javax.swing.JTextField value_editor;
private javax.swing.JLabel value_field;
// End of variables declaration
}
public class Node {
public Node() {}
public Node(Node parent_node) {
if (parent_node.nodeType == 1) {
parent = parent_node;
parent_node.addChild(this);
}
}
public Node(int node_type) {
nodeType = node_type;
}
public Node(Node parent_node, int node_type) {
if (parent_node.nodeType == 1) {
parent = parent_node;
parent_node.addChild(this);
}
nodeType = node_type;
}
public boolean addChild(Node node) {
if (nodeType == 1) {
children.add(node);
return true;
}
return false;
}
public Node parent;
public Vector<Node> children = new Vector<Node>();
public LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>();
public Node previousSibling;
public Node nextSibling;
public String tagName = "";
public int nodeType = 3;
public String nodeValue = "";
}
public class TagLibrary {
public static void init() {
if (init) return;
tags.put("br", false);
tags.put("hr", false);
tags.put("link", false);
tags.put("img", false);
tags.put("a", true);
tags.put("span", true);
tags.put("div", true);
tags.put("p", true);
tags.put("sub", true);
tags.put("sup", true);
tags.put("b", true);
tags.put("i", true);
tags.put("u", true);
tags.put("s", true);
tags.put("strong", true);
tags.put("em", true);
tags.put("quote", true);
tags.put("cite", true);
tags.put("table", true);
tags.put("thead", true);
tags.put("tbody", true);
tags.put("cite", true);
tags.put("head", true);
tags.put("body", true);
leaves.add("style");
leaves.add("script");
init = true;
}
private static boolean init = false;
public static Hashtable<String, Boolean> tags = new Hashtable<String, Boolean>();
public static Vector<String> leaves = new Vector<String>();
}
Here is the screeshot of the GUI:
Output
And here is the same when I make a viewport wider by dragging:
Output
This is close to what I need, despite the fact that the whole attributes are hidden when the parent line container is way too narrow.

Simple chat client using JMS

I'm using Swing, Java Messaging Service and GlassFish4.1 server to build a chat box from a Jpanel so I can add it to my Jframe application; but I seem to have a problem establishing a connection.
During runtime the program stops at the line:
TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn");
I previously got this client-code to work on an Enterprise application, but now I'm attempting to add it to a regular Java project I'm rather stuck.
Really appreciate any help on this, I'm very new to JMS so please keep answers as Lamen as possible. Thanks!
import java.awt.event.KeyEvent;
import javax.jms.*;
import javax.naming.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class ChatPanel extends javax.swing.JPanel implements Runnable{
private Thread t = null;
private TopicConnection tpConnection = null;
private TopicPublisher tpPublisher = null;
private TopicSession tpSession = null;
private TopicSubscriber tpSubscriber = null;
private final String name;
/**
* Creates new form chatFrame
* #param nickName
*/
public ChatPanel(String nickName)
{
initComponents();
DefaultCaret caret = (DefaultCaret) gameInfoTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
name = nickName;
connect();
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
// </editor-fold>
public JTextArea getTextArea()
{
return gameInfoTextArea;
}
public void setText(String textString)
{
String s = gameInfoTextArea.getText() + "\n" + textString;
gameInfoTextArea.setText(s);
}
private void connect()
{
try
{
Context ctx = new InitialContext();
TopicConnectionFactory tcf = (TopicConnectionFactory)
ctx.lookup("BJconn");
tpConnection = tcf.createTopicConnection();
tpConnection.setClientID(name);
tpSession = tpConnection.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup("BJDest");
tpPublisher = tpSession.createPublisher(topic);
tpSubscriber = tpSession.createDurableSubscriber(topic, name);
tpConnection.start();
t = new Thread(this);
t.start();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Chat cannot connect");
System.out.println(e.getMessage());
}
}
/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
tpConnection.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage() );
}
} */
private void sendMessage()
{
try
{
TextMessage tx = tpSession.createTextMessage();
tx.setText(name + ": " + this.chatField.getText());
tpPublisher.send(tx);
this.chatField.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Cannot send message");
}
}
#Override
public void run()
{
try
{
while (true)
{
TextMessage tx = (TextMessage) tpSubscriber.receive();
if (tx != null)
{
String content = "";
content += this.gameInfoTextArea.getText() + "\n" + tx.getText();
this.gameInfoTextArea.setText(content);
Thread.sleep(100);
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
chatField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
gameInfoTextArea = new javax.swing.JTextArea();
setBackground(new java.awt.Color(0, 102, 0));
chatField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chatFieldActionPerformed(evt);
}
});
chatField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
chatFieldKeyReleased(evt);
}
});
gameInfoTextArea.setEditable(false);
gameInfoTextArea.setColumns(20);
gameInfoTextArea.setRows(5);
jScrollPane1.setViewportView(gameInfoTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chatField)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>
private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void chatFieldKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
{
sendMessage();
}
}
// Variables declaration - do not modify
private javax.swing.JTextField chatField;
private javax.swing.JTextArea gameInfoTextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}

Libgdx collision using box2d working for desktop but failed to collide in Android emulator

My code for collision of a dynamic body to a static body works perfectly for desktop , but when running in Android emulator it can not able to detect collision ,Dynamic body goes down without collision.
I used Libgdx version : 1.5.0 .
Code :
package com.kg.game;
import java.util.Random;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
private static final float VIEWPORT_WIDTH = 10;
private static final float BALL_RADIUS = 0.15f;
private static final int MAX_BALLS = 200;
private World world;
private Body[] ballModels;
private Texture bottleTexture;
private Texture ballTexture;
private Sprite[] ballSprites;
private Texture whiteTexture;
private Sprite groundSprite;
private SpriteBatch batch;
private BitmapFont font;
private OrthographicCamera camera;
private final Random rand = new Random();
float w;
float h;
Box2DDebugRenderer debugRenderer;
private final TweenManager tweenManager = new TweenManager();
#Override
public void create() {
debugRenderer = new Box2DDebugRenderer();
world = new World(new Vector2(0, -10), true);
createGround();
createBalls();
batch = new SpriteBatch();
font = new BitmapFont();
font.setColor(Color.BLACK);
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_WIDTH * h / w);
camera.position.set(0, (VIEWPORT_WIDTH * h / w) / 2, 0);
camera.update();
createSprites();
Gdx.input.setInputProcessor(new InputAdapter() {
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
restart();
return true;
}
});
restart();
}
private void createGround() {
BodyDef bd = new BodyDef();
bd.position.set(0, 0);
bd.type = BodyType.StaticBody;
PolygonShape shape = new PolygonShape();
shape.setAsBox(100, 4);
FixtureDef fd = new FixtureDef();
fd.density = 1;
fd.friction = 0.5f;
fd.restitution = 0.5f;
fd.shape = shape;
world.createBody(bd).createFixture(fd);
shape.dispose();
}
private void createBalls() {
BodyDef ballBodyDef = new BodyDef();
ballBodyDef.type = BodyType.DynamicBody;
CircleShape shape = new CircleShape();
shape.setRadius(BALL_RADIUS);
FixtureDef fd = new FixtureDef();
fd.density = 1;
fd.friction = 0.5f;
fd.restitution = 0.5f;
fd.shape = shape;
ballModels = new Body[MAX_BALLS];
for (int i = 0; i < MAX_BALLS; i++) {
ballModels[i] = world.createBody(ballBodyDef);
ballModels[i].createFixture(fd);
}
shape.dispose();
}
private void createSprites() {
ballTexture = new Texture(Gdx.files.internal("ball.png"));
ballTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
ballSprites = new Sprite[MAX_BALLS];
for (int i = 0; i < MAX_BALLS; i++) {
ballSprites[i] = new Sprite(ballTexture);
ballSprites[i].setSize(BALL_RADIUS * 2, BALL_RADIUS * 2);
ballSprites[i].setOrigin(BALL_RADIUS, BALL_RADIUS);
}
whiteTexture = new Texture(Gdx.files.internal("ground.png"));
groundSprite = new Sprite(whiteTexture);
groundSprite.setSize(100, 4);
groundSprite.setPosition(-VIEWPORT_WIDTH / 2, 0);
groundSprite.setColor(Color.BLACK);
}
private float elapsed = 0;
#Override
public void render() {
tweenManager.update(1 / 60f);
world.step(1 / 60f, 10, 10);
debugRenderer.render(world, camera.combined);
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
GL20 gl = Gdx.gl20;
gl.glClearColor(1, 1, 1, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// Update
for (int i = 0; i < MAX_BALLS; i++) {
Vector2 ballPos = ballModels[i].getPosition();
ballSprites[i].setPosition(ballPos.x - ballSprites[i].getWidth()
/ 2, ballPos.y - ballSprites[i].getHeight() / 2);
ballSprites[i].setRotation(ballModels[i].getAngle()
* MathUtils.radiansToDegrees);
}
// Render
batch.setProjectionMatrix(camera.combined);
batch.begin();
groundSprite.draw(batch);
for (int i = 0; i < MAX_BALLS; i++)
ballSprites[i].draw(batch);
batch.end();
// batch.getProjectionMatrix().setToOrtho2D(0, 0, w, h);
batch.begin();
font.draw(batch, "Touch the screen to restart", 5, h - 5);
batch.end();
}
#Override
public void dispose() {
bottleTexture.dispose();
ballTexture.dispose();
batch.dispose();
font.dispose();
world.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return true;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
private void restart() {
Vector2 vec = new Vector2();
for (int i = 0; i < MAX_BALLS; i++) {
float tx = rand.nextFloat() * 1.0f - 0.5f;
float ty = VIEWPORT_WIDTH * h / w;
float angle = rand.nextFloat() * MathUtils.PI * 2;
ballModels[i].setActive(false);
ballModels[i].setLinearVelocity(vec.set(0, 0));
ballModels[i].setAngularVelocity(0);
ballModels[i].setTransform(vec.set(tx, ty), angle);
}
tweenManager.killAll();
Tween.call(new TweenCallback() {
private int idx = 0;
#Override
public void onEvent(int type, BaseTween<?> source) {
if (idx < ballModels.length) {
ballModels[idx].setAwake(true);
ballModels[idx].setActive(true);
idx += 1;
}
}
}).repeat(-1, 0.1f).start(tweenManager);
}
}
Screensots :
this is an idea, looking at the proportions of your images, I think the error may be out there, I would look at these lines:
groundSprite.setSize(100, 4); //<--especially here
groundSprite.setPosition(-VIEWPORT_WIDTH / 2, 0); //<--especially here
.
private void createGround() {
BodyDef bd = new BodyDef();
bd.position.set(0, 0); //<--especially here
bd.type = BodyType.StaticBody;
PolygonShape shape = new PolygonShape();
shape.setAsBox(100, 4); //<--especially here
especially the position and size, if it is standing in the same place, with the change of screen "device".
You tried to render debug? I see out there, if so, you can see your object in the emulated device?
I hope I understand, but not if that be the error

Getting null / empty JtextArea

I crated a Frame which have a panel inside it and the panel have a textarea inside it. Now i created a constructor which makes the frame visible for some time and after that it is set as invisible. Time for which it is visible it shows some massage.
When i run the constructor code inside the main method of outputDisplay class it shows the text massage
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class OutputDisplay {
static JFrame frame;
JPanel panel;
JTextArea area;
Font font;
public void timer(int time){
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
}
});
timer.start();
timer.setRepeats(false);
}
OutputDisplay(String ip,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.RED);
area.setSize(200, 200);
int j=0;
String[] t = {ip};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue,String path,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.MAGENTA);
area.setSize(200, 200);
int j=0;
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(500, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue) throws InterruptedException{
frame = new JFrame("Report");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.BLUE);
area.setSize(200, 200);
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 600);
frame.setVisible(true);
frame.setResizable(false);
}//constructor
public OutputDisplay() {
}//no arg
public void dialogue (String massage) throws InterruptedException{
frame = new JFrame("Massage");
frame.setLocation(400, 220);
JPanel panel = new JPanel();
JTextArea area = new JTextArea();
Font font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.GREEN);
area.setSize(200, 200);
int j=0;
String[] t = {massage};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(400, 100);
frame.setVisible(true);
Thread.sleep(8*1000);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//dialogue
static void warningPopUp (String massage){
JOptionPane.showMessageDialog(null, massage);
}//dialogue
public static void main(String[] args){
new OutputDisplay("We are checking for account validation"+"\n"
+ "If user id and password matches then we will goto websites for updation. " +"\n"
+ "You will get a complete report once we are done", 4*1000);
}//main
}//OutputDisplay
Don't call Thread.sleep(...) on the Swing EDT as that just puts your whole GUI to sleep.
Do use a Swing Timer instead.
Do Google and search this site for similar questions.
Please check out Lesson: Concurrency in Swing
Also check out the Swing Tutorials
Edit
You're still using Thread.sleep, again you shouldn't use it, but instead should use a Timer. Also, never set a JTextArea's size or preferred size ever. Do this and the scrollbars of your JScrollPane won't work. Instead, set its rows and columns.
import java.awt.Color;
import java.awt.Font;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TimeLimitedDialogTester {
private static final int EB_GAP = 25;
private JPanel mainPanel = new JPanel();
public TimeLimitedDialogTester() {
mainPanel.add(new JButton(new ShowDialogAction("Show Dialog")));
mainPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, 2 * EB_GAP, 2 * EB_GAP, 2 * EB_GAP));
}
public JPanel getMainPanel() {
return mainPanel;
}
#SuppressWarnings("serial")
private class ShowDialogAction extends AbstractAction {
public ShowDialogAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Window mainWin = SwingUtilities.getWindowAncestor(mainPanel);
int seconds = 5;
String dialogTitle = "WARNING";
String text = "We are checking for account validation. If user id and password matches then we"
+ " will go to websites for updating. You will get a complete report once we are done.";
TimeLimitedDialog timeLimitedDialog = new TimeLimitedDialog(mainWin, seconds, dialogTitle, text);
timeLimitedDialog.dialogShow();
}
}
private static void createAndShowGui() {
TimeLimitedDialogTester timeLimitedDialog = new TimeLimitedDialogTester();
JFrame frame = new JFrame("TimeLimitedDialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(timeLimitedDialog.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class TimeLimitedDialog {
private static final int ROWS = 6;
private static final int COLS = 30;
private static final Color FG = Color.green.darker().darker();
private JDialog dialog;
private JTextArea displayArea = new JTextArea(ROWS, COLS);
private int seconds;
public TimeLimitedDialog(Window mainWin, int seconds, String dialogTitle, String text) {
displayArea.setWrapStyleWord(true);
displayArea.setLineWrap(true);
displayArea.setFocusable(false);
displayArea.setText(text);
displayArea.setForeground(FG);
displayArea.setFont(displayArea.getFont().deriveFont(Font.BOLD));
this.seconds = seconds;
dialog = new JDialog(mainWin, dialogTitle, ModalityType.APPLICATION_MODAL);
dialog.add(new JScrollPane(displayArea));
dialog.pack();
dialog.setLocationRelativeTo(mainWin);
}
public void dialogShow() {
new Timer(seconds * 1000, new TimerListener()).start();
dialog.setVisible(true);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (dialog != null && dialog.isVisible()) {
dialog.dispose();
}
((Timer) e.getSource()).stop();
}
}
}

javax.swing: JEditorPane (html page) doesn't appear on main frame

class Browser has method getBrowserWindow() which returns JEditorPane(new URL("some URL")).
class MainForm calls new Browser().getBrowserWindow() and assigns it to another JEditorPane object.
editor = new Browser().getBrowserWindow();
scrollpane = new JScrollPane(editor);
Object editor.hashCode() is correct, so there's no doubt that i've got the right object.
Still, i can't see html page in the main frame.
P.S. i've tried creating instead of htmlpane simple JEditorPane filled with text only,
and this one i couldn't see neither.
P.P.S.
package faxutils;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
public class MainForm {
public MainForm() {
}
private static GeneralActions ga = new GeneralActions();
private static Arguments _args_for_Update;
private static String _Phone;
private static JTextField[] emails;
private static MyConstants c = new MyConstants();
private static JFrame frame = new JFrame("frame title");
private static JCheckBox c2 = new JCheckBox("SMS Notification");
private static JCheckBox c1 = new JCheckBox("PDF");
private static JCheckBox c3 = new JCheckBox("153");
private static JTextField textBox1 = new JTextField(20);
private static JTextField textBox2 = new JTextField(20);
private static JTextField textBox3 = new JTextField(20);
private static JTextField textBox4 = new JTextField(20);
private static JTextArea richText = new JTextArea();
private static JEditorPane log = new JEditorPane();
private static JScrollPane scrollp = new JScrollPane(richText);
private static JScrollPane scrollplog = new JScrollPane(log);
private static JPanel p1 = new JPanel();
private static JPanel p2 = new JPanel();
private static JLabel label3 = new JLabel("Send to:");
private static JLabel label2 = new JLabel("number");
private static JLabel label = new JLabel("Fax:");
private static JPanel p3 = new JPanel();
private static JButton button1 = new JButton("Search");
private static JButton button2 = new JButton("Save");
private static JButton button3 = new JButton("Send");
private static Component[] comp = new Component[]{c1, c2, c3, textBox2, textBox3, textBox3, textBox4, richText, log, button2, button3};
private static void createAndShowGUI() {
//Create and set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
Container contentPane = frame.getContentPane();
SpringLayout layout1 = new SpringLayout();
SpringLayout layout2 = new SpringLayout();
SpringLayout layout3 = new SpringLayout();
SpringLayout frmlayout = new SpringLayout();
p1.setBorder(new TitledBorder("Search"));
p2.setBorder(new TitledBorder("Customer details"));
p3.setBorder(new TitledBorder("Send test fax"));
p1.setLayout(layout1);
p2.setLayout(layout2);
p3.setLayout(layout3);
frame.setLayout(frmlayout);
//Create and add the components to p1.
p1.add(label);
p1.add(textBox1);
p1.add(button1);
//Create and add the components to p2
p2.add(scrollp);
p2.add(textBox2);
p2.add(textBox3);
p2.add(textBox4);
p2.add(c1);
p2.add(c2);
p2.add(button2);
//Create and add the components to p3
p3.add(c3);
p3.add(label3);
p3.add(label2);
p3.add(button3);
p3.add(scrollplog);
//Add panels to frame
contentPane.add(p1);
contentPane.add(p2);
contentPane.add(p3);
//Layout1
//label
layout1.putConstraint(SpringLayout.WEST, label,
5,
SpringLayout.WEST, p1);
layout1.putConstraint(SpringLayout.NORTH, label,
5,
SpringLayout.NORTH, p1);
//textbox1
layout1.putConstraint(SpringLayout.WEST, textBox1,
30,
SpringLayout.WEST, label);
layout1.putConstraint(SpringLayout.NORTH, textBox1,
0,
SpringLayout.NORTH, label);
//button1
layout1.putConstraint(SpringLayout.WEST, button1,
230,
SpringLayout.WEST, textBox1);
layout1.putConstraint(SpringLayout.NORTH, button1,
-5,
SpringLayout.NORTH, textBox1);
//Layout2
//RICHTEXT
layout2.putConstraint(SpringLayout.WEST, scrollp, 5, SpringLayout.WEST, p2);
layout2.putConstraint(SpringLayout.NORTH, scrollp, 5, SpringLayout.NORTH, p2);
layout2.putConstraint(SpringLayout.EAST, scrollp, -5, SpringLayout.EAST, p2);
layout2.putConstraint(SpringLayout.SOUTH, scrollp, -150, SpringLayout.SOUTH, p2);
//TEXTBOX1,2,3
layout2.putConstraint(SpringLayout.WEST, textBox2, 140, SpringLayout.WEST, scrollp);
layout2.putConstraint(SpringLayout.NORTH, textBox2, 130, SpringLayout.NORTH, scrollp);
layout2.putConstraint(SpringLayout.WEST, textBox3, 0, SpringLayout.WEST, textBox2);
layout2.putConstraint(SpringLayout.NORTH, textBox3, 25, SpringLayout.NORTH, textBox2);
layout2.putConstraint(SpringLayout.WEST, textBox4, 0, SpringLayout.WEST, textBox3);
layout2.putConstraint(SpringLayout.NORTH, textBox4, 25, SpringLayout.NORTH, textBox3);
//CHECKBOXES
layout2.putConstraint(SpringLayout.WEST, c1, 0, SpringLayout.WEST, scrollp);
layout2.putConstraint(SpringLayout.NORTH, c1, 200, SpringLayout.NORTH, scrollp);
layout2.putConstraint(SpringLayout.WEST, c2, 0, SpringLayout.WEST, c1);
layout2.putConstraint(SpringLayout.NORTH, c2, 25, SpringLayout.NORTH, c1);
//BUTTON
layout2.putConstraint(SpringLayout.WEST, button2, 160, SpringLayout.WEST, textBox4);
layout2.putConstraint(SpringLayout.NORTH, button2, 25, SpringLayout.NORTH, textBox4);
//Layout3
//CHECKBOX3
layout3.putConstraint(SpringLayout.WEST, c3, 5, SpringLayout.WEST, p3);
layout3.putConstraint(SpringLayout.NORTH, c3, 5, SpringLayout.NORTH, p3);
//label3
layout3.putConstraint(SpringLayout.WEST, label3, 50, SpringLayout.WEST, c3);
layout3.putConstraint(SpringLayout.NORTH, label3, 4, SpringLayout.NORTH, c3);
// label2
layout3.putConstraint(SpringLayout.WEST, label2, 50, SpringLayout.WEST, label3);
layout3.putConstraint(SpringLayout.NORTH, label2, 0, SpringLayout.NORTH, label3);
//button3
layout3.putConstraint(SpringLayout.WEST, button3, 305, SpringLayout.WEST, p3);
layout3.putConstraint(SpringLayout.NORTH, button3, 0, SpringLayout.NORTH, p3);
//Browser
layout3.putConstraint(SpringLayout.WEST, scrollplog, 0, SpringLayout.WEST, c3);
layout3.putConstraint(SpringLayout.NORTH, scrollplog, 25, SpringLayout.NORTH, c3);
layout3.putConstraint(SpringLayout.EAST, scrollplog, 320, SpringLayout.EAST, c3);
layout3.putConstraint(SpringLayout.SOUTH, scrollplog, 140, SpringLayout.SOUTH, c3);
//FrameLayout
//p1
frmlayout.putConstraint(SpringLayout.WEST, p1,
5,
SpringLayout.WEST, frame);
frmlayout.putConstraint(SpringLayout.NORTH, p1,
5,
SpringLayout.NORTH, frame);
frmlayout.putConstraint(SpringLayout.EAST, p1,
380,
SpringLayout.EAST, frame);
frmlayout.putConstraint(SpringLayout.SOUTH, p1,
50,
SpringLayout.SOUTH, frame);
//p2
frmlayout.putConstraint(SpringLayout.WEST, p2,
5,
SpringLayout.WEST, frame);
frmlayout.putConstraint(SpringLayout.NORTH, p2,
75,
SpringLayout.NORTH, p1);
frmlayout.putConstraint(SpringLayout.EAST, p2,
380,
SpringLayout.EAST, frame);
frmlayout.putConstraint(SpringLayout.SOUTH, p2,
285,
SpringLayout.SOUTH, p1);
//p3
frmlayout.putConstraint(SpringLayout.WEST, p3,
5,
SpringLayout.WEST, frame);
frmlayout.putConstraint(SpringLayout.NORTH, p3,
285,
SpringLayout.NORTH, p2);
frmlayout.putConstraint(SpringLayout.EAST, p3,
380,
SpringLayout.EAST, frame);
frmlayout.putConstraint(SpringLayout.SOUTH, p3,
200,
SpringLayout.SOUTH, p2);
//Display the window.
frame.setSize(400, 600);
initialize();
// frame.pack();
frame.setVisible(true);
}
private static void setPanelsEnabled(boolean b) {
for (int i = 0; i < comp.length; i++)
comp[i].setEnabled(b);
}
private static void initialize() {
try {
emails = new JTextField[]{textBox2, textBox3, textBox4};
textBox1.requestFocus();
setPanelsEnabled(false);
richText.setEditable(false);
log.setEditable(false);
textBox1.setText("enter number here");
} catch (Exception ex) {
System.out.println(c.MSGBOX_EXCEPTION_TITLE + ": " + ex);
}
}
private static void button1_Click() {
try {
label2.setText(textBox1.getText());
_Phone = textBox1.getText();
_args_for_Update = ga.query1(_Phone, c1, c2);
if (_args_for_Update.getUserId() == 0) {
c1.setSelected(false);
c2.setSelected(false);
System.out.println(c.MSGBOX_SEARCH_STATUS_TITLE + ": " + c.MSGBOX_NO_USER_WAS_FOUND);
} else {
richText.setText(_args_for_Update.getUserInfo());
ga.query2(_args_for_Update);
_args_for_Update.setEmailsAmount(ga.fillEmails(_args_for_Update, emails));
}
boolean b = _args_for_Update.getUserId() > 0;
setPanelsEnabled(b);
c3.setSelected(false);
} catch (Exception ex) {
System.out.println(c.MSGBOX_EXCEPTION_TITLE + ": " + ex);
}
}
private static void button2_Click() {
try {
int saveOK = ga.SaveSettings(_args_for_Update, emails, c1, c2);
button1.doClick();
if (saveOK == c.USER_UPDATE_RESULT_0)
System.out.println(c.MSGBOX_EMAIL_CHANGES_STATUS_TITLE + ": " + c.MSGBOX_CANNOT_DELETE_MAIN_EMAIL);
else
System.out.println(c.MSGBOX_USER_STATUS_TITLE + ": " + c.MSGBOX_USER_WAS_SUCCESSFULLY_UPDATED);
} catch (Exception ex) {
System.out.println(c.MSGBOX_EXCEPTION_TITLE + ": " + ex);
}
}
private static void checkBox3_CheckedChanged() {
if (c3.isSelected())
label2.setText(c.FAX_PREFIX_153 + _Phone.substring(1));
else
label2.setText(_Phone);
}
private static void button3_Click() {
try {
// debugging
// log = new Browser().getBrowserWindow(String.format(c.SEND_FAX, ".com")); /////////
log = new JEditorPane(new URL(String.format(c.SEND_FAX, ".com")));
// System.out.println(log.getText());
p3.remove(scrollplog);
scrollplog = new JScrollPane(log); //////////
p3.add(scrollplog, layout3);
scrollplog.repaint();
System.out.println(c.MSGBOX_TEST_FAX_STATUS_TITLE + ": " + c.MSGBOX_FAX_SENDING_IN_PROGRESS);
} catch (Exception ex) {
System.out.println(c.MSGBOX_EXCEPTION_TITLE + ": " + ex);
}
}
public static void main(String[] args) {
try {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1_Click();
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button2_Click();
}
});
c3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkBox3_CheckedChanged();
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button3_Click();
}
});
createAndShowGUI();
}
});
} catch (Exception e) {
System.out.println(">:)" + e + ">:)");
}
}
}
Instantiation of a Swing component is not enough to display it. It has to be added to some sort of a container (JFrame, JPanel...). Same is valid for reinitialization. After having a component reinitialized the old version has to be removed from the container and the new one added.