I have a JTable and I want to make a tic tac toe themed table. I have managed to get rid of three borders without really knowing how...
Here's my code:
public class Table extends JPanel {
public static void main( String[] args ) {
JFrame jFrame = new JFrame();
JTable table = new JTable(3, 3);
table.setBounds(90, 20, 200, 200);
for(int i = 0; i < 3; i++) {
table.setRowHeight(i, 67);
}
table.setBackground(Color.black);
table.setGridColor(Color.white);
table.setForeground(Color.white);
// content pane so I can set the background
jFrame.getContentPane().add(table);
jFrame.getContentPane().setBackground(Color.black);
jFrame.setSize(400, 400);
jFrame.setLayout(null);
jFrame.setVisible(true);
}
}
I also have some stuff that initializes the table more like setting values but I don't think that will matter but I can add it if you want. So how could I get the right border of the table to disappear too?
When I compile this code, the top, left and bottom borders are not visible
You can usesetBorder method with a LineBorder in order to fill it:
table.setGridColor(Color.white);
table.setBorder(BorderFactory.createLineBorder(table.getGridColor()));
By the way, setLayout(null) and setBounds is a bad practice that is going to give you hard time in the future (plus it is not user-friendly, since you cannot resize your frame and won't work in different screen sizes). Try to use LayoutManagers and let them do the work for you.
Also, take a look at initial threads. All swing applications should run on their own thread and not in the main thread.
Related
I know that absolute positioning is not recommended, but I need to show my labels randomly scattered as well as randomly changing their positions.
I have researched how to use setBounds but it doesn't seem to work. The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.
public class GUI extends JFrame{
device mobiles[];
device station;
JPanel pane= new JPanel();
public GUI()
{
setTitle("communication is Key");
setSize(1000, 1000);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane.setBackground(Color.WHITE);
int x=0; int y=0;
mobiles= new device[10];
for (int i = 0; i < 10; i++) {
x=randInt();
y=randInt();
mobiles[i]= new device(1,x,y);
pane.add(mobiles[i]);
}
x=randInt();
y=randInt();
station = new device(0,x,y);
pane.add(station);
this.add(pane);
}
and this is class "devices" that extends JLabel
public class device extends JLabel{
ImageIcon mob = new ImageIcon("mob.png");
ImageIcon tow = new ImageIcon("tower.png");
public device(int num, int x, int y)
{ if(num==1)
this.setIcon(mob);
else this.setIcon(tow);
this.setBounds(x, y, 3, 7);
}
}
any help in finding out what the problem is, would be be appreciated.
The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.
The layout manager sets the size and location of the component.
If you don't use the layout manager, then you are responsible for set the size and location of each component.
Typically I would set the size to equal to the components preferred size.
Also, did you display the x/y value that are randomly generated? Maybe the values are larger than the size of the panel.
and when I use setLayout(null) it shows a blank frame.
What layout is set to null? The panel of the frame. Your code doesn't use the above method. Post the code that you use to cause the problem. We don't want to guess what you may or may not be doing.
thanks to #CasparNoree ... the answer suggested was to initialize the Japnel from the start:
JPanel pane = new JPanel(null);
When you set the layout to null you can set the bounds manually with coordinates.
JFrame jf = new JFrame();
JPanel p = new JPanel();
JButton jb = new JButton();
// this is where you make it so setting the bounds actually does something
p.setLayout(null);
jb.setBounds(100,100,100,100);
p.add(jb);
jf.add(p);
jf.setVisible(true);
UPDATE: I have received justified criticism for posting non working code. I've taken that to heart and am updating this post with a complete working example. I'm also updating the description accordingly:
I have a very simple java swing GUI whose components take up what looks to be an equal amount of vertical (Y) space as is used by the largest Y extent component, but completely unnecessarily so. I have tried to shrink those components that don't need that much vertical space using preferredSize hints but to no avail.
The basic layout is simple: There's a main window and three vertical panels. The layout is a simple GridLayout (and I would prefer to keep it that way, unless someone shows me what I need cannot be done with GridLayout). All three panels seem to be occupying the same amount of vertical space, even though in the case of the sliders, this is massive waste of space. How can I get each of the sub-panes to only use as much space as they each need? i.e. I would like the two slider windows to be only as tall as the sliders and their description need to be.
The code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class test {
public static void main(String[] arg) {
JFrame mainWindow = new JFrame();
JSlider slider1 = new JSlider(0,100,50);
JSlider slider2 = new JSlider(0,100,50);
JPanel pnlSlider1 = new JPanel();
pnlSlider1.setLayout(new GridLayout(1,1)); // 1 row, 1 column
pnlSlider1.add(new JLabel("Description for slider1"));
pnlSlider1.add(slider1);
JPanel pnlSlider2 = new JPanel();
pnlSlider2.setLayout(new GridLayout(1,1)); // 1 row, 1 column
pnlSlider2.add(new JLabel("Description for slider2"));
pnlSlider2.add(slider2);
// label should now be to the left of slider
String content = "<html>Some rather long winded HTML content</html>";
JEditorPane ep = new JEditorPane("text/html", content);
// this is the main window panel
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1)); // 3 rows, 1 column
panel.add(ep);
panel.add(pnlSlider1);
panel.add(pnlSlider2);
// tie it all together and display the window
mainWindow.setPreferredSize(new Dimension(300, 600));
mainWindow.setLocation(100, 100);
mainWindow.getContentPane().add(panel);
mainWindow.pack();
mainWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
mainWindow.setVisible(true);
}
}
(removed rant about not having seen any GUI coding advances in 30 years as that's not pertinent to the problem and likely won't be solved in this post either)
..components take up what looks to be an equal amount of vertical (Y) space as is used by the largest Y extent component, but completely unnecessarily so.
Yes, that is the way GridLayout is designed to work.
Use a GridBagLayout or BoxLayout or GroupLayout instead, each of which can do a single column or row of components of variable size (width and height).
Basically all I want to do is draw two rows of buttons for a lights out game (homework), but I don't know how to make both panels show up. I've pretty much almost no graphics before, and I don't really understand anything I'm doing.
The panels them selves work, but it just shows whichever I add second (I assume it's overwriting the previous panel)
public static void main(String[] args) {
String nButtonsString = JOptionPane.showInputDialog("How many buttons would you like?");
int nButtons = Integer.parseInt(nButtonsString);
JFrame myFrame = new JFrame();
myFrame.setTitle("Linear Lights Out Game.");
myFrame.setSize(FRAME_SIZE);
JPanel control_buttons = new Linear_Controls();
myFrame.add(control_buttons);
JPanel lights = new LinearLightsPanel(nButtons);
myFrame.add(lights);
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.add(control_buttons);
myFrame.add(lights);
By default a JFrame uses a BorderLayout. Also, by default components get added to the CENTER of the BorderLayout. However the CENTER can only contain a single component so only the last component added is displayed. Try:
myFrame.add(control_buttons, BorderLayout.NORTH);
Now the two components should show up.
Read the section from the Swing tutorial on Using Layout Managers for more information and examples. Also take a look at the Trail/Table of Contents link to see other useful topics for basic Swing usage.
You have to create the 2 panels A and B and add them to another panel C. Then you add C to your frame.
A bit better explained: This is what you have now:
JPanel lights = new LinearLightsPanel(nButtons);
myFrame.add(lights);
But you would like something like:
JPanel lightsA = new LinearLightsPanel(nButtonsA);
JPanel lightsB = new LinearLightsPanel(nButtonsB);
JPanel lightsC = new JPanel();
lightsC.add(lightsA);
lightsC.add(lightsB);
myFrame.add(lightsC);
I'm developing a Java GUI and I need:
A label in first row(only one label).
Starting 2nd row need to add say 100 buttons which extends to multiple lines(width shouldn't go beyond the visible screen)
In a new line one more Label
From next line say 100 buttons which extends to multiple lines(width shouldn't go beyond the visible screen)...
[OPTIONAL] If the components exceeds JFrame height then need a scroll facility to the main window (only vertical)
I have a strange results with flow layout, sometimes it stick to visible width, sometimes it sets even 500 buttons in a single row.
I have tried every layout and also multipanes. Still no luck.
Please guide.. just need an idea, No need of code
Updated with code: Sorry guys, that was my first question to stackoverflow
Thanks for prompt response
Infact i tried many, here is a simple one.
setLayout(new FlowLayout());
setTitle("JAVA GUI");
setSize(500,500);
setVisible(true);
add(new JLabel("row 1"));
JPanel panel1 = new JPanel(new FlowLayout());
for(int i=0;i<200;i++){
panel1.add(new JButton("b"+i));
}
add(panel1);
Here the panel1 is appearing in a sigle row which goes beyond the visible part of the screen.
I think this can be solved by setting maximumsize to Jframe, but no idea how to set its size to FULL SCREEN.
You can try MigLayout.
http://www.miglayout.com/
Also this question is not really a question for stack overflow. A good way to ask your question would be to post your code and tell us what is wrong with it and what it is supposed to do.
While this is not the norm for 'good' stackOverflow questions, I don't have any problem with it myself. Some people cannot deal with anything except code. I would suggest that, if you're going to post code, that you take the trouble to post code that will compile, run, and demonstrate your situation. It really helps those of us out here understand what you're seeing and what you're trying to do.
You talk about "rows"; be aware that rows and columns are terms used with things like GridLayout and GridBagLayout, but I don't think they're appropriate for what you describe.
In your description, you don't say what you want scrolled. It would appear you want the entirety of the UI scrolled, I'll assume that for now.
I would try a JPanel with BoxLayout, oriented vertically, for the overall main UI. You will put some things into that:
The first JPanel.
Another JPanel, set with FlowLayout, holding the first bunch of buttons.
Another JPanel with the next JLabel
And a fourth JPanel, set with FlowLayout, holding the second bunch of buttons.
Now, I would put the top-level panel into a JScrollPane, and then put that into the CENTER section of a Frame (with its default BorderLayout), and see what happens. To tell the truth, I'm not sure, but these are the things I would start with.
I cannot tell, without running code, why you get odd behavior sometimes.
As said in a previous comment, using a ContentPane is the way to go. Here is a working example of what you want:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("JAVA GUI");
JPanel panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
int nbLines = 10;
for (int i = 0; i < nbLines; i++) {
JPanel linePanel = new JPanel(new FlowLayout());
linePanel.add(new JLabel("row " + i));
for(int j = 0; j < 50; j++) {
linePanel.add(new JButton("b" + j));
}
panel1.add(linePanel);
}
frame.setContentPane(panel1);
//frame.setSize(500, 500);
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
frame.pack();
frame.setVisible(true);
}
}
And here is what I get:
If you want to have left-aligned buttons you can use:
JPanel linePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
I currently have the code below.
public class cRunningView extends JInternalFrame {
static final int xOffset = 30, yOffset = 30;
public cRunningView() {
// Get name;
super("RUNNING", true, // resizable
false, // closable
true, // maximizable
true);// iconifiable
System.out.println("##" + "p.getName()");
// ...Then set the window size or call pack...
setSize(500, 200);
// Set the window's location.
setLocation(xOffset * 0, yOffset * 0);
JScrollPane scrollPane = new JScrollPane();
}
}
My aim is to have a JInternalFrame with a number of buttons and a box/rectangle on half of the screen.
Within this box i want to be able to draw graphics for e.g. Draw oval from x,y to x,y.
I've tried looking at examples but see to get my self more confused than i did to begin. All my code is working e.g. Showing the main GUI window and my internal frame opening but i cant seem to find a good tutuirol/starting point to do graphics within a JScrollPane.
Please note i dont have to use a JScrollPane i just thought i would be a good idea cause it would give the graphics a border round it.
Before anyone moans about the question i think it is valid AND I DONT want the code to be given to me on a plate, i'd rather know and understand what im doing so i can advance my knowledge and be able to help others !
Do i have to make another class and do
JScrollPane myPane = JScrollPane(graphicsClass)
then do everything with paint() then or is there someway to create a graphic and do it without another class?
If i do :
JScrollPane scrollPane = new JScrollPane();
Graphics temp = scrollPane.getGraphics();
temp.setColor(new Color(1, 22, 33));
temp.fillOval(60, 0, 120, 60);
scrollPane.paint(temp);
It throws errors.
Thanks
You don't do Graphics in a scrollpane. Also, don't use the getGraphics() method to do custom painting.
Custom painting is done by overriding the paintComponent() method of a JPanel or JComponent. Then if required you can add the panel to a scrollpane and add the scrollpane to your frame. Don't forget to set the preferred size of the panel so scrolling will work.
Start by reading the Swing tutorial on Custom Painting.