I have been trying to attach event handlers to abstract list model. didn't work out so I switched to default list model. now I need help debugging. why do I have so many errors? im working with windowbuilder so I recon it shouldn't be this hard.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Window {
private JFrame frame;
/**
* Launch the application. The main method is the entry point to a Java application.
* For this assessment, you shouldn't have to add anything to this.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. This is the constructor for this Window class.
* All of the code here will be executed as soon as a Window object is made.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame. This is where Window Builder
* will generate its code.
* #return
*/
public JPanel initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem mntmSave = new JMenuItem("Save");
File.add(mntmSave);
JMenuItem mntmLoad = new JMenuItem("Load");
File.add(mntmLoad);
JMenuItem mntmExit = new JMenuItem("Exit");
File.add(mntmExit);
frame.getContentPane().setLayout(null);
JList Left_list = new JList();
Left_list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
}
});
Left_list.setFont(new Font("Tahoma", Font.PLAIN, 14));
Left_list.setModel(new AbstractListModel() {
String[] values = new String[] {"Case", "Motherboard", "CPU", "RAM", "GPU", "HDD", "PSU"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
Left_list.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
Left_list.setBounds(10, 11, 146, 218);
frame.getContentPane().add(Left_list);
JList Right_list = new JList();
Right_list.setModel(new AbstractListModel() {
String[] values = new String[] {};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
Right_list.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
Right_list.setBounds(278, 16, 146, 213);
frame.getContentPane().add(Right_list);
JButton btnNewButton = new JButton("Add>>");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton.setBounds(166, 91, 102, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("<<Remove");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(166, 125, 102, 23);
frame.getContentPane().add(btnNewButton_1);
}
}
}
Related
Hi im currently working on a program but I need to be able to change the class (so that the frame changes) with just the click of a menu tab.
I would like someone to modify this to get my to class2.java
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
class 1.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class circle_ac {
private JFrame frame;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
circle_ac window = new circle_ac();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public circle_ac() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame = new JFrame();
frame.setResizable(true);
frame.setBounds(1000, 1000, 2250, 1000);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,frame1);
this.revalidate();
this.repaint();
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
/*setup calculate button*/
JButton btnCalculate = new JButton("calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*setup calculations*/
double rad;
double ans1;
double ans2;
double pi=3.1415926535897932384626433832795;
try {
rad=Double.parseDouble(txtRadius.getText()) ;
ans1= pi*(rad*rad);
ans2= 2*pi*rad;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(25);
txtTheAreaOf.setText("The Area Is "+df.format(ans1));
txtTheCircumfrenceOf.setText("The Circumference Is "+df.format(ans2) );
/*setup error message*/
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please Enter Valid Radius");
}
}
});
/*initialize calculate button*/
btnCalculate.setFont(new Font("Tahoma", Font.PLAIN, 60));
btnCalculate.setBackground(new Color(227, 227, 227));
btnCalculate.setForeground(Color.BLACK);
frame.getContentPane().add(btnCalculate, BorderLayout.SOUTH);
/*setup Radius text box*/
txtRadius = new JTextField();
txtRadius.setFont(new Font("Tahoma", Font.PLAIN, 55));
txtRadius.setCursor(null);
txtRadius.setInputVerifier(null);
txtRadius.setText(" Enter The Radius");
txtRadius.setBackground(SystemColor.controlHighlight);
frame.getContentPane().add(txtRadius, BorderLayout.CENTER);
txtRadius.setColumns(10);
/*setup Area text box*/
txtTheAreaOf = new JTextField();
txtTheAreaOf.setEditable(false);
txtTheAreaOf.setText("The Area Of The Circle Is ");
txtTheAreaOf.setBackground(SystemColor.control);
txtTheAreaOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
frame.getContentPane().add(txtTheAreaOf, BorderLayout.WEST);
/*setup Circumference text box*/
txtTheCircumfrenceOf =new JTextField();
txtTheAreaOf.setEditable(false);
txtTheCircumfrenceOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
txtTheCircumfrenceOf.setText("The Circumfrence Of The Circle Is ");
txtTheCircumfrenceOf.setBackground(SystemColor.control);
frame.getContentPane().add((Component) txtTheCircumfrenceOf, BorderLayout.EAST);
}
}
class2.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class area_c {
private JFrame frame1;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
area_c window = new area_c();
window.frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public area_c() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame1 = new JFrame();
frame1.setResizable(true);
frame1.setBounds(1000, 1000, 2250, 1000);
frame1.pack();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
frame1.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame1.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
System.out.println("Hello World!");
I need the menu tab to change it from class1.java to class2.java with an action listener.
is this possible, if so how do I do it.
I recommend to implement your two classes as JPanels. Then you can add these JPanels to your JFrame. Have a look at this small example, that shows the principle in a short and quick way. Hope it helps:
package test;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class TestFrame extends JFrame {
private Container contentPane;
private JPanel panel1,panel2;
public TestFrame() {
super("Test");
this.setJMenuBar(menubar());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = this.getContentPane();
createPanels();
contentPane.setLayout(new BorderLayout());
this.add(BorderLayout.CENTER,panel1);
this.pack();
this.setVisible(true);
}
private JMenuBar menubar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem m1 =new JMenuItem("Selection 1");
JMenuItem m2 =new JMenuItem("Selection 2");
m1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
refresh();
}
});
m2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
refresh();
}
});
fileMenu.add(m1);
fileMenu.add(m2);
menubar.add(fileMenu);
return menubar;
}
private void refresh() {
this.revalidate();
this.repaint();
}
private void createPanels() {
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(BorderLayout.CENTER,new JLabel("Hello World"));
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
panel2.add(BorderLayout.CENTER,new JLabel("Goodbye World"));
}
public static void main(String[] args) {
TestFrame t = new TestFrame();
}
}
In most of the IDE's, when you right-click on the Button in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
When you are in one frame, you can set it's visibility off to hide it, like this:
this.setVisible(false);
And you can create the object of another class (of the other frame where you want to redirect) and set it's visibility on to display it, like this:
area_c of = new area_c();
of.setVisible(true);
So, you will be transitioning from one class to another of different frames.
You can achieve the same using the object of JMenuItem object:
class1 = new JPanel();
class1.setLayout(new BorderLayout());
class1.add(BorderLayout.CENTER,new JLabel("Label_Name"));
class2 = new JPanel();
class2.setLayout(new BorderLayout());
class2.add(BorderLayout.CENTER,new JLabel("Label_Name"));
JMenuItem JMenuItemObject1 =new JMenuItem("Class 1");
JMenuItem JMenuItemObject2 =new JMenuItem("Class 2");
JMenuItemObject1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
this.revalidate();
this.repaint();
}
});
JMenuItemObject2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
this.revalidate();
this.repaint();
}
});
area.add(JMenuItemObject1);
area.add(JMenuItemObject2);
menubar.add(area);
I have two GUI classes named Menu and convert. I want to run the convert class when I click the "open" button. It looks so simple, but I couldn't figure it out.
Menu class
package com.ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnConvert = new JButton("open");
btnConvert.setBounds(44, 52, 89, 23);
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//???
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnConvert);
}
}
convert class
package com.ui;
import java.awt.EventQueue;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class convert {
private JFrame frmTitle;
private JTextField textField;
private double value;
private ButtonGroup group;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
convert window = new convert();
window.frmTitle.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public convert() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTitle = new JFrame();
frmTitle.setTitle("TITLE");
frmTitle.setBounds(100, 100, 450, 300);
frmTitle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTitle.getContentPane().setLayout(null);
JLabel lblInputValue = new JLabel("Input value:");
lblInputValue.setBounds(29, 22, 79, 14);
frmTitle.getContentPane().add(lblInputValue);
textField = new JTextField();
textField.setBounds(22, 47, 86, 20);
frmTitle.getContentPane().add(textField);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Convert", TitledBorder.LEADING, TitledBorder.TOP, null, Color.RED));
panel.setBounds(29, 118, 264, 133);
frmTitle.getContentPane().add(panel);
panel.setLayout(null);
final JRadioButton rdbtnKelvin = new JRadioButton("Kelvin");
rdbtnKelvin.setBounds(6, 30, 67, 23);
panel.add(rdbtnKelvin);
final JRadioButton rdbtnFahrenheit = new JRadioButton("Fahrenheit");
rdbtnFahrenheit.setBounds(71, 30, 77, 23);
panel.add(rdbtnFahrenheit);
final JRadioButton rdbtnCelcius = new JRadioButton("Celcius");
rdbtnCelcius.setBounds(174, 30, 67, 23);
panel.add(rdbtnCelcius);
group = new ButtonGroup();
group.add(rdbtnCelcius);
group.add(rdbtnFahrenheit);
group.add(rdbtnKelvin);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Celcius", "Fahrenheit", "Kelvin"}));
comboBox.setBounds(177, 47, 116, 20);
frmTitle.getContentPane().add(comboBox);
JButton btnConvert = new JButton("CONVERT");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value = Double.parseDouble(textField.getText().toString());
if(comboBox.getSelectedItem().toString().equals("Celcius")){
if(rdbtnCelcius.isSelected()==true){
value = value;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= 1.8*value +32;
}
else{
value =value+273;
}
}
else if (comboBox.getSelectedItem().toString().equals("Fahrenheit")){
if(rdbtnFahrenheit.isSelected()==true){
value = value;
}
else if (rdbtnCelcius.isSelected()==true){
value= (value-32)*1.8;
}
else{
value =(value-32)/1.8+273;
}
}
else{
if(rdbtnCelcius.isSelected()==true){
value = value-273;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= value -273*1.8+32;
}
else{
value =value;
}
}
textField.setText(value +"");
textField.setEnabled(false);
}
});
btnConvert.setBounds(303, 114, 89, 23);
frmTitle.getContentPane().add(btnConvert);
JButton btnClear = new JButton("CLEAR");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField.setEnabled(true);
comboBox.setSelectedIndex(0);
rdbtnKelvin.setSelected(true);
}
});
btnClear.setBounds(303, 170, 89, 23);
frmTitle.getContentPane().add(btnClear);
}
}
First of all, class names and constructors should start with an upper case letter, like you did it for class Menu, but not for class convert.
A Java programm should have just one and only one main method for all classes. So, delete complete your main method from Convert class, put new Convert(); in the actionPerformed() method of btnConvert in Menu class:
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Convert();
}
});
and add frmTitle.setVisible(true); to the end of the initialize() method of Convert class.
First, your class names should begin with a capital letter, so instead of "convert" it should be "Convert.
Create a public method in Convert:
public JFrame getFrame() {
return frmTitle;
}
Then in your button's actionPerformed() method, just:
Convert w = new Convert();
w.getFrame().setVisible(true);
I'm writing a program where there is a JTable to be created (Which I'm able to). But I want to add a scroll bar to it. Below is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
static DefaultTableModel model = new DefaultTableModel();
static JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.add(new JScrollPane(table));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
table.setBounds(10, 131, 516, 178);
contentPane.add(table);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
When I run the above program, the table frame is also not displayed. But when I remove frame.add(new JScrollPane(table));, it is displaying the table in the JTable area, but there is no scrollbar in it.
Please let me know how can I get a scrollbar in the table and display the data correctly.
Thanks
At first don't use null layout, please read here.
frame.add(new JScrollPane(table)); this scroll pane is not displaying because in null layout each component needs to have bounds. Try below code. I just changed static variables to instance variables. And added scrollpane in to the constructor.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(10, 131, 516, 178);
contentPane.add(scroll);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
Here is my code. I want to open another Java form using menu bar but when I click on menu item, it shows me an error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
adding a window to a container
What should I do now?
package Driver;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
public class frmTestMenu extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frmTestMenu frame = new frmTestMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frmTestMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100,653, 425);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 434, 31);
contentPane.add(menuBar);
JMenu mnFile = new JMenu("FIle");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
frmTestMenu.this.dispose();
}
});
mnFile.add(mntmExit);
JMenu mnItem = new JMenu("Item1");
menuBar.add(mnItem);
JMenuItem mntmMenuItem = new JMenuItem("open Test Internal Form");
mnItem.add(mntmMenuItem);
JMenuItem mntmMenuItem_3 = new JMenuItem("open Test Internal Form 2");
mnItem.add(mntmMenuItem_3);
JMenu mnItem_1 = new JMenu("item 2");
menuBar.add(mnItem_1);
JMenuItem mntmMenuItem_1 = new JMenuItem("Menu 2 item 1");
mnItem_1.add(mntmMenuItem_1);
JMenu mnItem_2 = new JMenu("item 3");
menuBar.add(mnItem_2);
JMenuItem mntmMenuItem_2 = new JMenuItem("Menu 3 item 1");
mnItem_2.add(mntmMenuItem_2);
final JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBounds(0, 0, 633, 366);
mntmMenuItem.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
frm3_0 test1 = new frm3_0();
test1.setBounds(10, 10, 426, 229);
desktopPane.add(test1);
test1.setVisible(true);
}
});
mntmMenuItem_3.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
frmcity_A test2 = new frmcity_A();
test2.setBounds(10, 10, 426, 229);
desktopPane.add(test2);
test2.setVisible(true);
}
});
JScrollPane scrollPane = new JScrollPane(desktopPane);
JDesktopPane desktopPane_1 = new JDesktopPane();
desktopPane_1.setBounds(145, 88, 1, 1);
desktopPane.add(desktopPane_1);
scrollPane.setBounds(0, 30, 633, 336);
contentPane.add(scrollPane);
}
}
I have a problem with comboboxes which display list of buttons. What I have now is
http://hizliresim.com/djQzr7
However I want something more like this
http://hizliresim.com/QXDE3G
First button is combobox and the second one is that combobox when it is clicked.
Here is the code
package asd;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
public class asd extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
asd frame = new asd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public asd() {
try {
// Set System L&F
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (UnsupportedLookAndFeelException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
catch (InstantiationException e) {
// handle exception
}
catch (IllegalAccessException e) {
// handle exception
}
ComboBoxRender renderer;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(92, 85, 60, 40);
renderer = new ComboBoxRender();
comboBox.setRenderer(renderer);
comboBox.addItem("1");
comboBox.addItem("2");
comboBox.addItem("3");
comboBox.setPreferredSize(new Dimension(60, 40));
comboBox.setMinimumSize(new Dimension(70, 30));
comboBox.setMaximumSize(new Dimension(500, 500));
comboBox.setBackground(Color.GRAY);
comboBox.setUI(new javax.swing.plaf.metal.MetalComboBoxUI(){
public void layoutComboBox(Container parent, MetalComboBoxLayoutManager manager) {
super.layoutComboBox(parent, manager);
arrowButton.setBounds(0,0,0,0);
}
});
contentPane.add(comboBox);
}
}
class ComboBoxRender implements ListCellRenderer<Object> {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index,boolean isSelected, boolean cellHasFocus) {
JButton btn = new JButton(value.toString());
btn.setSelected(false);
btn.setBorderPainted(true);
btn.setBackground(Color.gray);
btn.setSize(new Dimension(100, 100));
btn.setMargin(new Insets(1, 1, 1, 1));
btn.setMinimumSize(new Dimension(200,200));
return btn;
}
}
For that you need to use ListCellRenderer. Read about custom renderers.
For example :
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class TestFrame extends JFrame {
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
JComboBox<String> box = new JComboBox<>(new String[]{"1","2"});
box.setRenderer(getRenderer());
add(box);
}
private ListCellRenderer<? super String> getRenderer() {
return new ListCellRenderer<String>() {
private JButton btn = new JButton();
public Component getListCellRendererComponent(JList<? extends String> list,String value, int index,
boolean isSelected, boolean cellHasFocus) {
btn.setText(value);
return btn;
};
};
}
public static void main(String args[]) {
new TestFrame();
}
}