What is the best layout in Java for scrolling text? - java

im trying to do a bar that show some messages and I got a trouble with it, check the image below to see what I have so far:
http://i.stack.imgur.com/xSMtY.png
So, in the top bar, i have a panel made by myself that contains labels, each message is a label and it will roll in the panel, the problem is when the message go out of the screen i want her to go to the end of the queue, but since im using BoxLayout in my made up JPanel i can't do it, in the white bar, i got the same layout and i get the same problem, i dont know how i can keep rooling without break the chain...
(In Java)
If anyone of you can help me i will be glad for it...
Thank you all in advance for your time :)
Edit: as requested i will post some code here:
this is my custom panel code:
package smstest;
import entidades.MensagemParaEcra;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import static java.lang.Thread.sleep;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* #author NEMESIS
*/
public class MyPanel extends JPanel {
private JLabel label;
//private MyPanel panel;
private LinkedList<String> texto;
private LinkedList<MensagemParaEcra> msgs;
private LinkedList<JLabel> labels;
private int x = 0, tamanho;
public MyPanel() {
texto = new LinkedList<>();
msgs = new LinkedList<>();
labels = new LinkedList<>();
//config panel
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.setBackground(Color.black);
Dimension dim = new Dimension(1500, 30);
tamanho = 1500;
this.setPreferredSize(dim);
this.repaint();
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
tamanho = MyPanel.this.getWidth();
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
});
// start the scrolling of the labels
start();
}
public void addMensagem(MensagemParaEcra msg) {
labels.add(new JLabel(msg.getTexto() + " -- "));
refresh();
}
public void removerMsg(int id) {
int size = msgs.size();
for (int i = 0; i < size; i++) {
if (msgs.get(i).getId() == id) {
msgs.remove(i);
}
}
refresh();
}
private void refresh() {
int size = labels.size();
labels.get(0).setLocation(0, 0);
for (int i = 0; i < size; i++) {
labels.get(i).setForeground(Color.white);
labels.get(i).setFont(new Font("Tahoma", Font.BOLD, 40));
labels.get(i).setOpaque(true);
labels.get(i).setBackground(Color.red);
MyPanel.this.add(labels.get(i));
// since im using a box layout it's useless but otherwise this
// may add my labels one after the other
if (i > 0) {
int largura = labels.get(i - 1).getWidth();
labels.get(i).setLocation(x + largura, 0);
} else {
labels.get(i).setLocation(x, 0);
}
}
}
private void start() {
final Runnable running = new Runnable() {
#Override
public void run() {
MyPanel.this.repaint();
}
};
Thread t = new Thread() {
public void run() {
while (true) {
for (JLabel lb : labels) {
// make the labels get 3 pixels to the left
lb.setLocation(lb.getLocation().x -3, 0);
}
try {
SwingUtilities.invokeAndWait(running);
sleep(30);
} catch (InterruptedException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
}
}
And this is the frame that have the 2 bars for the scrolling text:
package smstest;
import entidades.DadosDaAplicacao;
import entidades.MensagemParaEcra;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import static java.lang.Thread.sleep;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
*
* #author NEMESIS
*/
public final class MonitorDeMensagensFrame extends javax.swing.JFrame {
private static final MonitorDeMensagensFrame instance = new MonitorDeMensagensFrame();
private static Point point = new Point();
private int tamanho = 1500;
private JLabel label;
private JLabel label1;
/**
* Creates new form MonitorDeMensagensFrame
*/
public MonitorDeMensagensFrame() {
initComponents();
MyPanel topPanel = new MyPanel();
// its an undecorated frame so i have the listers to move it
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
Point p = getLocation();
setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
// setting the size of the frame
setSize(getRes().width, 73);
setLocation(0, 0);
PanelMsg.repaint();
// create the labels for the below bar
criarPub();
// add messages to the upper bar using a method in MyPanel
// this messages now are made up for tests
topPanel.addMensagem(new MensagemParaEcra(0, "msg 1"));
topPanel.addMensagem(new MensagemParaEcra(1, "msg 2"));
topPanel.addMensagem(new MensagemParaEcra(2, "msg 3"));
topPanel.addMensagem(new MensagemParaEcra(3, "msg 4"));
topPanel.addMensagem(new MensagemParaEcra(4, "msg 5"));
topPanel.addMensagem(new MensagemParaEcra(5, "msg 6"));
topPanel.addMensagem(new MensagemParaEcra(6, "msg 7"));
// start the rolling text on the below bar
startPub();
}
private Dimension getRes() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
// Get the current screen size
Dimension scrnsize = toolkit.getScreenSize();
return scrnsize;
}
/**
* This method is called from within the constructor to initialize 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() {
PanelMsg = new javax.swing.JPanel();
PanelPublicidade = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
getContentPane().setLayout(new java.awt.GridLayout(2, 0));
PanelMsg.setBackground(new java.awt.Color(255, 0, 0));
PanelMsg.setMinimumSize(new java.awt.Dimension(173, 20));
PanelMsg.setLayout(new java.awt.BorderLayout());
getContentPane().add(PanelMsg);
PanelPublicidade.setBackground(new java.awt.Color(102, 255, 102));
PanelPublicidade.setMinimumSize(new java.awt.Dimension(403, 25));
javax.swing.GroupLayout PanelPublicidadeLayout = new javax.swing.GroupLayout(PanelPublicidade);
PanelPublicidade.setLayout(PanelPublicidadeLayout);
PanelPublicidadeLayout.setHorizontalGroup(
PanelPublicidadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 806, Short.MAX_VALUE)
);
PanelPublicidadeLayout.setVerticalGroup(
PanelPublicidadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 26, Short.MAX_VALUE)
);
getContentPane().add(PanelPublicidade);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MonitorDeMensagensFrame().setVisible(true);
}
});
}
public static MonitorDeMensagensFrame getInstance() {
return instance;
}
public void criarPub() {
String msg = DadosDaAplicacao.getInstance().getMsgPublicidade();
PanelPublicidade.setLayout(new BoxLayout(PanelPublicidade, BoxLayout.X_AXIS));
PanelPublicidade.setBackground(Color.black);
Dimension dim = new Dimension(1500, 30);
PanelPublicidade.setPreferredSize(dim);
PanelPublicidade.repaint();
PanelPublicidade.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
tamanho = PanelMsg.getWidth();
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
});
label = new JLabel("");
label1 = new JLabel("");
label.setText(msg + " ");
label1.setText(msg + " ");
label.setForeground(Color.black);
label.setFont(new Font("Tahoma", Font.PLAIN, 40));
label.setOpaque(true);
label.setBackground(Color.white);
label1.setForeground(Color.black);
label1.setFont(new Font("Tahoma", Font.PLAIN, 40));
label1.setOpaque(true);
label1.setBackground(Color.white);
PanelPublicidade.add(label);
PanelPublicidade.add(label1);
label.setLocation(PanelPublicidade.getLocation().x, PanelPublicidade.getLocation().y);
label1.setLocation(label.getWidth(), label.getLocation().y);
PanelPublicidade.repaint();
}
public void startPub() {
final int tamanho = label.getWidth();
final Runnable running = new Runnable() {
#Override
public void run() {
PanelPublicidade.repaint();
}
};
Thread t = new Thread() {
#Override
public void run() {
while (true) {
label.setLocation(label.getLocation().x - 3,0);
label1.setLocation(label1.getLocation().x - 3, 0);
// if(label.getLocation().x + tamanho == 0){
// label.setLocation(label1.getLocation().x, 0);
// }
try {
SwingUtilities.invokeAndWait(running);
sleep(28);
} catch (InterruptedException ex) {
Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
}
// Variables declaration - do not modify
private javax.swing.JPanel PanelMsg;
private javax.swing.JPanel PanelPublicidade;
// End of variables declaration
}
There is the code...
Thank you for the help :)

Related

Simple Output Prints Twice to JTextArea in Java

I was wondering why the JTextArea prints the same line twice. Im using multithreading and im new to this concept. I was wondering if that's where the issue is. As of looking it over I tried seeing if any run methods were called twice to cause such a thing. There aren't any loops in the code either. The line that says "Prints twice?" in the GameThread class is where the issue starts. Thanks for help.
Main Menu Class
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.awt.event.ActionEvent;
public class MainMenu {
private JFrame menu;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu window = new MainMenu();
window.menu.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public MainMenu() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
menu = new JFrame();
menu.getContentPane().setBackground(Color.BLACK);
menu.setTitle("Zombie Game");
menu.setBounds(100, 100, 574, 374);
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.getContentPane().setLayout(null);
JButton btnPlay = new JButton("Play");
// button action on click
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
GameScreen enterGame = new GameScreen();
menu.setVisible(false);
enterGame.run();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Zombie Survival");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 40));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(118, 34, 381, 73);
menu.getContentPane().add(lblNewLabel);
btnPlay.setBackground(Color.WHITE);
btnPlay.setForeground(Color.RED);
btnPlay.setFont(new Font("Tahoma", Font.BOLD, 17));
btnPlay.setToolTipText("Click to begin.");
btnPlay.setBounds(225, 190, 118, 54);
menu.getContentPane().add(btnPlay);
}
}
Game Board
import java.awt.EventQueue;
import java.io.PrintStream;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import java.awt.Font;
import javax.swing.JScrollPane;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GameScreen {
private JFrame gameFrm;
/**
* Launch the application.
*/
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GameScreen window = new GameScreen();
window.gameFrm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws InterruptedException
*/
public GameScreen() throws InterruptedException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws InterruptedException
*/
private void initialize() throws InterruptedException {
gameFrm = new JFrame();
gameFrm.getContentPane().setBackground(Color.BLACK);
gameFrm.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 478, 718, 134);
gameFrm.getContentPane().add(scrollPane);
JTextArea displayTextArea = new JTextArea();
displayTextArea.setLineWrap(true);
displayTextArea.setWrapStyleWord(true);
displayTextArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
});
scrollPane.setViewportView(displayTextArea);
displayTextArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
displayTextArea.setForeground(Color.WHITE);
displayTextArea.setBackground(Color.BLACK);
PrintStream printStream = new PrintStream(new CustomOutputStream(displayTextArea));
System.setOut(printStream);
JLabel forestPicture = new JLabel("New label");
forestPicture.setIcon(new ImageIcon("C:\\Users\\fstal\\Documents\\Java Programs\\UpdatedZombieGame\\src\\gameForest.jpg"));
forestPicture.setBounds(0, 0, 738, 622);
gameFrm.getContentPane().add(forestPicture);
gameFrm.setBackground(Color.WHITE);
gameFrm.setTitle("Zombie Game");
gameFrm.setBounds(100, 100, 752, 659);
gameFrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Game work
GameThread gThread = new GameThread();
gThread.start();
}
}
Thread Class
public class GameThread extends Thread {
static String [] zombies = {"Zombie", "Fast Zombie", "Big Zombie", "Crawler"};
static String [] bag = {"Assault Rifle", "SMG", "Shotgun", "Sniper"};
static int [] zHealth = {100, 90, 200, 50};
static int [] damage = {90, 80, 100, 200};
static int playerHealth = 50;
public void run() {
try {
System.out.println("Zombies are coming!");
//Thread.sleep(2000);
System.out.println("Prints twice?");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CustomOutputStream Class for TextArea
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
public class CustomOutputStream extends OutputStream {
private JTextArea displayTextArea;
CustomOutputStream(JTextArea textArea) {
this.displayTextArea = textArea;
}
#Override
public void write(int b) throws IOException {
// redirects data to the text area
displayTextArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
displayTextArea.setCaretPosition(displayTextArea.getDocument().getLength());
}
}
You're creating two instance of the GameScreen, so your output get's printed twice
When you perform...
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
GameScreen enterGame = new GameScreen();
menu.setVisible(false);
enterGame.run();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
It calls the GameScreen constructor, which calls initialize()
/**
* Create the application.
*
* #throws InterruptedException
*/
public GameScreen() throws InterruptedException {
initialize();
}
And when you call run, it does it again...
/**
* Launch the application.
*/
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GameScreen window = new GameScreen();
window.gameFrm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You really don't need to do this again in run.
Now that we've discussed that problem, you have a number of other issues.
Firstly, Swing is NOT thread safe and you should never modify the UI (or anything the UI relies on) from outside the context of the Event Dispatching Thread.
See Concurrency in Swing for some more details (and possible solutions)
Second, null layouts are generally a bad idea - it made a mess of your UI on my PC. You should really take the time to learn how to use the various layout managers available in the API - see Laying Out Components Within a Container

How to Run TimerTask behind JFrame in java

I have a problem with the application (GUI JFrame form Class) that I created, I am trying to run a method that contains commands to perform data scanning using java.util.TimerTask. The method I want to run through JCheckBoxMenuItem and will run if I tickcheckBoxMenuItem. The problem is that when I check 'checkBoxMenuItem`, scan method still running but I can not access JFrame (GUI) again.
import Database.KoneksiDatabase2;
import Design.ClButtonTransparan;
import Design.JPanelWithImage;
import Proses.Data.DebitDiberikan;
import Proses.Data.DebitKebutuhan;
import Proses.Data.DebitTersedia;
import Proses.Data.AutoScanNReply;
import Proses.Data.CurahHujan;
import Proses.Data.DataKirim;
import Proses.Data.DataMasuk;
import Proses.Data.Faktor_K;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.util.Timer;
public class FormPAI extends javax.swing.JFrame {
private JPanel contentPane, panel1, panelJam;
private JLabel lbtotQs, lbtotQb, lbtotQa, lbfaktorK, lbQa1, lbQa2, lbQa3;
private JLabel lbQa4, lbQa5, lbQa6, lbQa7, lbQa8, lbQa9, lbQa10, lbQa11;
private JLabel lbQa12, lbQb1, lbQb2, lbQb3, lbQb4, lbQb5, lbQb6, lbQb7;
private JLabel lbQb8, lbQb9, lbQb10, lbQb11, lbQb12, lbTotQ;
private JButton btn1, btn2, btn3, btn4, btn5, btn6;
//public Timer timer2 = null;
private JPopupMenu popUp;
private JMenuItem tulisPesan, inbox, kotakKeluar, pesanTerkirim;
ActionListener aksi, aksiTulisPesan, aksiInbox, aksikotakKeluar, aksiPesanTerkirim;
private Timer timer;
public FormPAI() throws IOException, SQLException {
initComponents();
setTitle("Pembagian Air Irigasi");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 650);
BufferedImage img = ImageIO.read(new File("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\bacground3.jpg"));
contentPane = new JPanelWithImage(img);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setLocationRelativeTo(null);
btnClose();
BufferedImage imgSkema = ImageIO.read(new File("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\baturiti3.png"));
panel1 = new JPanelWithImage(resize(imgSkema, 670, 420));
panel1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel1.setBounds(5, 115, 680, 425);
contentPane.add(panel1);
ClockLabel dateLable = new ClockLabel("date");
ClockLabel timeLable = new ClockLabel("time");
// ClockLabel dayLable = new ClockLabel("day");
panelJam = new JPanel();
panelJam.setBounds(545, 541, 140, 55);
panelJam.setBackground(Color.black);
panelJam.add(timeLable);
panelJam.add(dateLable);
// panelJam.add(dayLable);
contentPane.add(panelJam);
jCheckBoxMenuItem1.setText("Run Gammu");
jCheckBoxMenuItem1.setSelected(false);
jCheckBoxMenuItem1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Checked? " + jCheckBoxMenuItem1.isSelected());
int state = e.getStateChange();
if (state == ItemEvent.SELECTED){
try {
scan();
} catch (SQLException ex) {
Logger.getLogger(FormPAI.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
timer.cancel();
}
}
});
}
public void scan() throws SQLException{
java.util.TimerTask task = new java.util.TimerTask() {
DebitKebutuhan dk = new DebitKebutuhan();
#Override
public void run(){
System.out.println("ajik");
DataMasuk obj = new DataMasuk();
DataKirim dkrm = new DataKirim();
CurahHujan ch = new CurahHujan();
String cek = null, processed="";
try {
Connection c = KoneksiDatabase2.getKoneksiDBSMS();
ResultSet rset = c.prepareStatement("SELECT * FROM inbox WHERE Processed='false'").executeQuery();
while (rset.next()){
cek = rset.getString("ID");
processed = rset.getString("Processed");
}
if (cek != null){
obj.ambilTeksPesan();
obj.cekFormatPesan();
if (obj.formatSMS == true && processed.equals("false")){
obj.ambilDataPesan();
obj.simpanPesan_ke_DB();
obj.sendToDataMasuk();
obj.updateDataMasuk();
ch.simpanCHKeDB();
dkrm.sendToOutbox();
obj.tandaiSudahDibalas(cek);
}
}
rset.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
timer = new Timer(true);// true to run timer as daemon thread
timer.schedule(task, 0, 5000);// Run task every 5 second
try {
Thread.sleep(60000*60); // Cancel task after 1 minute.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
public final void btnClose(){
ImageIcon idt = new ImageIcon("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\exit.png");
Image imgRoll = idt.getImage();
Image newImgRoll = imgRoll.getScaledInstance(65, 65, 100);
ImageIcon icon = new ImageIcon("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\shutdown.png");
Image img = icon.getImage();
Image newimg = img.getScaledInstance(65, 65, 100);
btn6 = new ClButtonTransparan("<html><center>"+"KELUAR"+"</center></html>");
btn6.setFont(new Font("Berlin Sans FB Demi", Font.PLAIN,12));
btn6.setBounds(555, 5, 105, 105); // posisi jbutton (x, y) dan ukurunnnya (lebar, tinggi)
btn6.setIcon(new ImageIcon(newimg));
btn6.setRolloverIcon(new ImageIcon (newImgRoll));
btn6.setVerticalTextPosition(SwingConstants.BOTTOM); //membuat text jbutton berada dibawah
btn6.setHorizontalTextPosition(SwingConstants.CENTER); //membuat text jbutton berada ditengah
contentPane.add(btn6);
btn6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//JOptionPane.showConfirmDialog(rootPane, menuBar);
System.exit(0);
}
});
}
/**
* This method is called from within the constructor to initialize 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() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");
jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jCheckBoxMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jCheckBoxMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormPAI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try{
FormPAI frame = new FormPAI();
frame.setVisible(true);
//frame.scan();
}catch(Exception e){
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}
class ClockLabel extends JLabel implements ActionListener {
String type;
SimpleDateFormat sdf;
public ClockLabel(String type) {
this.type = type;
setForeground(Color.green);
switch (type) {
case "day" : sdf = new SimpleDateFormat("EEEE ");
setFont(new Font("Digital-7", Font.PLAIN, 14));
setHorizontalAlignment(SwingConstants.RIGHT);
break;
case "time" : sdf = new SimpleDateFormat("hh:mm a");
setFont(new Font("sans-serif", Font.PLAIN, 16));
setHorizontalAlignment(SwingConstants.CENTER);
break;
case "date" : sdf = new SimpleDateFormat("dd MMMM yyyy");
setFont(new Font("sans-serif", Font.PLAIN, 20));
setHorizontalAlignment(SwingConstants.CENTER);
break;
default : sdf = new SimpleDateFormat();
break;
}
javax.swing.Timer t = new javax.swing.Timer(1000, this);
t.start();
}
#Override
public void actionPerformed(ActionEvent ae) {
Date d = new Date();
setText(sdf.format(d));
}
}
The problem is that you are putting the UI thread to sleep, and it looks like you are sleeping for longer than you think you are... 60000 * 60 = one hour!
public void scan() throws SQLException{
java.util.TimerTask task = new java.util.TimerTask() {
// ...
};
timer = new Timer(true);// true to run timer as daemon thread
timer.schedule(task, 0, 5000);// Run task every 5 second
try {
//--------------------------------------------------
// This is putting the UI to sleep for an hour!
//--------------------------------------------------
Thread.sleep(60000*60); // Cancel task after 1 minute. <-- NOT 1 minute!
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
You should try to get all of that business onto a separate thread. It could be done like this:
public void scan() throws SQLException{
Runnable scanRunner = new Runnable() {
public void run() {
java.util.TimerTask task = new java.util.TimerTask() {
// ...
};
timer = new Timer(true);// true to run timer as daemon thread
timer.schedule(task, 0, 5000);// Run task every 5 second
try {
Thread.sleep(1000*60); // Cancel task after 1 minute.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
};
new Thread(scanRunner).start();
}
As a side note, there are likely a lot of other issues doing it this way since you could check/uncheck the box in the UI at your leisure, and it would not stop any previous scan tasks... I'll let you manage that situation yourself, or ask a different question.

Swing Components invisible

When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});

set focus to JList and have cursor on textField swing java autocomplete

I started to develop my own auto complete swing component and I want to set focus to the list when user press up or down keys and in the same time let the cursor on the textfield to allow him to type text or number....
to set focus to JList when typing up or down I have used
list.requestFocus();
is there any way to have focus on JList and cursor on JTextField
please view the image in here
here my code :
package examples.autocomplete;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import com.gestioncaisse.dao.ClientDAO;
import com.gestioncaisse.dao.DAO;
import com.gestioncaisse.dao.MyConnection;
import com.gestioncaisse.pojos.Client;
import com.gestioncaisse.utils.utils;
public class testcombo extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
final DAO<Client> clientDao;
List<Client> list_clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testcombo frame = new testcombo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
boolean first_time = true;
/**
* Create the frame.
*/
public testcombo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
clientDao = new ClientDAO(MyConnection.getInstance());
list_clients = clientDao.findAll();
textField = new JTextField();
textField.setBounds(5, 11, 113, 20);
textField.setColumns(10);
final JButton btnNewButton = new JButton("...");
btnNewButton.setBounds(116, 10, 45, 23);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 31, 156, 144);
final JList list = new JList(
utils.fromListToObjectTable2Clients(list_clients));
scrollPane.setViewportView(list);
list.setVisibleRowCount(5);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentPane.add(scrollPane);
contentPane.add(textField);
contentPane.add(btnNewButton);
textField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
int a = list.getSelectedIndex();
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
list.requestFocus();
} else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
list.requestFocus();
} else if (!first_time) {
} else {
first_time = false;
}
}
#Override
public void keyPressed(KeyEvent arg0) {
}
});
}
}
//if (a > 0)
//list.setSelectedIndex(a - 1);
//int first_vis = list.getFirstVisibleIndex();
//list.setListData(utils.fromListToObjectTable2Clients(clientDao.findByString(textField.getText())));
//list.setSelectedIndex(0);
Leave the focus on the JTextField but add KeyBindings to the UP/DOWN key. In the actions just change selection in JList (public void setSelectedIndex(int index) method)
UPDATE
An aslternative way would be to have focus on JList and add KeyListener translating typed chars to the JTextField. To Show caret use
jTextFieldInstance.getCaret().setVisible(true);
jTextFieldInstance.getCaret().setSelectionVisible(true);
Here i used to retrieve matched data from database
keywordssearcher.setEditable(true);
final JTextComponent sfield = (JTextComponent) keywordssearcher.getEditor().getEditorComponent();
sfield.setVisible(true);
sfield.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
comboFilter(sfield.getText(), con);
}
});
}
#Override
public void keyPressed(KeyEvent e) {
if (!(sfield.getText().equals("")) || (sfield.getText() == null)) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
addKeyWord(sfield.getText().toString());
}
}
}
});
public void comboFilter(String enteredText, Connection ncon) {
log.info("ncon autosuggest--->" + ncon);
ArrayList<String> filterArray = new ArrayList<String>();
String str1 = "";
try {
Statement stmt = dc.ConnectDB().createStatement();
String str = "SELECT k_word FROM T_KeyWords WHERE k_word LIKE '" + enteredText + "%'";
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
str1 = rs.getString("k_word");
filterArray.add(str1);
con.close();
}
} catch (Exception ex) {
log.error("Error in getting keywords from database" + ex.toString());
JOptionPane.showMessageDialog(null, "Error in getting keywords from database" + ex.toString());
}
if (filterArray.size() > 0) {
keywordssearcher.setModel(new DefaultComboBoxModel(filterArray.toArray()));
keywordssearcher.setSelectedItem(enteredText);
keywordssearcher.showPopup();
} else {
keywordssearcher.hidePopup();
}
}
Here my keywordssearcher(jcombobox) is editable and the entered value can be added directly into the database.
use this as a reference and modify the code

JInternalFrame change background color (Nimbus L&F)

I'm using the Nimbus L&F and trying to change the background color. I'm setting the color with this: iFrame.getContentPane().setBackground(Color.BLACK);. However it ends up with a small area at the top with the default color. And even worse. If I re-size the JInternalFrame this area changes it color from a darker gray into a lighter one. I searched for this problem and at least i figured out that it has to be a problem caused by the title bar.
Picture of the JInternalFrame
Is there a way to solve this problem? Is this a known bug? Thank you.
Edit:
A small programm, where it happens.
Following line causes the problem: ret.put("defaultFont", new Font("Arial", Font.BOLD, 16)); Is this the wrong way to set the default font ?
package jInternalFrameTest;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
public class JInternalFrameTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JInternalFrameTest() {
super("JInternalFrame Background Demo");
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height - inset * 2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
createGUI();
}
private void createGUI() {
MyInternalFrame frame = new MyInternalFrame();
frame.setVisible(true);
this.getLayeredPane().add(frame, JLayeredPane.DRAG_LAYER);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel(){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public UIDefaults getDefaults() {
UIDefaults ret = super.getDefaults();
ret.put("defaultFont", new Font("Arial", Font.BOLD, 16));
return ret;
}
});
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
}
new JInternalFrameTest().setVisible(true);
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
class MyInternalFrame extends JInternalFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public MyInternalFrame() {
super("IFrame", true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(300, 300);
getContentPane().setBackground(Color.BLACK);
pack();
}
}
}

Categories