No items are displayed in the Palette in Eclipse oxygen - java

I am using Eclipse for RCP and RAP Developers (Oxygen). Upon opening palette it is empty. Even though I have my code in edit mode in the source tab.
In the below image palette is empty
As Suggested added the code below.
On opening the Design tab, the palette is empty.
package com.jcg.rca.main;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
//import org.eclipse.wb.swt.SWTResourceManager;
public class MainWindow {
protected Shell shlLogin;
private Text userNameTxt;
private Text passwordTxt;
private String userName = null;
private String password = null;
/**
* Launch the application.
*
* #param args
*/
public static void main(String[] args) {
try {
MainWindow window = new MainWindow();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shlLogin.open();
shlLogin.layout();
while (!shlLogin.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shlLogin = new Shell(SWT.CLOSE | SWT.TITLE | SWT.MIN);
shlLogin.setSize(450, 300);
shlLogin.setText("Login");
CLabel label = new CLabel(shlLogin, SWT.NONE);
//label.setImage(SWTResourceManager.getImage(MainWindow.class, "/com/jcg/rca/main/eclipse_logo.png"));
label.setBounds(176, 10, 106, 70);
label.setText("");
Label lblUsername = new Label(shlLogin, SWT.NONE);
lblUsername.setBounds(125, 115, 55, 15);
lblUsername.setText("Username");
Label lblPassword = new Label(shlLogin, SWT.NONE);
lblPassword.setBounds(125, 144, 55, 15);
lblPassword.setText("Password");
userNameTxt = new Text(shlLogin, SWT.BORDER);
userNameTxt.setBounds(206, 109, 173, 21);
passwordTxt = new Text(shlLogin, SWT.BORDER | SWT.PASSWORD);
passwordTxt.setBounds(206, 144, 173, 21);
Button btnLogin = new Button(shlLogin, SWT.NONE);
btnLogin.setBounds(206, 185, 75, 25);
btnLogin.setText("Login");
btnLogin.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
userName = userNameTxt.getText();
password = passwordTxt.getText();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
String errorMsg = null;
MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_ERROR);
messageBox.setText("Alert");
if (userName == null || userName.isEmpty()) {
errorMsg = "Please enter username";
} else if (password == null || password.isEmpty()) {
errorMsg = "Please enter password";
}
if (errorMsg != null) {
messageBox.setMessage(errorMsg);
messageBox.open();
}
} else {
MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_WORKING);
messageBox.setText("Info");
messageBox.setMessage("Valid");
messageBox.open();
}
}
});
}}
.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................

JUST CREATE A SIMPLE JAVA PROJECT.
Then I used the Swing > JFrame for the class.
DONT create the project from the one under WindowsBuilder.

Right click on palette box
Then select restore default palette

Related

Java adding type writer effect that does not halt the entire program

I have looked around for a while to add a system which delays the GUI text area only but to no avail, so far I have this:
public void msg2(String msg) {
for (int i = 0; i < msg.length(); i++) {
mainTextController.append(Character.toString(msg.charAt(i)));
try {
Thread.sleep(45);
} catch (Exception ex) {
ex.printStackTrace();
}
}
mainTextController.append("\n");
}
the problem here is that whenever i run this method it works and the type-writer effect is there, but, the entire program halts until the sleep method is over.
I have tried BlockingQueue but the same results are shown.
I am not looking to be spoon fed just some insight on how can I overcome this problem.
this is the entire class:
package gui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
public class LabyrinthGUI {
protected Shell shell;
private Text mainTextController;
/**
* Launch the application.
*
* #param args
*/
public static void main(String[] args) {
try {
LabyrinthGUI window = new LabyrinthGUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
Display display;
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
Button btnGoNorth;
protected void createContents() {
shell = new Shell();
shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
shell.setSize(600, 700);
shell.setText("Murat's Labyrinth - v0.1");
mainTextController = new Text(shell, SWT.READ_ONLY | SWT.WRAP);
mainTextController.setDragDetect(false);
mainTextController.setDoubleClickEnabled(false);
mainTextController.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_ARROW));
mainTextController.setEditable(false);
mainTextController.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
mainTextController.setForeground(SWTResourceManager.getColor(SWT.COLOR_YELLOW));
mainTextController.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
mainTextController.setBounds(10, 10, 564, 535);
btnGoNorth = new Button(shell, SWT.BORDER);
btnGoNorth.setSelection(true);
btnGoNorth.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
msg2("You clicked here");
}
});
btnGoNorth.setGrayed(true);
btnGoNorth.setTouchEnabled(true);
btnGoNorth.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoNorth.setBounds(227, 551, 75, 25);
btnGoNorth.setText("Go North");
Button btnGoSouth = new Button(shell, SWT.BORDER);
btnGoSouth.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
btnGoSouth.setText("Go South");
btnGoSouth.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoSouth.setBounds(227, 626, 75, 25);
Button btnGoWest = new Button(shell, SWT.BORDER);
btnGoWest.setText("Go West");
btnGoWest.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoWest.setBounds(134, 587, 75, 25);
Button btnGoEast = new Button(shell, SWT.BORDER);
btnGoEast.setText("Go East");
//btnGoEast.setCursor(new Cursor());
btnGoEast.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoEast.setBounds(328, 587, 75, 25);
}
public void lock() {
btnGoNorth.setEnabled(false);
}
public void unlock() {
btnGoNorth.setEnabled(true);
}
public void msg2(String msg) {
for (int i = 0; i < msg.length(); i++) {
mainTextController.append(Character.toString(msg.charAt(i)));
try {
Thread.sleep(45);
} catch (Exception ex) {
ex.printStackTrace();
}
}
mainTextController.append("\n");
}
}
the entire program halts until the sleep method is over.
Don't use Thread.sleep().
Instead you should be using a Swing Timer for animation.
Read the section from the Swing tutorial on How to Use Swing Timers for more information and working examples.

How to attribute sound through array and play it using Jbutton?

I'm currently working on a Magic8Ball game, very basic, although I did change it to a genie theme, and now I've decided to add sound to the game.
Basically I have prepared the reading of the answers and saved them as an audio file (mp3), and I want to attribute each voice over to the appropriate array string.
So if the voice reading says "as I see it, yes" it should be linked to array[0] which contains that answer. So ultimately, I want the game to say the answers to the player as it displays the answer.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class CompSays02GUI extends JFrame {
public static void main(String[] args) {
//set look and feel for UI as deault operating system look
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//start the program
new CompSays02GUI().setVisible(true);
}
public CompSays02GUI() {
setTitle("Genie Game");
setSize(725, 525);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addComponents();
}
private void addComponents() {
MainPanel background = new MainPanel();
add(background, BorderLayout.CENTER);
}
private class MainPanel extends JPanel implements ActionListener {
private JTextField question;
private JButton ask;
private JButton exit;
private JLabel result;
/**
* Initialize MainPanel
*/
public MainPanel() {
setLayout(null); // set to free layout
addComponents();
}
/**
* Add components to JPanel
*/
private void addComponents() {
//question text field
question = new JTextField();
question.setForeground(Color.BLUE); //set the foreground color
question.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16)); // set the font
question.setBounds(100, 120, 250, 33); // set location, width and height
add(question);
//ask button
ask = new JButton("Ask");
ask.addActionListener(this); // add action listener to handle button click
ask.setBackground(Color.BLUE); // set background color
ask.setForeground(Color.WHITE); // set text color
ask.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); // set font
ask.setBounds(400, 120, 80, 33); // set location, width and height
add(ask);
//exit button
exit = new JButton("Exit");
exit.addActionListener(this);
exit.setBackground(Color.RED);
exit.setForeground(Color.WHITE);
exit.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));
exit.setBounds(500, 120, 80, 33);
add(exit);
//result label
result = new JLabel();
result.setForeground(Color.BLACK);
result.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 22));
result.setBounds(250, 200, 400, 33);
add(result);
}
/**
* Paint the image in background
*
* #param g Graphics
*/
#Override
public void paintComponent(Graphics g) {
try {
super.paintComponents(g);
//read the image
Image img = ImageIO.read(new File("resources/genie.png"));
//draw in background of panel
g.drawImage(img, 0, 0, null);
} catch (IOException ex) { // else if image not found, print error
System.out.println("Error: Image 'genie.png' not found");
System.out.println(ex.getMessage());
}
}
/**
* Handle the ask and exit buttons clicks
*
* #param e ActionEvent
*/
#Override
public void actionPerformed(ActionEvent e) {
// if ask button clicked
if (e.getSource() == ask) {
//get question
String ques = question.getText();
//if it's empty
if (ques.isEmpty()) {
JOptionPane.showMessageDialog(this, "Error: Your question "
+ "was not stated as a yes or no. Try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
//check the question and continue else if it's valid
if (questionCheck(ques)) {
result.setText(printResult(ques));
}
}
// if exit button clicked
if (e.getSource() == exit) {
//print message
JOptionPane.showMessageDialog(this, "Thanks for playing!\n\n");
}
}
/**
* Check else if the question is valid
*
* #param ques String
* #return boolean
*/
private boolean questionCheck(String ques) {
// They have a valid question
boolean result = true;
//else if it's not yes/no question
if (ques.indexOf("who") != -1 || ques.indexOf("what") != -1
|| ques.indexOf("why") != -1 || ques.indexOf("which") != -1
|| ques.indexOf("how") != -1 || ques.indexOf("When") != -1
|| ques.indexOf("whats") != -1 || ques.indexOf("what's") != -1) {
result = false;
JOptionPane.showMessageDialog(this, "Error: Your question was "
+ "not stated as a yes or no. Try again.", "Error",
JOptionPane.ERROR_MESSAGE);
}
return result;
}
/**
* Generate random number from 1-20 and return the result answer
*
* #return String
*/
private String printResult(String ques) {
String[] answers = new String [20];
answers[0] = "As i see it, yes";
answers[1] = "It is certain";
answers[2] = "It is decidedly so";
answers[3] = "Most Likely";
answers[4] = "Outlook looking good";
answers[5] = "Sign points to yes";
answers[6] = "Without a doubt";
answers[7] = "Yes";
answers[8] = "Yes, definitely";
answers[9] = "You shouldn't rely on it";
answers[10] = "Reply hazy, try again";
answers[11] = "Try again later";
answers[12] = "Better not tell you now";
answers[13] = "Cannor predict now";
answers[14] = "Concentrate and ask again";
answers[15] = "Don't count on it";
answers[16] = "My reply is... NO!";
answers[17] = "My sources say no";
answers[18] = "Outlook not so good";
answers[19] = "Very doubtful";
Random nexGen = new Random();
int nextAnswer = nexGen.nextInt(answers.length);
return answers[nextAnswer];
}
}
Please help.
Thanks.
Simple example for playing a sound:
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.*;
class SoundTest {
public static void main(String[] args) throws Exception {
URL urlToSound = new URL("file:c:/java/gun1.wav");
// URL urlToSound = new URL("file:c:/java/flyby1.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(urlToSound);
final Clip clip = AudioSystem.getClip();
clip.open(ais);
JButton button = new JButton("Play Sound");
button.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
clip.setFramePosition(0);
clip.start();
}
} );
JOptionPane.showMessageDialog(null, button);
}
}

java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver

I have java source,and when I run,it writes
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver
I thinks it is needed ODBC driver,but I can't see it.
Java source code:
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.event.*;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class a extends javax.swing.JDialog {
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JTextField txtPiradi;
private JTextField txtSaxeli;
private JTextField txtGvari;
Image img;
File file = null;
String path = "";
JTextField text = new JTextField(20);
JButton browse, save;
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
/**
* Auto-generated main method to display this JDialog
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
wevrtaDamateba inst = new wevrtaDamateba(frame);
inst.setVisible(true);
}
});
}
public wevrtaDamateba(JFrame frame) {
super(frame);
initGUI();
}
private void initGUI() {
try {
{
getContentPane().setLayout(null);
this.setTitle("\u10d0\u10ee\u10d0\u10da\u10d8 \u10ec\u10d4\u10d5\u10e0\u10d8\u10e1 \u10d3\u10d0\u10db\u10d0\u10e2\u10d4\u10d1\u10d0");
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("\u10e1\u10d0\u10ee\u10d4\u10da\u10d8:");
jLabel1.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel1.setBounds(78, 21, 60, 40);
}
{
jLabel2 = new JLabel();
getContentPane().add(jLabel2);
jLabel2.setText("\u10d2\u10d5\u10d0\u10e0\u10d8:");
jLabel2.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel2.setBounds(78, 67, 60, 40);
}
{
jLabel3 = new JLabel();
getContentPane().add(jLabel3);
jLabel3.setText("\u10de\u10d8\u10e0\u10d0\u10d3\u10d8 N:");
jLabel3.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel3.setBounds(78, 112, 60, 40);
}
{
jLabel4 = new JLabel();
getContentPane().add(jLabel4);
jLabel4.setText("\u10e1\u10e3\u10e0\u10d0\u10d7\u10d8:");
jLabel4.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel4.setBounds(78, 152, 60, 40);
}
{
txtSaxeli = new JTextField();
getContentPane().add(txtSaxeli);
txtSaxeli.setBounds(161, 28, 180, 23);
}
{
txtGvari = new JTextField();
getContentPane().add(txtGvari);
txtGvari.setBounds(161, 74, 180, 23);
}
{
txtPiradi = new JTextField();
getContentPane().add(txtPiradi);
txtPiradi.setBounds(161, 119, 180, 23);
}
{
browse = new JButton();
getContentPane().add(browse);
browse.setText("\u10e1\u10e3\u10e0\u10d0\u10d7\u10d8\u10e1 \u10d0\u10e0\u10e9\u10d4\u10d5\u10d0");
browse.setBounds(161, 159, 180, 23);
browse.setFont(new java.awt.Font("Sylfaen",0,12));
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(new ImageFileFilter());
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
path = file.getPath();
ImageIcon icon = new ImageIcon(path);
// label.setIcon(icon);
text.setText(path);
repaint();
}
}
});
}
{
save = new JButton();
getContentPane().add(save);
save.setText("\u10d3\u10d0\u10db\u10d0\u10e2\u10d4\u10d1\u10d0");
save.setBounds(173, 224, 123, 23);
save.setFont(new java.awt.Font("Sylfaen",0,12));
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
File f = new File(path);
String saxeli = txtSaxeli.getText();
String gvari = txtGvari.getText();
int piradi = Integer.parseInt(txtPiradi.getText());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Base","","");
PreparedStatement psmnt = conn
.prepareStatement("insert into user('saxeli','gvari','piradi','img') values (?,?,?,?)");
FileInputStream fis = new FileInputStream(f);
psmnt.setString(1, saxeli);
psmnt.setString(2, gvari);
psmnt.setInt(3, piradi);
psmnt.setBinaryStream(4, (InputStream) fis,
(int) (f.length()));
int s = psmnt.executeUpdate();
JOptionPane.showMessageDialog(null,
"Inserted successfully!");
} catch (Exception ex) {
System.out.print(ex);
}
}
});
}
}
this.setSize(665, 346);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void clear() {
// TODO Auto-generated method stub
}
class ImageFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
if (file.isDirectory())
return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".jpg") || name.endsWith(".png") || name
.endsWith(".gif"));
}
public String getDescription() {
return "Images (*.gif,*.bmp, *.jpg, *.png )";
}
}
}
Check whether you have Base ODBC DataSource in your ODBC DataSource Panel.

FileDialog and Composite

I am trying to create a browse button with FileDialog and composite in Java SWT. (Composite because, I am use CTabFolder and CTabItem. I felt to add components to CTabItem composite is good enough)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.custom.CBanner;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.wb.swt.SWTResourceManager;
public class DemoShell extends Shell {
protected Composite composite;
private Text filename;
private Table table;
protected Shell shell;
public static void main(String args[]) {
try {
Display display = Display.getDefault();
DemoShell shell = new DemoShell(display);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean parseFile(Table table, String filename) {
try {
BufferedReader br = new BufferedReader( new FileReader(filename) );
String line = "";
StringTokenizer token = null, subtoken = null;
int tokenNum = 1;
while((line = br.readLine()) != null) {
// lineNum++;
// break comma separated file line by line
token = new StringTokenizer(line, ";");
String sno = null;
while(token.hasMoreTokens()) {
subtoken = new StringTokenizer(token.nextToken().toString(), ",");
sno = "";
sno = Integer.toString(tokenNum);
TableItem item = new TableItem (table, SWT.NONE);
item.setText (0, sno );
item.setText (1, subtoken.nextToken());
item.setText (2, subtoken.nextToken());
item.setText (3, subtoken.nextToken());
item.setText (4, subtoken.nextToken());
item.setText (5, subtoken.nextToken());
tokenNum++;
System.out.println("S.No # " + tokenNum + token.nextToken());
}
tokenNum = 0;
}
br.close();
return true;
} catch(Exception e) {
System.err.println("Parse Error: " + e.getMessage());
return false;
}
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
filename.setText(files[i]);
filename.setEditable(false);
}
}
/**
* Create the shell.
* #param display
*/
public DemoShell(Display display) {
super(display, SWT.SHELL_TRIM);
TabFolder tabFolder = new TabFolder(this, SWT.NONE);
tabFolder.setBounds(10, 10, 462, 268);
TabItem re_item = new TabItem(tabFolder, SWT.NONE);
re_item.setText("Road Network");
TabItem ttable_item = new TabItem(tabFolder, SWT.NONE);
ttable_item.setText("Time Table");
createContents_tt(tabFolder, ttable_item );
}
/**
* Create contents of the shell.
*/
protected void createContents_tt(TabFolder tabFolder, TabItem ttable_item) {
setText("SWT Application");
setSize(530, 326);
//Table declaration
table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
table.setBounds(10, 153, 450, 107);
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = {"S.No", "Route", "Transport #", "Cross Point", "Start Time", "End Time"};
for (int i=0; i<titles.length; i++) {
TableColumn column = new TableColumn (table, SWT.NONE);
column.setText (titles [i]);
}
for (int i=0; i<titles.length; i++) {
table.getColumn (i).pack ();
}
Composite composite = new Composite(tabFolder, SWT.NONE);
composite.setLayout(new FillLayout());
Group group_1 = new Group(shell, SWT.NONE);
group_1.setBounds(10, 10, 450, 127);
filename = new Text(group_1, SWT.BORDER);
filename.setBounds(31, 95, 377, 21);
filename.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
Group group = new Group(group_1, SWT.NONE);
group.setBounds(81, 46, 245, 43);
Label lblEitherBrowseFor = new Label(group_1, SWT.NONE);
lblEitherBrowseFor.setBounds(10, 19, 430, 21);
lblEitherBrowseFor.setText("Either Browse for a file or Try to upload the time table data through Manual entry");
Button btnManual = new Button(group, SWT.NONE);
btnManual.setBounds(162, 10, 75, 25);
btnManual.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
btnManual.setText("Manual");
Button btnBrowser = new Button(group, SWT.NONE);
btnBrowser.setBounds(27, 10, 75, 25);
btnBrowser.setText("Browse");
btnBrowser.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(composite, SWT.NULL);
String path = dialog.open();
if (path != null) {
File file = new File(path);
if (file.isFile())
{
displayFiles(new String[] { file.getAbsolutePath().toString()});
DemoShell.parseFile(table, file.toString());
}
else
displayFiles(file.list());
}
}
});
ttable_item.setControl(composite);
}
#Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
}
I am getting the following error when trying to add in the above manner.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor FileDialog(Composite, int) is undefined
Cannot refer to a non-final variable composite inside an inner class defined in a different method
I request for suggestions/help to clear the bug or re-do with any other way.
You are trying to access composite from within the Listener you define (SelectionAdapter). The notation you use to create the listener implicitly creates a new class. So you are effectively trying to access the variable composite from an inner class, which can only be done if composite is a static field of your outer class or if you make the composite final.
So just do the following:
final Composite composite = new Composite(tabFolder, SWT.NONE);
and it will work.
Moreover, as the error states, there is no constructor that takes a Composite. You have to use a Shell. So just do the following:
FileDialog dialog = new FileDialog(composite.getShell(), SWT.NULL);
This however will give you another exception, since you use the field shell somewhere above that line which is null. Since your class is a Shell, replace all occurences of shell with this and it will work.

output string using java textfield.setText() by using for loop

The question is, I try to make second textfield (textFieldGen) to print out the exact result likes console. Currently, second textfield shows one string only.
This is my first coding on java GUI.
(extra info, I built it using Eclipse with WindowBuilder + GEF )
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.TextField;
import java.awt.Label;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class PassGenerator {
private JFrame frmPasswordGenerator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassGenerator window = new PassGenerator();
window.frmPasswordGenerator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PassGenerator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPasswordGenerator = new JFrame();
frmPasswordGenerator.setTitle("Password Generator");
frmPasswordGenerator.setBounds(100, 100, 419, 229);
frmPasswordGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPasswordGenerator.getContentPane().setLayout(null);
final TextField textFieldGen = new TextField();
final TextField textFieldPass = new TextField();
textFieldPass.setBounds(74, 60, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldPass);
Label labelPass = new Label("Password Length:");
labelPass.setBounds(74, 33, 177, 21);
frmPasswordGenerator.getContentPane().add(labelPass);
Button genButton = new Button("Generate");
genButton.setBounds(262, 60, 86, 23);
frmPasswordGenerator.getContentPane().add(genButton);
// Add action listener to button
genButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
//System.out.println("You clicked the button");
String getTxt = textFieldPass.getText();
boolean y = true;
do{
try{
int c = Integer.parseInt(getTxt);
Random r = new Random();
String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z"};
int nc = 0-c;
int c2 = c/2;
int nc2 = 0-c2;
int ncm = (nc+1)/2;
if (c%2 == 0){
for(int x = nc2; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
}
else {
for(int x = ncm; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
y = false;
}
catch (NumberFormatException e1 ){
int messageType = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(null, "Please Enter Integer only", "Error!!", messageType);
y = false;
}
}while (y);
}
});
Label labelGen = new Label("Generated Password:");
labelGen.setBounds(74, 109, 149, 21);
frmPasswordGenerator.getContentPane().add(labelGen);
textFieldGen.setBounds(74, 136, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldGen);
Button copyButton = new Button("Copy");
copyButton.setBounds(262, 136, 86, 23);
frmPasswordGenerator.getContentPane().add(copyButton);
}
}
Use textFieldGen.setText (textFieldGen.getText () + "\n" + Integer.toString(numNum))
I don't see why you are setting the contents of the text field twice. I would just do:
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
//textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
//textFieldGen.setText(Integer.toString(numNum));
textFieldGen.setText(alpha + Integer.toString(numNum));
In general it is not a good practice to replace the entire text when all you want to do is append some characters to the text field. If you don't like the above then you can do:
textField.setText(alpha);
...
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), Integer.toString(numNum), null);
Edit:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JTextField textField = new JTextField(20);
add( textField );
textField.setText( "testing: " );
try
{
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), "1", null);
}
catch(Exception e) {}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Categories