MainFrame.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
public class MainFrame extends JFrame{
private TextPanel textPanel1;
private TextPanel textPanel2;
private FormPanel formPanel;
private JSplitPane splitPane;
private JTabbedPane tabPane;
public MainFrame() {
super("Hello");
setLayout(new BorderLayout());
tabPane = new JTabbedPane();
textPanel1 = new TextPanel();
tabPane.addTab("Tab 1", textPanel1);
textPanel2 = new TextPanel();
tabPane.addTab("Tab 2", textPanel2);
//Newly Added code
formPanel = new FormPanel(textPanel1,textPanel2);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,formPanel,tabPane);
splitPane.setOneTouchExpandable(true);
add(splitPane,BorderLayout.CENTER);
// add(formPanel,BorderLayout.WEST);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(500, 400));
setSize(600, 500);
}
}
TextPanel.java
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Scrollbar;
import java.io.ByteArrayOutputStream;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
public class TextPanel extends JPanel {
private JTextArea textArea1;
private JTextArea textArea2;
private FormPanel formPanel;
//Newly added code
private TextPanel textPanel;
public TextPanel(){
setLayout(new BorderLayout());
textArea1 = new JTextArea();
add(new JScrollPane(textArea1),BorderLayout.CENTER);
//textArea2 = new JTextArea();
//add(new JScrollPane(textArea2),BorderLayout.CENTER);
}
//Newly added code
public void appendText(String string, TextPanel textPanel2) {
// TODO Auto-generated method stub
this.textPanel = textPanel2;
textArea1.append(string);
}
}
FormPanel.java
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.ObjectInputStream.GetField;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class FormPanel extends JPanel {
private static int numberOfTabs = 1;
private JLabel serverName_1;
private JLabel serverName_2;
private JButton startServer_1;
private JButton startServer_2;
//Added New Code
private TextPanel textPanel1;
private TextPanel textPanel2;
JumpHosts jumpHosts = new JumpHosts();
//Added New Code
public FormPanel(final TextPanel textPanel1,final TextPanel textPanel2){
Dimension dim = getPreferredSize();
dim.width = 350;
setPreferredSize(dim);
setMinimumSize(dim);
//Added New Code
this.textPanel = textPanel1;
this.textPanel = textPanel2;
serverName_1 = new JLabel("server1 ");
startServer_1 = new JButton("Start");
serverName_2 = new JLabel("server2 ");
startServer_2 = new JButton("Start");
startServer_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] ev = new String[]{"username#10.10.10.10","username#server1"};
String cmd = "ls -ltr";
//jumpHosts.JumpHosts(ev,cmd);
//Newly added code
jumpHosts.JumpHosts(ev,cmd,textPanel1);
}
});
startServer_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] ev = new String[]{"username#10.10.10.10","username#server2"};
String cmd = "ls -ltr";
//jumpHosts.JumpHosts(ev,cmd);
//Newly added code
jumpHosts.JumpHosts(ev,cmd,textPanel2);
}
});
Border innerborder = BorderFactory.createTitledBorder("Detail");
Border outerborder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(outerborder, innerborder));
layoutComponents();
}
public void layoutComponents(){
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
//////////// First row ////////////
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 0.01;
gc.gridx = 0;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(serverName_1,gc);
/////////// Next Column ////////////
gc.gridy = 0;
gc.weightx = 2;
gc.weighty = 0.01;
gc.gridx = 2;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(startServer_1,gc);
//////////// Second row ////////////
gc.gridy++;
gc.weightx = 1;
gc.weighty = 0.1;
gc.gridx = 0;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(serverName_2,gc);
/////////// Next Column ////////////
//gc.gridy = 1;
gc.weightx = 2;
gc.weighty = 0.1;
gc.gridx = 2;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(startServer_2,gc);
}
}
JumpHosts.java
import com.jcraft.jsch.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.*;
public class JumpHosts {
TextPanel textPanel = new TextPanel();
//Newly added code
public void JumpHosts(final String[] arg,final String command,final TextPanel textPanel) {
StringBuffer resultDisplayBuffer = new StringBuffer();
SwingWorker sw = new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
try{
JSch jsch = new JSch();
if(arg.length <= 1){
System.out.println("This program expects more arguments.");
System.exit(-1);
}
Session session = null;
Session[] sessions = new Session[arg.length];
String host = arg[0];
String user = host.substring(0, host.indexOf('#'));
host = host.substring(host.indexOf('#')+1);
sessions[0] = session = jsch.getSession(user, host, 22);
session.setUserInfo(new MyUserInfo());
session.connect();
//textPanel.appendText("The session has been established to "+user+"#"+host+"\n");
//Newly added code
textPanel.appendText("The session has been established to "+user+"#"+host+"\n",textPanel);
for(int i = 1; i < arg.length; i++){
host = arg[i];
user = host.substring(0, host.indexOf('#'));
host = host.substring(host.indexOf('#')+1);
int assinged_port = session.setPortForwardingL(0, host, 22);
textPanel.appendText("portforwarding: "+
"localhost:"+assinged_port+" -> "+host+":"+22+"\n");
sessions[i] = session =
jsch.getSession(user, "localhost", assinged_port);
session.setUserInfo(new MyUserInfo());
session.setHostKeyAlias(host);
session.connect();
textPanel.appendText("The session has been established to "+
user+"#"+host+"\n");
}
String sudo_pass;
{
JTextField passwordField=(JTextField)new JPasswordField(8);
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null,
ob,
"Enter password for sudo",
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
sudo_pass=passwordField.getText();
}
Channel channel=session.openChannel("exec");
// man sudo
// -S The -S (stdin) option causes sudo to read the password from the
// standard input instead of the terminal device.
// -p The -p (prompt) option allows you to override the default
// password prompt and use a custom one.
((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
textPanel.appendText(new String(tmp,0,i));
}
if (channel.isClosed()) {
textPanel.appendText(new String("exit-status: " + channel.getExitStatus())+ "\n");
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
textPanel.appendText("Disconnect\n\n");
for(int i = sessions.length-1; i >= 0; i--){
sessions[i].disconnect();
}
}
catch(Exception e){
System.out.println(e);
}
return null;
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
so whenever I am clicking on any button the output gets redirected to only one textarea whereas other seems to be no usable. i.e to the last created tab.
I want that when I am clicking on button 1 then it should write to tab 1 and when I am clicking on button 2 then it should write to tab 2 and so on.
Examples appreciated as I am new to java
In JumpHosts:
TextPanel textPanel = new TextPanel();
you create an instance of TextPanel which is referenced by no other object in the program. This is not either of the TextPanels you created in MainFrame.
You need to pass the TextPanels created in MainFrame, namely:
private TextPanel textPanel;
private TextPanel textPanel2;
into your JumpHosts constructor:
JumpHosts(TextPanel textPanel1, TextPanel textPanel2)
to be able to reference the same TextPanel as MainFrame does.
Response to Followup:
You will need to pass your TextPanel first to your FormPanel constructor from within your MainFrame constructor. You will then need to modify your FormPanel contructor to pass the TextPanel to your JumpHosts constructor.
Related
I Browse a csv file and load the contents of the file to Jtable.
I want to add the JcomboBox in every row of the JTable .
Here is my tool for your reference:
I dont know how to add the ComboBox in each column of row.please help me to solve this problem .Any help is appreciated
Here is my code for your reference....
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.List;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import com.csvreader.CsvReader;
public class GUI {
private JPanel dialog = null;
private AboutDialog adlg;
public void addComponentsToPane() {
final JTextField txtfldcsvpth = new JTextField("Select a folder");
final JTextField txtsimprepname = new JTextField("Select a folder");
final JButton Btnbrowsecsv = new JButton("Select file");
final JButton BtnsimpRep = new JButton("Create SimpRep");
final JTable table = new JTable(){
final long serialVersionUID = 1L;
public boolean isCellEditable(int row,int column) {
return false;
};
};
BtnsimpRep.setEnabled(true);
dialog.setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.anchor = GridBagConstraints.LINE_START;
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.insets = new Insets(3, 3, 3, 3);
gBC.weightx = 1;
gBC.weighty = 0;
/******************************Browse Csv File***************************************/
JLabel label1 = new JLabel("Input File");
label1.setHorizontalAlignment(SwingConstants.RIGHT);
label1.setHorizontalTextPosition(SwingConstants.RIGHT);
label1.setPreferredSize(new Dimension(100, Btnbrowsecsv
.getPreferredSize().height));
gBC.gridx = 0;
gBC.gridy = 0;
dialog.add(label1, gBC);
//jtextfield for CsvPath
gBC.gridx = 1;
gBC.gridy = 0;
txtfldcsvpth.setPreferredSize(new Dimension(200, Btnbrowsecsv
.getPreferredSize().height));
txtfldcsvpth.setEditable(false);
dialog.add(txtfldcsvpth, gBC);
//Jbutton for Csv Browsing..
gBC.gridx = 2;
gBC.gridy = 0;
Btnbrowsecsv.setToolTipText("Select folder containing STEP files");
Btnbrowsecsv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String selectedFile = fileChooserMethod();
if (selectedFile != null) {
txtfldcsvpth.setText(selectedFile);
try{
BufferedReader br = new BufferedReader(new FileReader(new File(selectedFile)));
ArrayList <String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
JOptionPane.showMessageDialog(null, elements);
String[] columNames = new String[] {"Serial No","PartNumber", "Quantity"};
Object[][] content = new Object[elements.size()][3];
for(int i=1; i<elements.size(); i++) {
content[i][0] = i;
content[i][1] = elements.get(i)[1].trim();
content[i][2] = elements.get(i)[0].trim();
//content[i][2] = elements.get(i)[2].trim();
// content[i][3] = elements.get(i)[3].trim();
}
JOptionPane.showMessageDialog(null, content.length);
table.setModel(new DefaultTableModel(content,columNames));
}catch(Exception e){
}
}
}
});
dialog.add(Btnbrowsecsv, gBC);
/******************************JTable for CsvGrid***************************************/
JScrollPane js=new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
js.setPreferredSize(new Dimension(300 + Btnbrowsecsv
.getPreferredSize().width, 400));
js.setVisible(true);
js.setHorizontalScrollBar(null);
// final JTable jt=new JTable(data,column);
table.setCellSelectionEnabled(false);
table.setRowSelectionAllowed(false);
table.setBorder(BorderFactory.createEtchedBorder());
table.setRowHeight(20);
table.setVisible(true);
gBC.gridx = 0;
gBC.gridy = 1;
gBC.gridwidth = 3;
dialog.add(js, gBC);
/******************************JButton for SimpRepCreation***************************************/
gBC.gridx = 0;
gBC.gridy = 4;
gBC.gridwidth = 3;
BtnsimpRep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
boolean allFilesConverted = false;
}
});
dialog.add(BtnsimpRep, gBC);
}
public GUI() {
// JDialog.setDefaultLookAndFeelDecorated(true);
dialog = new JPanel();
// Set up the content pane.
addComponentsToPane();
dialog.setSize(dialog.getPreferredSize());
adlg = new AboutDialog(dialog);
}
/*****************************file choosing method********************************************/
private String fileChooserMethod() {
JFileChooser fileChooser = new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV files", "csv");
fileChooser.setFileFilter(filter);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int retVal = fileChooser.showDialog(dialog, "Select File");
if (retVal == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getPath();
} else {
return null;
}
}
public static Object gettable (String csvPath){
try {
BufferedReader br = new BufferedReader(new FileReader(new File(csvPath)));
ArrayList <String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
Object[][] content = new Object[elements.size()][2];
for(int i=0; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0].trim();
content[i][1] = elements.get(i)[1].trim();
//content[i][2] = elements.get(i)[2].trim();
//content[i][3] = elements.get(i)[3].trim();
}
return content;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
new GUI();
}
}
Thanks Regards,
Dinesh
Do you need to set the combo box in a specific cell?
You can set a cell renderer which uses a JCombobox. Similar to this:
http://www.java2s.com/Tutorial/Java/0240__Swing/UsingaJComboBoxinaCellinaJTableComponent.htm
got a problem here, trying to create a login to database system at the moment. I have to classes : UserLogManagerMainWindow and DatabaseConnectionFrame. My program is about log management. I want to make a database connection :
UserLogManagerMainWindow class has a button "Connect to database", on it's click DatabaseConnectionFrame initialize and gets up a frame with jlabels and jtextfields, after I enter everything i need, i press "Login" button, after this I want that my UserLogManagerMainWindow class continues on pressenting the logs from connected database.
I have written some code about how it supposed to look : "the logic about what am i trying to say"
connectToDatabaseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DatabaseConnectionFrame dcf = new DatabaseConnectionFrame();
dcf.setVisible(true);
if(dcf.answer == true) {
importButtons(menuBar);
setJMenuBar(menuBar);
try {
DatabaseComm.getColumnNamesToPanel(model, titles);
projects = DatabaseComm.AddLogsToArrayReturnProjectNames(events);
DatabaseComm.fillDataToPanel(model, events, titles, row);
DatabaseComm.resizeColumnWidth(table);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else {
System.out.println("not working");
}
}
});
But if statement does not working, i know why. That's why i'm asking how to make it work? More likely, threading is the key, but not good at it at the moment. Any tips without threading? And if threading is the only way, may i get some help of it?
Giving DatabaseConnectionFrame class below either:
package manager;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class DatabaseConnectionFrame extends JFrame{
private JPanel contentPane;
private JTextField address;
private JPasswordField password;
private JTextField username;
private JButton btnLogin;
private JButton btnCancel;
private JLabel lblPort;
private JTextField port;
public boolean answer = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseConnectionFrame frame = new DatabaseConnectionFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DatabaseConnectionFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(450,250);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
JLabel lblDatabaseIpAddress = new JLabel("Database ip address:");
GridBagConstraints gbc_lblDatabaseIpAddress = new GridBagConstraints();
gbc_lblDatabaseIpAddress.anchor = GridBagConstraints.EAST;
gbc_lblDatabaseIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblDatabaseIpAddress.gridx = 0;
gbc_lblDatabaseIpAddress.gridy = 0;
contentPane.add(lblDatabaseIpAddress, gbc_lblDatabaseIpAddress);
address = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(address, gbc_textField);
address.setColumns(10);
lblPort = new JLabel("Port");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.anchor = GridBagConstraints.EAST;
gbc_lblPort.insets = new Insets(0, 0, 5, 5);
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 1;
contentPane.add(lblPort, gbc_lblPort);
port = new JTextField();
GridBagConstraints gbc_textField1 = new GridBagConstraints();
gbc_textField1.insets = new Insets(0, 0, 5, 0);
gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField1.gridx = 1;
gbc_textField1.gridy = 1;
contentPane.add(port, gbc_textField1);
port.setColumns(10);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblUsername = new GridBagConstraints();
gbc_lblUsername.anchor = GridBagConstraints.EAST;
gbc_lblUsername.insets = new Insets(0, 0, 5, 5);
gbc_lblUsername.gridx = 0;
gbc_lblUsername.gridy = 2;
contentPane.add(lblUsername, gbc_lblUsername);
username = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 2;
contentPane.add(username, gbc_textField_1);
username.setColumns(10);
JLabel lblPassword = new JLabel("Password");
GridBagConstraints gbc_lblPassword = new GridBagConstraints();
gbc_lblPassword.anchor = GridBagConstraints.EAST;
gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
gbc_lblPassword.gridx = 0;
gbc_lblPassword.gridy = 3;
contentPane.add(lblPassword, gbc_lblPassword);
password = new JPasswordField();
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.insets = new Insets(0, 0, 5, 0);
gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
gbc_passwordField.gridx = 1;
gbc_passwordField.gridy = 3;
contentPane.add(password, gbc_passwordField);
btnLogin = new JButton("Login");
GridBagConstraints gbc_btnLogin = new GridBagConstraints();
gbc_btnLogin.insets = new Insets(0, 0, 0, 5);
gbc_btnLogin.gridx = 0;
gbc_btnLogin.gridy = 4;
contentPane.add(btnLogin, gbc_btnLogin);
btnCancel = new JButton("Cancel");
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 1;
gbc_btnCancel.gridy = 4;
contentPane.add(btnCancel, gbc_btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String dbAddress = address.getText();
String dbPort = port.getText();
String dbUsername = username.getText();
char[] dbPassword = password.getPassword();
if( dbAddress.isEmpty() || dbPort.isEmpty() || dbUsername.isEmpty() || dbPassword.length == 0) {
JOptionPane.showMessageDialog(getParent(),
"All fields have to be filled!");
}
else {
if(databaseValidation(dbAddress, dbPort, dbUsername, dbPassword)) {
JOptionPane.showMessageDialog(getParent(),
"Connected!");
answer = true;
setVisible(false);
}
else {
JOptionPane.showMessageDialog(getParent(),
"There was error connecting to the database!");
answer = false;
}
}
System.out.println(answer);
}
});
}
public boolean databaseValidation(String address, String port, String username, char[] password) {
String pw = String.valueOf(password);
System.out.println(pw);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/logctrl?user=" + username + "&password=" + pw );
} catch (SQLException e) {
System.out.println("Error connecting to database!");
return false;
}
System.out.println("Connected");
return true;
}
}
If you want to wait for the user input, you have two choices, you either make your own observer pattern which can be called at some point in the future when the state changes in some way or you use a dialog, which will block the codes execution at the point the dialog is made visible and will wait till it's closed
See How to use dialogs for details
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Show the dialog");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(TestPane.this), "I'm in charge now", true);
JButton btn = new JButton("Waiting");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(btn);
dialog.pack();
dialog.setLocationRelativeTo(TestPane.this);
dialog.setVisible(true);
JOptionPane.showMessageDialog(TestPane.this, "You won't see this till the dialog is closed");
}
});
}
}
}
so I have 2 classes, 1 for a very small interface and 1 for some calculations. basically I want to have a string displayed in a box. That's done but now I need the string to be obtained from my other class. Here is where my question lies, How do I do that if my code looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class SwingJPanelDemo extends JFrame { //where I want the string to be send to from the other class
String letter = "apple"; //teststring
private JLabel LetterTest = new JLabel(letter); //where I use the string
private JButton NextButton = new JButton("Next");
private JButton NoButton = new JButton("No");
public SwingJPanelDemo() {
super("Is This Your Letter?");
JPanel newPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridx = 0;
constraints.gridy = 0;
newPanel.add(LetterTest, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(NextButton, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(NoButton, constraints);
newPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Is This Your Letter?"));
add(newPanel);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
// set look and feel to the system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SwingJPanelDemo().setVisible(true);
}
});
}
}
How would I go about Getting s string to this?
If your other class looks like this:
public class Other {
public static String text = "some text";
}
you can just use Other.text to get the String.
So, my problem here is that I want a JPanel on my JFrame to function as a slideshow where 4 different pictures fade in and fade out.
I'm using the Scalr library to resize, everything works except with I use run();
As soon as I use that my window won't open and it get stuck with just the text running through. Is there anyway to make this panel have it's own way? Just sitting in the corner and doing his own thing?
A basic explanation would be lovely because I'm very new with Threads and everything around that.
Thank you!
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.AbstractAction;
import se.lundell.team.Team;
import javax.swing.ListSelectionModel;
import javax.swing.Action;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import org.imgscalr.Scalr;
public class MainWindow {
private JFrame frame;
private JTextField textField;
private final ButtonGroup buttonGroup = new ButtonGroup();
protected DefaultListModel<Team> teamList;
private JList list;
private JTextArea textArea;
private final Action addTeamAction = new AddTeamAction();
private final Action removeTeamAction = new RemoveTeamAction();
private final Action clearListAction = new ClearListAction();
private final Action generateAction = new GenerateAction();
public ArrayList<Team> teamA;
public ArrayList<Team> teamB;
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 957, 642);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
JPanel leftPanel = new JPanel();
splitPane.setLeftComponent(leftPanel);
GridBagLayout gbl_leftPanel = new GridBagLayout();
gbl_leftPanel.columnWidths = new int[]{0, 0};
gbl_leftPanel.rowHeights = new int[]{0, 0, 41, 66, 0, 0};
gbl_leftPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_leftPanel.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
leftPanel.setLayout(gbl_leftPanel);
teamList = new DefaultListModel<Team>();
teamList.addElement(new Team("team1"));
teamList.addElement(new Team("team2"));
teamList.addElement(new Team("team3"));
teamList.addElement(new Team("team4"));
list = new JList();
list.setModel(teamList);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 0, 5, 0);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
leftPanel.add(list, gbc_list);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 1;
leftPanel.add(textField, gbc_textField);
textField.setColumns(10);
JPanel btnPanel = new JPanel();
GridBagConstraints gbc_btnPanel = new GridBagConstraints();
gbc_btnPanel.insets = new Insets(0, 0, 5, 0);
gbc_btnPanel.fill = GridBagConstraints.VERTICAL;
gbc_btnPanel.gridx = 0;
gbc_btnPanel.gridy = 2;
leftPanel.add(btnPanel, gbc_btnPanel);
btnPanel.setLayout(new GridLayout(0, 3, 0, 0));
JButton btnAdd = new JButton("Add");
btnAdd.setAction(addTeamAction);
buttonGroup.add(btnAdd);
btnPanel.add(btnAdd);
JButton btnRemove = new JButton("Remove");
btnRemove.setAction(removeTeamAction);
buttonGroup.add(btnRemove);
btnPanel.add(btnRemove);
JButton btnClear = new JButton("Clear");
btnClear.setAction(clearListAction);
buttonGroup.add(btnClear);
btnPanel.add(btnClear);
JPanel generatePanel = new JPanel();
generatePanel.setPreferredSize(new Dimension(10, 20));
GridBagConstraints gbc_generatePanel = new GridBagConstraints();
gbc_generatePanel.fill = GridBagConstraints.BOTH;
gbc_generatePanel.insets = new Insets(0, 0, 5, 0);
gbc_generatePanel.gridx = 0;
gbc_generatePanel.gridy = 3;
leftPanel.add(generatePanel, gbc_generatePanel);
generatePanel.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnGenerate = new JButton("Generate");
btnGenerate.setAction(generateAction);
btnGenerate.setFont(new Font("Tahoma", Font.PLAIN, 26));
generatePanel.add(btnGenerate);
PictureFrame canvasPanel = new PictureFrame();
GridBagConstraints gbc_canvasPanel = new GridBagConstraints();
gbc_canvasPanel.fill = GridBagConstraints.BOTH;
gbc_canvasPanel.gridx = 0;
gbc_canvasPanel.gridy = 4;
leftPanel.add(canvasPanel, gbc_canvasPanel);
JPanel rightPanel = new JPanel();
splitPane.setRightComponent(rightPanel);
rightPanel.setLayout(new BorderLayout(0, 0));
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
textArea.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(textArea, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnMenu = new JMenu("Menu");
menuBar.add(mnMenu);
JMenuItem mntmLoad = new JMenuItem("Load");
mnMenu.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnMenu.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnMenu.add(mntmExit);
frame.setVisible(true);
}
protected JList getList() {
return list;
}
private class AddTeamAction extends AbstractAction {
public AddTeamAction() {
putValue(NAME, "Add");
putValue(SHORT_DESCRIPTION, "Add team to list.");
}
public void actionPerformed(ActionEvent e) {
if(!textField.getText().isEmpty()) {
teamList.addElement(new Team(textField.getText()));
textField.setText("");
} else {
JOptionPane.showMessageDialog(null, "You need to enter a name.", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
private class RemoveTeamAction extends AbstractAction {
public RemoveTeamAction() {
putValue(NAME, "Remove");
putValue(SHORT_DESCRIPTION, "Remove the selected team.");
}
public void actionPerformed(ActionEvent e) {
int choice = getList().getSelectedIndex();
teamList.removeElementAt(choice);
}
}
private class ClearListAction extends AbstractAction {
public ClearListAction() {
putValue(NAME, "Clear");
putValue(SHORT_DESCRIPTION, "Clear the list and the tournament window");
}
public void actionPerformed(ActionEvent e) {
teamList.clear();
textArea.setText("");
teamA.clear();
teamB.clear();
}
}
private class GenerateAction extends AbstractAction {
public GenerateAction() {
putValue(NAME, "Generate");
putValue(SHORT_DESCRIPTION, "Generate a new Round Robin tournament.");
teamA = new ArrayList<Team>();
teamB = new ArrayList<Team>();
}
public void actionPerformed(ActionEvent e) {
rotateSchedual();
}
private void rotateSchedual(){
if(teamList.getSize() % 2 == 0) {
start();
} else {
teamList.addElement(new Team("Dummy"));
start();
}
}
protected void start() {
for(int i = 0; i < teamList.getSize(); i++) {
teamA.add(teamList.getElementAt(i));
}
// Split the arrayList to two and invert.
splitSchedual();
int length = teamA.size();
System.out.println(teamB.size());
System.out.println(length);
printSchedual(length);
//remove index 0 from teamA and add index 0 from teamB first in the list. then add the first team back in again.
for(int i = 0;i <= (length - 1); i++){
//copy index 0 and add it to the other array.
//remove index 0 in both arrays.
teamA.add(1, teamB.get(0));
teamB.remove(0);
teamB.add(teamA.get(length));
teamA.remove(length);
printSchedual(length);
}
}
//Splits the array in to two arrays.
protected void splitSchedual(){
int length = teamA.size();
for(int i = (length/2);i < (length);i++){
teamB.add(teamA.get(i));
}
for(int i = (length - 1);i >= (length/2); i--) {
teamA.remove(i);
}
}
protected void printSchedual(int length){
int rounds = length;
for(int i = 0; i < (rounds - 1); i++){
textArea.append((i+1) + ". " + teamA.get(i).getTeamname() + " - " + teamB.get(i).getTeamname() + "\n");
}
textArea.append("-----------------------------\n");
}
}
public class PictureFrame extends JPanel implements Runnable {
Runnable run;
Image[] imageArray = new Image[4];
Image resized;
public PictureFrame() {
setVisible(true);
try {
imageArray[0] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/TrophyTheChampion.gif").getFile()));
imageArray[1] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy.gif").getFile()));
imageArray[2] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy1.gif").getFile()));
imageArray[3] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/nicolas_cage.jpg").getFile()));
} catch (IOException e) {
e.printStackTrace();
}
resized = Scalr.resize((BufferedImage)imageArray[0], 190, 190);
}
#Override
public void run() {
System.out.println("körs bara en gång.");
while(true) {
System.out.println("This will print, over and over again.");
for(int i = 0; i < imageArray.length; i++) {
resized = Scalr.resize((BufferedImage)imageArray[i], 190, 190);
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
#Override
public void paint(Graphics g) {
g.drawImage(resized, 30, 0, null);
}
}
}
Currently my code will not run because I have no main, but when I make a main it must be static, and I am under the impression I shouldn't be making all of my variables for the Swing elements Static, as per the advice of many.
I'm not sure how to invoke the methods without using main as the constructor, currently my gui does not appear.
Thanks.
package movieinfo;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.io.FileUtils;
public class Swinggui {
JButton enter;
public JTextField movietext;
JList listofmovies;// converts moviestowatch into gui
// element.
File textfilemovie; // file which movies marked for watching
// are saved
java.util.List<String> moviestowatch; // arraylist which is
// populated by
// textfilemovie
// than printed to
// GUI element
ListSelectionListener setSearch;
JButton add;
String info;
public Swinggui() throws IOException {
yourMovies();
gui();
jsonAndButtons();
}
public void gui() {
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
enter = new JButton("Get Info");
c.gridx = 2;
c.gridy = 1;
maingui.add(enter, c);
add = new JButton("add");
c.gridx = 5;
c.gridy = 6;
maingui.add(add, c);
JTextArea movieinfo = new JTextArea(info, 5, 20);
movieinfo.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2,
Color.red));
movietext = new JTextField(18);
c.gridx = 1;
c.gridy = 1;
maingui.add(movietext, c);
final JScrollPane scrolll = new JScrollPane(movieinfo);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 2;
maingui.add(scrolll, c);
final JLabel titlee = new JLabel("Enter movie name below!");
c.gridx = 1;
c.gridy = 0;
maingui.add(titlee, c);
c.gridx = 1;
c.gridy = 3;
maingui.add(titlee, c);
final JLabel watchlist = new JLabel("Watchlist");
c.gridx = 5;
c.gridy = 1;
maingui.add(watchlist, c);
maingui.setResizable(false);
maingui.setVisible(true);
listofmovies = new JList(moviestowatch.toArray());
c.gridx = 4;
c.gridy = 3;
maingui.add(new JScrollPane(listofmovies), c);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
listofmovies.addListSelectionListener(setSearch);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
}
public void jsonAndButtons() {
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(apicall.getMovieInfo(movietext.getText()
.replaceAll(" ", "%20")));
info = apicall.getMovieInfo(movietext.getText().replaceAll(" ",
"%20"));
}
});
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
FileUtils.writeStringToFile(new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt"),
"\n" + movietext.getText(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
moviestowatch = FileUtils.readLines(textfilemovie);
listofmovies = new JList(moviestowatch.toArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void yourMovies() throws IOException {
textfilemovie = new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt");
textfilemovie.createNewFile();
moviestowatch = FileUtils.readLines(textfilemovie);
setSearch = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
info = apicall.getMovieInfo(((String) listofmovies
.getSelectedValue()).replaceAll(" ", "%20"));
}
};
}
}
Firstly, don't keep everything in one class. Create some other class and then create object of that type, and invoke its methods, it would look like this in your main() method:
MyClass myClass = new MyClass();
myClass.doStuff();
inside your main put:
new Swinggui();
This will pull you out of the static context and bring you into the non-static Swinggui constructor
Make your class Swinggui extend JFrame.
Then create a main method and create object of Swinggui
Swinggui gui = new Swinggui();
now you must make gui visible, for this write.
gui.setVisible(true);
And you are good to go.
Refer everything in code using "this" and you would have non static items.