So here I have two classes: Customer Order Class and Confirmation Class. I want to access the data stored in LastNameTextField (Customer Order Class) and set it as the text for UserLastNameLabel (Confirmation Class) after clicking a "Submit" button. For some reason however, the output displays nothing.
Snippet of my code:
package customer_order;
public class customer_order extends Frame{
private static final long serialVersionUID = 1L;
private JPanel jPanel = null;
private JLabel LastNameLabel = null;
protected JTextField LastNameTextField = null;
private JButton SubmitButton = null;
public String s;
public customer_order() {
super();
initialize();
}
private void initialize() {
this.setSize(729, 400);
this.setTitle("Customer Order");
this.add(getJPanel(), BorderLayout.CENTER);
}
/**
* This method initializes LastNameTextField
*
* #return javax.swing.JTextField
*/
public JTextField getLastNameTextField() {
if (LastNameTextField == null) {
LastNameTextField = new JTextField();
LastNameTextField.setBounds(new Rectangle(120, 100, 164, 28));
LastNameTextField.setName("LastNameTextField");
}
return LastNameTextField;
}
/**
* This method initializes SubmitButton
*
* #return javax.swing.JButton
*/
private JButton getSubmitButton() {
if (SubmitButton == null) {
SubmitButton = new JButton();
SubmitButton.setBounds(new Rectangle(501, 225, 96, 29));
SubmitButton.setName("SubmitButton");
SubmitButton.setText("Submit");
SubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
//THE STRING I WANT
s = LastNameTextField.getText();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new confirmation().setVisible(true);
}
});
}
});
}
return SubmitButton;
}
package customer_order;
public class confirmation extends customer_order{
private static final long serialVersionUID = 1L;
private JPanel jPanel = null; // #jve:decl-index=0:visual-constraint="58,9"
private JLabel LastNameLabel = null;
private JLabel UserLastNameLabel = null;
// #jve:decl-index=0:
/**
* This method initializes frame
*
* #return java.awt.Frame
*/
public confirmation() {
super();
initialize();
}
private void initialize() {
this.setSize(729, 400);
this.setTitle("Confirmation");
this.add(getJPanel(), BorderLayout.CENTER);
}
/**
* This method initializes jPanel
*
* #return javax.swing.JPanel
*/
private JPanel getJPanel() {
if (jPanel == null) {
UserLastNameLabel = new JLabel();
UserLastNameLabel.setBounds(new Rectangle(121, 60, 167, 26));
//THE PROBLEM?
UserLastNameLabel.setText(s);
}
return jPanel;
}
The s field will only have a value if the getSubmitButton method is called (it doesn't seem to be in your code), the button it returns is added to the form, and the user has already clicked on the button.
When you call new confirmation(), you get a new object with its own field s, and for s in the new confirmation to have a value it will also need to have the getSubmitButton method called, and the action listener triggered.
I don't really see any reason for confirmation to extend customer_order in this case. Normally you extend a class to specialise - for example, if you had certain orders which were treated differently because they repeated every week you may make a new class repeating_customer_order which adds extra fields to deal with the repeating. Accessing data from one class in another isn't really a reason to make one extend the other.
For what you want to do, I'd suggest removing the inheritence (get rid of extends customer_order), and then passing the value of s into the constructor:
customer_order:
s = LastNameTextField.getText();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new confirmation(s).setVisible(true);
}
});
confirmation:
private final String s;
public confirmation(final String s) {
super();
this.s = s;
initialize();
}
As an aside, your code would be much easier to read if you kept to the standard naming schemes used in most Java apps:
classes should begin with an uppercase letter and be CamelCased, e.g. CustomerOrder instead of customer_order
fields should begin with a lowercase letter, e.g. lastNameTextField or submitButton
This helps people see at a glance what is going on - at the minute a quick glance at LastNameTextField.getText() makes it look like you're calling a static method in a class called LastNameTextField!
Related
I'created a JLabel that should display "TextA" if the variable count == -1,
"Text B" if the variable count == 0 and "TextC" if the variable count == 1.
I've used Swing to create my interface, which you can see below
TempConverter
The red rectangle shows where the JLabel should be.
I have tried creating 3 JLabels and changing the setVisible(Boolean) whenever the variable count value condition applies. This didn't work because I got the following error:
Exception in thread "main" java.lang.NullPointerException
at tempconverterUI.TempConverter.main(TempConverter.java:354)
C:\Users\x\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
And the JLabels could not be placed in the same location in the GUI (overlapping was not possible).
I've tried using jLabel.setText() to change the Text displayed in the JLabel, whenever the variable condition applied. I got a similar error to the one above (if not the same).
I've read some other posts and researched further and found that some people suggested ActionListeners to be set but I am unsure that these will work with a simple variable, as opposed to a component in the GUI.
My Code is as follows:
package tempconverterUI;
import javax.swing.JOptionPane;
import messageBoxes.UserData;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.WString;
public class TempConverter extends javax.swing.JFrame {
public interface someLib extends Library
{
public int engStart();
public int endStop();
public int engCount();
public WString engGetLastError();
public int engSetAttribute(WString aszAttributeID, WString aszValue);
}
/**
* Creates new form TempConverter
*/
public TempConverter() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
The layout is created here, followed by the Temperature convertion methods and unrelated component's functionality (which I believe is not relevant in this case)
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/**This is where the Login form gets created*/
UserData.popUp();
/**After this the Library functions are called, which will return the variable count value*/
someLib lib = (someLib) Native.loadLibrary("someLib", someLib.class);
int startResult = lib.engStart();
System.out.println(startResult);
if (startResult < 0)
{
System.out.println(lib.engGetLastError());
}
System.out.println(UserData.getAcInput());
int setAtResult = lib.engSetAttribute(new WString("CODE"), UserData.getAcInput());
System.out.println(setAtResult);
if (setAtResult < 0)
{
System.out.println(lib.engGetLastError());
}
And next is the piece of code from where I should control the JLabel Text to display
int count = lib.engCount();
System.out.println(count);
if (count == -1)
{
System.out.println(lib.engGetLastError());
}
else if (count == 0)
{
}
else
{
}
new TempConverter().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JPanel bottomPanel;
private javax.swing.JButton convertButton;
private static javax.swing.JButton button;
private javax.swing.JTextField from;
private javax.swing.JComboBox<String> fromCombo;
private javax.swing.JLabel fromLabel;
private javax.swing.JLabel title;
private javax.swing.JTextField to;
private javax.swing.JComboBox<String> toCombo;
private javax.swing.JLabel toLabel;
private javax.swing.JPanel topPanel;
// End of variables declaration
}
Any help with this would be much appreciated. If you could include a simple code example as well, this would be fantastic as I am new to Java (and programming, in general).
Issues:
Don't set the JLabel visible, but rather add it initially to the GUI, leave it visible by default, and simply set its text via setText(...).
Give the class that holds the JLabel public methods that allow outside classes the ability to set the label's text. Something like public void setLabelText(String text), and in the method call setText(text) on the JLabel.
Debug your NullPointerException as you would any other NPE -- look at the stacktrace, find the line that throws it, and then look back into the code to see why a key variable on that line is null.
When and how you change the JLabel will depend on what event you want to listen for. If it is user input, then you will want to respond to that input, be it an ActionListener added to a JButton or to a JTextField, or an itemListener added to a JRadioButton.
If you want instead to listen for the change in state of a variable, no matter how the variable is changed, then make it a "bound property" (tutorial) using PropertyChangeSupport and a PropertyChangeListener.
For an example of the latter:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
#SuppressWarnings("serial")
public class ShowCount extends JPanel {
private static final int TIMER_DELAY = 1000;
private JLabel countLabel = new JLabel(" ");
private CountModel model = new CountModel();
public ShowCount() {
model.addPropertyChangeListener(CountModel.COUNT, new ModelListener(this));
setPreferredSize(new Dimension(250, 50));
add(new JLabel("Count:"));
add(countLabel);
Timer timer = new Timer(TIMER_DELAY, new TimerListener(model));
timer.start();
}
public void setCountLabelText(String text) {
countLabel.setText(text);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
ShowCount mainPanel = new ShowCount();
JFrame frame = new JFrame("ShowCount");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class CountModel {
public static final String COUNT = "count"; // for count "property"
// support object that will notify listeners of change
private SwingPropertyChangeSupport support = new SwingPropertyChangeSupport(this);
private int count = 0;
public int getCount() {
return count;
}
public void setCount(int count) {
int oldValue = this.count;
int newValue = count;
this.count = count;
// notify listeners that count has changed
support.firePropertyChange(COUNT, oldValue, newValue);
}
// two methods to allow listeners to register with support object
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
support.addPropertyChangeListener(propertyName, listener);
}
}
class ModelListener implements PropertyChangeListener {
private ShowCount showCount;
public ModelListener(ShowCount showCount) {
super();
this.showCount = showCount;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
int newValue = (int) evt.getNewValue();
showCount.setCountLabelText(String.format("%03d", newValue));
}
}
class TimerListener implements ActionListener {
private CountModel model;
public TimerListener(CountModel model) {
super();
this.model = model;
}
#Override
public void actionPerformed(ActionEvent e) {
int oldCount = model.getCount();
int newCount = oldCount + 1;
model.setCount(newCount);
}
}
Is there a way or method in which we can add placeholder in j text field. I want to add placeholder "Enter Your Number" in field but how can I do this. I check all methods but didn't working.
Code:
public class Loop extends JFrame{
private JTextField t1;
public L(){
getContentPane().setLayout(null);
t1=new JTextField();
t1.setBounds(27,50,47,28);
getContentPane().add(t1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main:
public class Main {
public static void main(String[] args) {
L object = new L();
}
}
Check out Text Prompt for a flexible solution.
You can control when prompt is displayed (always, focus gained or focus lost). You can also customize the style of the text.
Here is an example of which you can you inspire
package TinyOS;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.Document;
#SuppressWarnings("serial")
public class PlaceholderTextField extends JTextField {
public static void main(final String[] args) {
final PlaceholderTextField tf = new PlaceholderTextField ("");
tf.setColumns(20);
tf.setPlaceholder("Here is a placeHolder!");
final Font f = tf.getFont();
tf.setFont(new Font(f.getName(), f.getStyle(), 30));
JOptionPane.showMessageDialog(null, tf);
}
private String placeholder;
public PlaceholderTextField () {
}
public PlaceholderTextField (
final Document pDoc,
final String pText,
final int pColumns)
{
super(pDoc, pText, pColumns);
}
public PlaceholderTextField (final int pColumns) {
super(pColumns);
}
}
I hope that can help you
This code should work, it listen on first click and removes the text
public class Loop extends JFrame{
private JTextField t1;
private boolean clicked = false;
public L(){
getContentPane().setLayout(null);
t1=new JTextField();
t1.setText("Enter Your Number");
t1.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e){
if(!clicked){
clicked=true;
t1.setText("");
}
}
}
t1.setBounds(27,50,47,28);
getContentPane().add(t1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Maybe better solution exists
Note - not tested
EDIT (how the boolean clicked works)
when you call method mousePressed(MouseEvent) at the first time, the clicked variable is false, by declaration:
private boolean clicked = false;
So the if body is executed (because !clicked = !false = true)
in the if body, the clicked variable is set to true, so if condition will be then false: (because !clicked = !true = false)
This solves the problem of running code just once.
I want to get the text of private access JTextArea from another class in the same package and store/save the text into a String.
public class JTextAreaDemo extends javax.swing.JFrame {
public JTextAreaDemo() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class();
d.readJtxtAreaText();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JTextAreaDemo().setVisible(true);
}
});
}
private javax.swing.JTextArea jTextArea1;
/**
* #return the jTextArea1
*/
public String getjTextArea1() {
return jTextArea1.getText();
}
/**
* #param jTextArea1 the jTextArea1 to set
*/
public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
this.jTextArea1 = jTextArea1;
}
Now I want to save the text of JTextArea to string in below class
public class TxtArea_Class {
JTextAreaDemo demo;
String txt;
public TxtArea_Class(){
demo = new JTextAreaDemo();
txt = new String();
}
public void readJtxtAreaText(){
txt = demo.getjTextArea1();
if(txt.isEmpty()){
System.out.println("Failed To Get TextArea Contents ");
}
else{
System.out.println("Successfully Get TextArea Contents ");
}
}
Console Output :
Failed to Get TextArea Contents
Problem is in your TextArea_Calss's constructor
try the following.
public TextArea_class(TextAreaDemo demo) {
this.demo = demo;
this.str = new String();
}
and in button event. do this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class(this);
d.readJtxtAreaText();
}
In current implementation, Every-time you create an instance of TextArea-calss a new frame get created. because in TextArea_Class constructor you are creating an new instance of demo class.
and you are trying to get value from newly created demoFrame(that might be invisible for you but exist).
I'm hoping this will solve your issue.
You have two different instances of JTextAreaDemo!! One created in main and made visible, the other created in TxtArea_Class. The first one is the one on the screen, and the second is the one you read the string from. So the text you enter into the first doesn't show in the second.
I got the contents of JTxtArea from another class by updating my code by this.
TextArea_class
public TextArea_class(TextAreaDemo demo) {
this.demo = demo;
this.str = new String();
}
JTxtAreaDemo
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
TxtArea_Class d = new TxtArea_Class(this);
d.readJtxtAreaText();
}
I am creating a simple user interface whereby a user could click on a button to run a specific Java class. Upon clicking, the progress of the task should be displayed to the user and also provide a Cancel button for the user to terminate the task at any point of time while the task is running.
In this case, I am using a ProgressMonitor to be displayed when a user clicks on a JButton in the UI, whereby runEngineerBuild() containing a runnable thread will be invoked to execute the methods of another Java class (called EngineerBuild.java). However, the ProgressMonitor dialog does not display. How can I get the ProgressDialog to show? I'm wondering if it is because of the nature of multiple running threads or maybe I'm missing out on something. Would really appreciate your help!
In SecondPanel.java:
package mainApplication;
import java.awt.Font;
public class SecondPanel extends JPanel {
private MainApplication ma = null; // main JFrame
private JPanel pnlBtn;
private JPanel pnlProgress;
private JButton btnRunAll;
private JButton btnEngBuild;
private JButton btnWholeDoc;
private JButton btnCancelProgress;
private JLabel lblTitleSteps;
private JLabel lblAlt;
private JLabel lbl_1a;
private JLabel lbl_1b_c;
private JLabel lblTitleStatus;
private JProgressBar progressRunAll;
private JProgressBar progressEngBuild;
private JProgressBar progressWholeDoc;
private Property property = Property.getInstance();
// private Task task;
private boolean cancelFlag;
/**
* Create the panel for Step 1 TabbedPane.
*/
public SecondPanel(MainApplication mainApp) {
// TODO Auto-generated constructor stub
super();
ma = mainApp;
}
public SecondPanel() {
this.setBackground(new Color(224, 255, 255));
this.setBounds(0, 0, 745, 1350);
this.setPreferredSize(new Dimension(745, 600));
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
pnlBtn = new JPanel();
pnlBtn.setLayout(new BoxLayout(pnlBtn, BoxLayout.PAGE_AXIS));
pnlBtn.setAlignmentY(Component.TOP_ALIGNMENT);
pnlProgress = new JPanel();
pnlProgress.setLayout(new BoxLayout(pnlProgress, BoxLayout.PAGE_AXIS));
pnlProgress.setAlignmentY(TOP_ALIGNMENT);
pnlBtn.add(Box.createRigidArea(new Dimension(0, 15)));
btnEngBuild = new JButton("Run EngineerBuild.java");
btnEngBuild.setToolTipText("Build search engineer");
btnEngBuild.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// start activity
activity = new SimulatedActivity(1000);
activity.start();
// launch progress dialog
progressDialog = new ProgressMonitor(ma,
"Waiting for Simulated Activity", null, 0, activity
.getTarget());
progressDialog.setMillisToPopup(1000);
// start timer
activityMonitor = new Timer(500, null);
activityMonitor.start();
btnEngBuild.setEnabled(false);
}
});
activityMonitor = new Timer(500, new ActionListener() {
private PrintStream textArea;
public void actionPerformed(ActionEvent event) {
int current = activity.getCurrent();
// show progress
runEngineerBuild();
textArea.append(current + "\n");
progressDialog.setProgress(current);
// check if task is completed or canceled
if (current == activity.getTarget() || progressDialog.isCanceled()) {
activityMonitor.stop();
progressDialog.close();
activity.interrupt();
btnEngBuild.setEnabled(true);
}
}
});
btnEngBuild.setMinimumSize(new Dimension(200, 30));
btnEngBuild.setPreferredSize(new Dimension(200, 30));
btnEngBuild.setMaximumSize(new Dimension(200, 30));
pnlBtn.add(btnEngBuild);
pnlBtn.add(Box.createRigidArea(new Dimension(0, 15)));
// components in panel progress
lblTitleStatus = new JLabel();
lblTitleStatus.setText("<html><u>Task Status</u></html>");
progressEngBuild = new JProgressBar();
Border border2 = BorderFactory.createTitledBorder("Run EngineerBuild");
progressEngBuild.setBorder(border2);
// title
pnlProgress.add(lblTitleStatus);
pnlProgress.add(Box.createRigidArea(new Dimension(0, 15)));
pnlProgress.add(progressEngBuild);
pnlProgress.add(Box.createRigidArea(new Dimension(0, 15)));
this.add(Box.createRigidArea(new Dimension(15, 10)));
this.add(pnlBtn);
this.add(Box.createRigidArea(new Dimension(50, 10)));
this.add(pnlProgress);
}
public void runEngineerBuild()
{
EngineerBuildRunnable ebr = new EngineerBuildRunnable();
ebr.run();
}
private class EngineerBuildRunnable implements Runnable {
EngineerBuild eb;
public EngineerBuildRunnable() {
eb = new EngineerBuild();
}
public void run() {
eb.initial();
eb.storeIntoFile();
}
}
private Timer activityMonitor;
private ProgressMonitor progressDialog;
private SimulatedActivity activity;
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
}
/**
* A simulated activity thread.
*/
class SimulatedActivity extends Thread {
/**
* Constructs the simulated activity thread object. The thread increments a
* counter from 0 to a given target.
*
* #param t
* the target value of the counter.
*/
public SimulatedActivity(int t) {
current = 0;
target = t;
}
public int getTarget() {
return target;
}
public int getCurrent() {
return current;
}
public void run() {
try {
while (current < target && !interrupted()) {
sleep(100);
current++;
}
} catch (InterruptedException e) {
}
}
private int current;
private int target;
}
Here's the link for the original ProgressMonitor code if you're interested:
User Interface Programming - Example 1-11 ProgressMonitorTest.java
In all likelihood, calling runEngineerBuild() will call long-running code, something that you're doing on the Swing event thread, and this will tie up the thread rendering your GUI useless and frozen until that long-running code has completed its run. The solution is the same as all similar issues -- call runEngineerBuild() in a background thread such as a SwingWorker.
A quick fix would be to explicitly call runEngineerBuild() in a simple thread:
EngineerBuildRunnable ebr = new EngineerBuildRunnable();
new Thread(ebr).start();
// ebr.run(); // !!! don't call a Runnable's run method directly !!!!
For details on how to use a SwingWorker, please check out: Lesson: Concurrency in Swing.
Im building a Ui in Swing wherein my requirement is to have JPanes within a JTable. These JPanes will have JButtons within them.
My use case is as follows --
Im writing a MethodEditor wherein im providing a UI to store the methods within a supplied file. The UI would also allow editing the parameters being passed to the method on the click of a button.
Every single method would have a UI representation as follows --
My basic representation of the Method class is as follows --
public Class Method {
String methodName;
List<String> InputVariableNames;
String OutputVariableName;
}
Now i have a list of Method objects, List<Method> methodList on which i want to base my JTable.
This List is contained in a MethodModel class as follows --
public class MethodModel {
List<Method> methodModel;
}
I had asked a question earlier and have based my code on the answer provided there. My code however does not seem to be working. My code is as follows --
public class MethodEditor extends JTable {
private static final long serialVersionUID = 1L;
private MethodEditorModel model ;
private MethodCellRenderer cellRenderer;
public MethodEditor(MethodModel bean) {
setRowHeight(25);
this.setPreferredSize(new Dimension(500, 500));
model = new MethodEditorModel(bean);
this.setModel(model);
setupComponent();
}
private void setupComponent() {
cellRenderer = new MethodCellRenderer();
this.setDefaultRenderer(Object.class,cellRenderer);
this.setBorder(BorderFactory.createLineBorder(Color.GRAY));
}
private static class MethodEditorModel extends DefaultTableModel implements PropertyChangeListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private MethodModel bean;
public MethodEditorModel(MethodModel bean) {
this.bean = bean;
bean.addPropertyChangeListener(this);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
fireTableDataChanged();
}
}
private static class MethodCellRenderer implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
private MethodEditorCellPanel renderer = new MethodEditorCellPanel();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
MethodModel methodModel = (MethodModel)value;
for(Method method : methodModel.getMethodList()) {
renderer.setComponents((Method) method);
}
return renderer;
}
}
private static class MethodEditorCellPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton upButton;
private JButton downButton;
private JButton methodDetailsButton;
private Method method;
public MethodEditorCellPanel() {
upButton = new JButton("Up");
downButton = new JButton("Down");
}
public void setComponents(Method method)
{
this.method = method;
methodDetailsButton = new JButton(method.getMethodName());
upButton.addActionListener(this);
downButton.addActionListener(this);
methodDetailsButton.addActionListener(this);
Box verticalBar = Box.createHorizontalBox();
verticalBar.add(upButton);
verticalBar.add(Box.createHorizontalStrut(15));
verticalBar.add(methodDetailsButton);
verticalBar.add(Box.createHorizontalStrut(15));
verticalBar.add(downButton);
add(verticalBar);
}
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getSource().equals(downButton)) {
}
if(evt.getSource().equals(upButton)) {
}
if(evt.getSource().equals(methodDetailsButton)) {
}
}
}
}
The code compiles but the JTable does not show up.
Any pointers on what i may be doing wrong would be of great help.
Don't include another components to JTable. Let alone components with multiple other components. The reason is that JTable won't pass mouse events to its cells. So even when you have buttons inside JTable, then you would have to take care about pressing them by yourself, by:
get cell it was clicked to
get the exact coordinates
extrapolate these coordinates to the inner component
manually call click on the corresponding button.
And even then you won't get button animation and stuff.
If you need to arrange components into a table, use JPanel with GridLayout or GridBagLayout.