Can't drag to resize JTable columns - java

Long story short, I'm making a custom Swing component that's basically a JTable with a panel on its side. The table should of course be scrollable and have a table header, but since I only want the header to be above the actual JTable and not above the side panel, I had to pull some tricks to make it work. But that part works fine.
However, in the process I've somehow managed to break the mouse-drag-column-resizing functionality of the JTableHeader. I am completely clueless as to why and what I can do about it.
Below is a minimal working sample to illustrate my problem.
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import javax.swing.table.JTableHeader;
final class FooTable extends JPanel implements Scrollable {
public FooTable() {
initComponents();
}
// Generated by NetBeans IDE
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
sidePanel = new javax.swing.JPanel();
table = new javax.swing.JTable();
setLayout(new java.awt.GridBagLayout());
sidePanel.setMinimumSize(new java.awt.Dimension(70, 0));
sidePanel.setPreferredSize(new java.awt.Dimension(70, 0));
sidePanel.setLayout(null);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weighty = 1.0;
add(sidePanel, gridBagConstraints);
table.setFont(table.getFont().deriveFont(table.getFont().getSize()+1f));
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"1", "A", "I", "-"},
{"2", "B", "II", "--"},
{"3", "C", "III", "---"},
{"4", "D", "IV", "----"},
{"5", "E", "V", "-----"},
{"6", "F", "VI", "------"},
{"7", "G", "VII", "-------"},
{"8", "H", "VIII", "--------"},
{"9", "I", "IX", "---------"},
{"10", "J", "X", "----------"}
},
new String [] {
"Column 1", "Column 2", "Column 3", "Column 4"
}
));
table.setRowHeight(24);
table.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(table, gridBagConstraints);
}// </editor-fold>
public JScrollPane createScrollView() {
JScrollPane jsp = new JScrollPane(this);
JViewport jvp = new JViewport();
final JTableHeader th = new JTableHeader();
th.setTable(table);
th.setColumnModel(table.getColumnModel());
th.setResizingAllowed(true);
jvp.setView(new JPanel() {
{
setLayout(null);
add(th);
th.setLocation(70, 0);
FooTable.this.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
th.setSize(FooTable.this.getWidth(), th.getPreferredSize().height);
}
});
setPreferredSize(new Dimension(th.getPreferredSize().width, th.getPreferredSize().height));
}
});
jsp.setColumnHeader(jvp);
return jsp;
}
// Variables declaration - do not modify
private javax.swing.JPanel sidePanel;
private javax.swing.JTable table;
// End of variables declaration
//
// Scrollable implementation
//
public Dimension getPreferredScrollableViewportSize() {
Dimension d = new Dimension();
d.width = sidePanel.getPreferredSize().width + table.getPreferredSize().width;
d.height = sidePanel.getPreferredSize().height + table.getPreferredSize().height;
return d;
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return table.getScrollableUnitIncrement(visibleRect, orientation, direction);
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return table.getScrollableBlockIncrement(visibleRect, orientation, direction);
}
public boolean getScrollableTracksViewportWidth() {
return table.getScrollableTracksViewportWidth();
}
public boolean getScrollableTracksViewportHeight() {
return table.getScrollableTracksViewportHeight();
}
//
// Test program
//
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FooTable fooTable = new FooTable();
f.add(fooTable.createScrollView());
f.pack();
f.setVisible(true);
}
}

I think what you are missing is also telling the JTable about the JTableHeader. In the method createScrollView try adding the following just before returning:
table.setTableHeader(th);

Related

Unable to add keyListeners to buttons

I am trying to create a keyboard GUI with some basic functionalities. The problem that I am running into is within my draw(...){...} function, which highlights the addKeyListener() method, with the error:
The method addKeyListener(KeyListener) in the type Component is not applicable for the arguments (a3_keyboard)
Im not sure what I'm doing wrong. I tried changing my code up with,
getContentPane().addKeyListener(this);
for (JButton button : first) { button.addKeyListener(this); }
for (JButton button : second) { button.addKeyListener(this); }
for (JButton button : third) { button.addKeyListener(this); }
for (JButton button : fourth) { button.addKeyListener(this); }
for (JButton button : fifth) { button.addKeyListener(this); }
But that's throwing me the same error. Full code below:
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class a3_keyboard extends JFrame implements KeyListener {
//input
String input;
//default color
Color defaultColor = new JButton().getBackground();
//main rows of keys
private String rowOne[] = {
"~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "h"
};
private String rowTwo[] = {
"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"
};
private String rowThree[] = {
"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "'", "Enter"
};
private String rowFour[] = {
"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", " ^"
};
private String rowFive[] = {
" ", "<", "v", ">"
};
/** Account for chars with no shift:
** Program toggles Shift key, meaning
** if a user clicks on it, all keys will be
** toggled to their respective shift value. The
** user can tap the shift key again to
** change back to regular value */
private String shiftless[] = {
"1","2","3","4","5","6","7","8","9","0",
"-","=","q","w","e","r","t","y","u","i","o","p",
"[","]","\\","a","s","d","f","g","h","j","k","l",
";","z","x","c","v","b","n","m",",",".","/"
};
//Account for special chars
private String specialChars[] = {
"~", "-", "+", "[", "]", "\\", ";", ".", "?"
};
private JLabel context = new JLabel("Type some text using your keyboard. "
+ "The keys you press will be highlighed and the text will be displayed.\n "
+ "Note: Clicking the buttons with your mouse will not perform any action.")
.setFont(new Font("Verdana",Font.BOLD,14));
//declare rows of buttons
private JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
//ctor
public a3_keyboard() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000,600));
this.setLocation(50,50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
private void __init__body() {
JTextArea body = new JTextArea().setPreferredSize(new Dimension(600, 150));
}
public void __init__panels() {
JPanel top = new JPanel();
JPanel middle = new JPanel();
JPanel bottom = new JPanel();
JPanel contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5,1));
top.add(info, BorderLayout.WEST);
top.add(info, BorderLayout.SOUTH);
middle.setLayout( new BorderLayout());
middle.add(text, BorderLayout.WEST);
middle.add(text, BorderLayout.CENTER);
}
private void __init__() {
//text area
__init__body();
//panels for layout
__init__panels();
pack();
//get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
//create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
//create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
//draw out the rows of buttons
draw(
r1, length_rowOne,
r2, length_rowTwo,
r3, length_rowThree,
r4, length_rowFour,
r5, length_rowFive
);
}
//draw rows of buttons
public void draw(JPanel r1, int s1,
JPanel r2, int s2,
JPanel r3, int s3,
JPanel r4, int s4,
JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
buttons_rowOne[i].addKeyListener(this);
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
buttons_rowTwo[i].addKeyListener(this);
r1.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
buttons_rowThree[i].addKeyListener(this);
r1.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
buttons_rowFour[i].addKeyListener(this);
r1.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowOne[i]);
//account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400,10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
buttons_rowFive[i].addKeyListener(this);
}
r1.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
}//!draw(...)
//called when a button is pressed
#Override
public void activated(KeyEvent press) {
int index = press.getKeyCode();
input = String.format("%s", index);
}//!activated(...)
//called when a button is released
#Override
public void deactivated(KeyEvent release) {
int index = release.getKeyCode();
input = String.format( "%s"+KeyEvent.getKeyText(keyCode) );
this.setBackground(defaultColor);;
}//!deactivated(...)
//main method
public static void main(Strings[] args) {
new a3_keyboard();
}//!main method
//obtain the JButton’s original background colour before you change its colour
}//!main class
If Im missing something, please let me know and I'll add it to the question.
Edit:
New code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class a3_keyboard extends JFrame implements KeyListener {
//input
String input;
//input body
JTextArea body;
//panels
JPanel top, middle, bottom, contextBox = new JPanel();
//default color
Color defaultColor = new JButton().getBackground();
//main rows of keys
public String rowOne[] = {
"~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "h"
};
public String rowTwo[] = {
"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"
};
public String rowThree[] = {
"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "'", "Enter"
};
public String rowFour[] = {
"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", " ^"
};
public String rowFive[] = {
" ", "<", "v", ">"
};
/** Account for chars with no shift:
** Program toggles Shift key, meaning
** if a user clicks on it, all keys will be
** toggled to their respective shift value. The
** user can tap the shift key again to
** change back to regular value */
public String shiftless[] = {
"1","2","3","4","5","6","7","8","9","0",
"-","=","q","w","e","r","t","y","u","i","o","p",
"[","]","\\","a","s","d","f","g","h","j","k","l",
";","z","x","c","v","b","n","m",",",".","/"
};
//Account for special chars
public String specialChars[] = {
"~", "-", "+", "[", "]", "\\", ";", ".", "?"
};
//declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
//ctor
public a3_keyboard() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000,600));
this.setLocation(50,50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
JTextArea body = new JTextArea();
body.setPreferredSize(new Dimension(600, 150));
}
public void __init__panels() {
JLabel context = new JLabel("Type some text using your keyboard. "
+ "The keys you press will be highlighed and the text will be displayed.\n "
+ "Note: Clicking the buttons with your mouse will not perform any action.");
context.setFont(new Font("Verdana",Font.BOLD,14));
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5,1));
top.add(context, BorderLayout.WEST);
top.add(context, BorderLayout.SOUTH);
middle.setLayout( new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
//text area
__init__body();
//panels for layout
__init__panels();
pack();
//get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
//create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
//create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
//draw out the rows of buttons
draw(
r1, length_rowOne,
r2, length_rowTwo,
r3, length_rowThree,
r4, length_rowFour,
r5, length_rowFive
);
}
//draw rows of buttons
public void draw(JPanel r1, int s1,
JPanel r2, int s2,
JPanel r3, int s3,
JPanel r4, int s4,
JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
buttons_rowOne[i].addKeyListener(this);
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
buttons_rowTwo[i].addKeyListener(this);
r1.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
buttons_rowThree[i].addKeyListener(this);
r1.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
buttons_rowFour[i].addKeyListener(this);
r1.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowOne[i]);
//account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400,10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
buttons_rowFive[i].addKeyListener(this);
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
buttons_rowFive[i].addKeyListener(this);
}
r1.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
}//!draw(...)
// called when a button is pressed
#Override
public void keyPressed(KeyEvent pressed) {
JButton current = (JButton) pressed.getSource();
current.setBackground(Color.GRAY);
body.append(toString(current.getKeyChar()));
}//!keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent released) {
JButton current = (JButton) released.getSource();
current.setBackground(defaultColor);
}//!keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
JButton current = (JButton) typed.getSource();
}
//main method
public static void main(String[] args) {
new a3_keyboard();
}//!main method
private static final long serialVersionUID = 999;
}//!main class
Edit 2:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class ButtonInPane extends JFrame implements KeyListener {
//redacted, see below
#Override
public void keyPressed(KeyEvent press) {
JButton current = (JButton) press.getSource();
current.setBackground(Color.GRAY);
StringBuilder sb = new StringBuilder();
sb.append(press.getKeyChar());
body.append(sb.toString());
} // !keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent release) {
JButton current = (JButton) release.getSource();
current.setBackground(defaultColor);
} // !keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
JButton current = (JButton) typed.getSource();
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
Edit 3:
#Override
public void keyPressed(KeyEvent press) {
Object current = press.getSource().toString();
for (int i = 0; i < 14; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.GRAY);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.GRAY);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.GRAY);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.GRAY);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.GRAY);
}
}
} // !keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource().toString();
for (int i = 0; i < 14; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
}
}
} // !keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
This version puts the keylistener on the correct component. However you now need to redesign this given your new understanding...
Because as the code is right now, the jtext area body simply gets a repeat of the key as you press them. There are several ways you could solve this.
Some of the brute force and others more intricate but elegant. Ping me if you still want help.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
// main rows of keys
public String rowOne[] = {
"~",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"h"
};
public String rowTwo[] = {
"Tab",
"Q",
"W",
"E",
"R",
"T",
"Y",
"U",
"I",
"O",
"P",
"[",
"]",
"\\"
};
public String rowThree[] = {
"Caps",
"A",
"S",
"D",
"F",
"G",
"H",
"J",
"K",
"L",
":",
"'",
"Enter"
};
public String rowFour[] = {
"Shift",
"Z",
"X",
"C",
"V",
"B",
"N",
"M",
",",
".",
"?",
" ^"
};
public String rowFive[] = {
" ",
"<",
"v",
">"
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public String shiftless[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"=",
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
};
// Account for special chars
public String specialChars[] = {
"~",
"-",
"+",
"[",
"]",
"\\",
";",
".",
"?"
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(2000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(600, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 1));
top.add(context2);
top.add(context1);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
#Override
public void keyPressed(KeyEvent press) {
StringBuilder sb = new StringBuilder();
sb.append(press.getKeyChar());
body.append(sb.toString());
} // !keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource();
} // !keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
Object current = typed.getSource();
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class

JTable not honoring cell renderer's necessary height

This should be simple, but I can't figure out what is going wrong. I need my table to display with a fairly large font size but the table painter is not honoring the height of the cell renderer.
I've seen this post and it's working brilliantly for when my preferences window has been given a changed font size. But although the renderer knows what font size to use, the table on initial display is using the standard row height (16). Surely the table painter should automatically take into account the preferred height of the renderer? Or do I actually have to manually tell it what height to use?
I've tried a call to doLayout() as shown below, but it doesn't make any difference.
Here's an SSCCE to demonstrate the problem:
public class IncorrectRowHeight extends JPanel
{
private class MyCellRenderer extends JTextField implements TableCellRenderer
{
private MyCellRenderer()
{
setFont(new Font("SansSerif", Font.PLAIN, 30));
setBorder(BorderFactory.createEmptyBorder());
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
setText(value.toString());
return this;
}
}
public IncorrectRowHeight()
{
super(new BorderLayout());
add(new JTextField(25), BorderLayout.PAGE_START);
String[][] data = {
{"a", "b", "c", "d", "e"},
{"f", "g", "h", "i", "j"},
{"k", "l", "m", "n", "o"},
{"p", "q", "r", "s", "t"}
};
String[] cols = {"h1", "h2", "h3", "h4", "h5"};
JTable t = new JTable(data, cols);
t.setGridColor(Color.GRAY);
t.setPreferredScrollableViewportSize(new Dimension(300, 65));
TableColumnModel model = t.getColumnModel();
for (int i = 0; i < model.getColumnCount(); i++)
{
TableColumn column = model.getColumn(i);
column.setCellRenderer(new MyCellRenderer());
}
JScrollPane scroller = new JScrollPane(t);
add(scroller, BorderLayout.CENTER);
//t.doLayout(); // doesn't help matters
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("IncorrectRowHeight");
JComponent newContentPane = new IncorrectRowHeight();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
It produces the following:
This ain't rocket science! What am I doing wrong?
Probably this method help you
public static void updateRowHeight(JTable table, int margin) {
final int rowCount = table.getRowCount();
final int colCount = table.getColumnCount();
for (int i = 0; i < rowCount; i++) {
int maxHeight = 0;
for (int j = 0; j < colCount; j++) {
final TableCellRenderer renderer = table.getCellRenderer(i, j);
maxHeight = Math.max(maxHeight, table.prepareRenderer(renderer, i, j).getPreferredSize().height);
}
table.setRowHeight(i, maxHeight + margin);
}
}
Use this method after the table is populated with the data. margin parameter is used for additional increment of row height. If not required - use 0.
Here is your example with the correct cell height.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
/**
* <code>IncorrectRowHeight</code>.
*/
public class IncorrectRowHeight extends JPanel {
private class MyCellRenderer extends JTextField implements TableCellRenderer {
private MyCellRenderer() {
setFont(new Font("SansSerif", Font.PLAIN, 30));
setBorder(BorderFactory.createEmptyBorder());
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
setText(value.toString());
return this;
}
}
public IncorrectRowHeight() {
super(new BorderLayout());
add(new JTextField(25), BorderLayout.PAGE_START);
String[][] data = {{"a", "b", "c", "d", "e"}, {"f", "g", "h", "i", "j"}, {"k", "l", "m", "n", "o"}, {"p", "q", "r", "s", "t"}};
String[] cols = {"h1", "h2", "h3", "h4", "h5"};
JTable t = new JTable(data, cols);
t.setGridColor(Color.GRAY);
t.setPreferredScrollableViewportSize(new Dimension(300, 65));
TableColumnModel model = t.getColumnModel();
for (int i = 0; i < model.getColumnCount(); i++) {
TableColumn column = model.getColumn(i);
column.setCellRenderer(new MyCellRenderer());
}
updateRowHeight(t, 0);
JScrollPane scroller = new JScrollPane(t);
add(scroller, BorderLayout.CENTER);
}
public static void updateRowHeight(JTable table, int margin) {
final int rowCount = table.getRowCount();
final int colCount = table.getColumnCount();
for (int i = 0; i < rowCount; i++) {
int maxHeight = 0;
for (int j = 0; j < colCount; j++) {
final TableCellRenderer renderer = table.getCellRenderer(i, j);
maxHeight = Math.max(maxHeight, table.prepareRenderer(renderer, i, j).getPreferredSize().height);
}
table.setRowHeight(i, maxHeight + margin);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("IncorrectRowHeight");
JComponent newContentPane = new IncorrectRowHeight();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Use table.setRowHeight(table.getFontMetrics(font).getHeight());
package com.logicbig.example;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
public class IncorrectRowHeight extends JPanel {
private static final Font font = new Font("SansSerif", Font.PLAIN, 30);
private class MyCellRenderer extends JTextField implements TableCellRenderer {
private MyCellRenderer() {
setFont(font);
setBorder(BorderFactory.createEmptyBorder());
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setText(value.toString());
return this;
}
}
public IncorrectRowHeight() {
super(new BorderLayout());
add(new JTextField(25), BorderLayout.PAGE_START);
String[][] data = {
{"a", "b", "c", "d", "e"},
{"f", "g", "h", "i", "j"},
{"k", "l", "m", "n", "o"},
{"p", "q", "r", "s", "t"}
};
String[] cols = {"h1", "h2", "h3", "h4", "h5"};
JTable t = new JTable(data, cols);
t.setRowHeight(t.getFontMetrics(font).getHeight());
t.setGridColor(Color.GRAY);
t.setPreferredScrollableViewportSize(new Dimension(300, 65));
TableColumnModel model = t.getColumnModel();
for (int i = 0; i < model.getColumnCount(); i++) {
TableColumn column = model.getColumn(i);
column.setCellRenderer(new MyCellRenderer());
}
JScrollPane scroller = new JScrollPane(t);
add(scroller, BorderLayout.CENTER);
//t.doLayout(); // doesn't help matters
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("IncorrectRowHeight");
JComponent newContentPane = new IncorrectRowHeight();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

JTable multiple Row header

The SSSCE for the problem i face is posted below
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
public class TableTest extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel panel;
private JPanel buttonPanel;
private JTable table;
private JTable headerTable;
JButton cancelButton;
private DefaultTableModel tableModel;
private DefaultTableModel headerTableModel;
String fileName = null;
public TableTest() {
init();
}
public void init() {
setTitle("Table");
//Panel
panel = new JPanel();
panel.setLayout(new GridBagLayout());
this.getContentPane().add(panel);
buttonPanel = new JPanel();
//cancel button
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
buttonPanel.add(cancelButton);
String[] headerNames = {"", "Col 1", "Col 2", "Col 1", "Col 2"};
String[] mainHeaderNames = {"Header 1", "Header2"};
headerTableModel = new DefaultTableModel();
for (int i = 0; i < mainHeaderNames.length; i++) {
headerTableModel.addColumn(mainHeaderNames[i]);
}
//table model
tableModel = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column) {
if(column == 0){
return true;
} else {
return false;
}
}
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Boolean.class;
}
return null;
}
};
//set default model to the table
table = new JTable(tableModel);
headerTable = new JTable(headerTableModel);
// set table header
for (int col = 0; col < headerNames.length; col++) {
tableModel.addColumn(headerNames[col]);
}
//set table dimensions
int height = 0;
int width = 1000;
if(tableModel.getRowCount() < 20) {
height = tableModel.getRowCount()*16;
} else {
height = 350;
}
table.setPreferredScrollableViewportSize(new Dimension(width, height));
//table header column width and height
table.getTableHeader().setPreferredSize(new Dimension(100,28));
headerTable.getTableHeader().setPreferredSize(new Dimension(100,28));
//Set the width for column
DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
colModel.setColumnSelectionAllowed(false);
colModel.getColumn(0).setPreferredWidth(5);
colModel.getColumn(1).setPreferredWidth(300);
colModel.getColumn(2).setPreferredWidth(200);
colModel.getColumn(3).setPreferredWidth(300);
colModel.getColumn(4).setPreferredWidth(200);
//table setting
table.setFillsViewportHeight(true);
headerTable.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
//The header of column should be fixed.If set to true - columns can be re-arranged
table.getTableHeader().setReorderingAllowed(false);
headerTable.getTableHeader().setReorderingAllowed(false);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane headerScrollPane = new JScrollPane(headerTable);
headerScrollPane.setPreferredSize(new Dimension(100,28));
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
//Add the scroll pane to this panel.
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
panel.add(headerScrollPane, c);
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
panel.add(scrollPane, c);
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 2;
c.weightx = 0;
c.weighty = 0;
panel.add(buttonPanel, c);
addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
int option = JOptionPane.showConfirmDialog(panel, "Do you want to close this window?", " Confirm" , JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
dispose();
} else {
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
});
//Display the window.
if(tableModel.getRowCount() >= 0){
pack();
setAlwaysOnTop(true);
setLocationRelativeTo(this);
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run(){
new TableTest();
}
});
}
}
Am using two JTables here ,
I am tryin to implement like , if i move split between header 1 and header 2 the respective split line in below table also should be moved.
Since am using two jTables i am not sure how can i achieve this. Or is there any other way to this am new to java please help.
Your layout is wrong. Try to make a layout like this:

Change JCombobox popup width [duplicate]

This question already has answers here:
How can I change the width of a JComboBox dropdown list?
(7 answers)
Closed 8 years ago.
How can I set a fixed width of a JComboboxs popup-menu that is using GridBagLayout and fill=HORIZONTAL?
One of the things I tried is to just override the getSize() method but dose not work.
public class ComboBoxSize extends JFrame {
public static void main(String args[]) {
// THE COMBOBOX
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
JComboBox<String> comboBox = new JComboBox<String>(labels) {
public Dimension getSize() {
Dimension d = getPreferredSize();
d.width = 50;
return d;
}
};
comboBox.setMaximumRowCount(comboBox.getModel().getSize());
// ADD COMBOBOX TO PANEL
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(comboBox, c);
// ADD PANEL TO FRAME
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Here is the solution, this worked for me, add this PopupMenuListener to your JComboBox:
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.ComboPopup;
public class CustomComboBoxPopupMenuListener implements PopupMenuListener {
// ==============================================================================
// Members
// ==============================================================================
private int bgTop = 0;
private int bgLeft = 0;
private int bgRight = 0;
private int bgBottom = 0;
// ==============================================================================
// Constructors
// ==============================================================================
public CustomComboBoxPopupMenuListener() {
super();
}
// ==============================================================================
// Methods
// ==============================================================================
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
final JComboBox box = (JComboBox) e.getSource();
final Object comp = box.getUI().getAccessibleChild(box, 0);
if (!(comp instanceof JPopupMenu)) {
return;
}
final JPopupMenu popupMenu = (JPopupMenu) comp;
popupMenu.setBorder(null);
if (popupMenu.getComponent(0) instanceof JScrollPane) {
final JScrollPane scrollPane = (JScrollPane) popupMenu
.getComponent(0);
scrollPane.setBorder(BorderFactory.createEmptyBorder(bgTop, bgLeft,
bgBottom, bgRight));
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
if (popupMenu instanceof ComboPopup) {
final ComboPopup popup = (ComboPopup) popupMenu;
final JList list = popup.getList();
list.setBorder(null);
final Dimension size = list.getPreferredSize();
size.width = Math.max(box.getPreferredSize().width + bgLeft
+ bgRight, box.getWidth());
size.height = Math.min(scrollPane.getPreferredSize().height
+ bgTop + bgBottom, size.height + bgTop + bgBottom);
scrollPane.setPreferredSize(size);
scrollPane.setMaximumSize(size);
}
}
}
}
Example in your code:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ComboBoxSize extends JFrame {
public static void main(String args[]) {
// THE COMBOBOX
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
JComboBox<String> comboBox = new JComboBox<String>(labels);
comboBox.setMaximumRowCount(comboBox.getModel().getSize());
comboBox.addPopupMenuListener(new CustomComboBoxPopupMenuListener());
// ADD COMBOBOX TO PANEL
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(comboBox, c);
// ADD PANEL TO FRAME
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Source: click here

How to get proper alignment of Title border over the Jtable

Im trying to build small application in java swings. I started using this link: Creating a Grid in Java.
Everything was good. I finished that task but onething is left that I'm trying to remove extra title border. I tried to reduce the border of title border still its not affect. Any one with good suggestion try to share with me.
package swings.application.framework;
import java.awt.*;
import java.awt.event.ActionEvent
;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Inf3rNix
*/
public class KidsProblemTable {
private static JButton okbtn;
private static JFrame frame;
public static void main(String[] args) {
Runnable runner = new Runnable() {
#Override
public void run() {
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Kids Table");
Border border = LineBorder.createGrayLineBorder();
frame.setLayout(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
JLabel Heading = new JLabel("My Result");
Heading.setFont(new Font("Gabriola", Font.ITALIC, 56));
Heading.setForeground(Color.BLUE);
Heading.setBounds(550, -60, 300, 200);
JLabel Heading2 = new JLabel("Nice Job! Here are your results...");
Heading2.setFont(new Font("Buxton Sketch", Font.ITALIC, 26));
Heading2.setForeground(Color.BLUE);
Heading2.setBounds(500, 10, 600, 200);
JLabel Heading3 = new JLabel();
String str = "You got 5 correct answer out of 7 question";
Heading3.setText("<html><a href=' ' style='color:rgb(248,116,49);'>" + str + "</a></html>");
Heading3.setFont(new Font("Andy", Font.PLAIN, 20));
Heading3.setBounds(500, 70, 600, 200);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
Border border1 = BorderFactory.createTitledBorder("Exercise");
panel1.setBounds(150, 200, 1000, 190);
String column = "Questions".toUpperCase();
// AttributedString as = new AttributedString(column);
// Font plainFont = new Font("Times New Roman", Font.PLAIN, 24);
// as.addAttribute(TextAttribute.FONT, plainFont);
// as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON,0,8 );
String column1 = "Problem".toUpperCase();
String column2 = "Answer".toUpperCase();
String column3 = "Answer".toUpperCase();
String results = "results".toUpperCase();
Object rowData[][] = {{"1", "3+9", "12", "12", "Correct !"},
{"2", "4+3", "7", "7", "Correct !"},
{"3", "10+8", "17", "18", "Sorry :("},
{"4", "5+1", "6", "6", "Correct !"},
{"5", "10+8", "18", "18", "Correct !"},
{"6", "8+2", "10", "10", "Correct !"},
{"7", "5+6", "4", "11", "Sorry :("}
};
Object columnNames[] = {column, column1, column2, column3, results};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tb1 = new JTable(model) {
//when checking if a cell is editable always return false
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
//JTable table1 = new JTable(rowData, columnNames1);
tb1.setBackground(Color.getHSBColor(153, 0, 91));
JScrollPane scrollPane1 = new JScrollPane(tb1);
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
// ImageIcon icon = createImageIcon("images/wavy.gif", "wavy-line border icon");
okbtn=new JButton("Press Ok to Exit");
okbtn.setBorder(raisedbevel);
okbtn.setFont(new Font("Vani", Font.BOLD, 12));
okbtn.setBounds(575, 390, 150, 50);
panel2.add(scrollPane1, BorderLayout.CENTER);
okbtn.addActionListener(new buttonActionListener());
frame.add(Heading);
frame.add(Heading2);
frame.add(Heading3);
frame.add(okbtn);
frame.add(panel1);
panel2.setBorder(border1);
panel1.add(panel2);
frame.setSize(500, 500);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
private static class buttonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==okbtn){
JOptionPane.showMessageDialog(null, "All the best !!!");
WindowEvent winClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
}
}
}
}
maybe
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Inf3rNix
*/
public class KidsProblemTable {
private JFrame frame;
private JPanel panel1 = new JPanel();
private JLabel Heading = new JLabel("My Result", JLabel.CENTER);
private JLabel Heading2 = new JLabel("Nice Job! Here are your results...", JLabel.CENTER);
private JLabel Heading3 = new JLabel();
private String str = "You got 5 correct answer out of 7 question";
private JPanel panel2 = new JPanel();
private JButton okbtn;
private Object rowData[][] = {{"1", "3+9", "12", "12", "Correct !"},
{"2", "4+3", "7", "7", "Correct !"},
{"3", "10+8", "17", "18", "Sorry :("},
{"4", "5+1", "6", "6", "Correct !"},
{"5", "10+8", "18", "18", "Correct !"},
{"6", "8+2", "10", "10", "Correct !"},
{"7", "5+6", "4", "11", "Sorry :("}
};
private String column = "Questions".toUpperCase();
private String column1 = "Problem".toUpperCase();
private String column2 = "Answer".toUpperCase();
private String column3 = "Answer".toUpperCase();
private String results = "results".toUpperCase();
private Object columnNames[] = {column, column1, column2, column3, results};
private DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
private JTable tb1 = new JTable(model) {
private static final long serialVersionUID = 1L;
//when checking if a cell is editable always return false
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
private JScrollPane scrollPane1 = new JScrollPane(tb1);
public KidsProblemTable() {
Border border1 = BorderFactory.createTitledBorder("Exercise");
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
tb1.setBackground(Color.getHSBColor(153, 0, 91));
tb1.setPreferredScrollableViewportSize(tb1.getPreferredSize());
Heading.setFont(new Font("Gabriola", Font.ITALIC, 56));
Heading.setForeground(Color.BLUE);
Heading2.setFont(new Font("Buxton Sketch", Font.ITALIC, 26));
Heading2.setForeground(Color.BLUE);
Heading3.setText("<html><a href=' ' style='color:rgb(248,116,49);'>" + str + "</a></html>");
Heading3.setFont(new Font("Andy", Font.PLAIN, 20));
panel1.setLayout(new GridLayout(3, 1));
panel1.add(Heading);
panel1.add(Heading2);
panel1.add(Heading3);
// ImageIcon icon = createImageIcon("images/wavy.gif", "wavy-line border icon");
okbtn = new JButton(" Press Ok to Exit ");
okbtn.setBorder(raisedbevel);
okbtn.setFont(new Font("Vani", Font.BOLD, 12));
okbtn.addActionListener(new buttonActionListener());
panel2.add(okbtn);
panel2.setBorder(border1);
frame = new JFrame("Kids Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1, BorderLayout.NORTH);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.SOUTH);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
private class buttonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == okbtn) {
JOptionPane.showMessageDialog(null, "All the best !!!");
WindowEvent winClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
}
}
public static void main(String[] args) {
Runnable runner = new Runnable() {
#Override
public void run() {
new KidsProblemTable();
}
};
EventQueue.invokeLater(runner);
}
}
I found your problem,
You added the scrollPane to panel2 as
panel2.add(scrollPane1, BorderLayout.CENTER);
but you didn't setLayout as BorderLayout for panel2.
and you set the Layout of panel1 as null
see this code
JPanel panel1 = new JPanel();
panel1.setLayout(null);//add to your code
JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout());//add to your code
panel2.setBounds(0,0,800,120);//add to your code
out put:
may this image will remove after some hours
out put image

Categories

Resources